diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index 150328ff7..f8ccffdd0 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -299,7 +299,7 @@ android { } } - defaultConfig.versionCode = 2406 + defaultConfig.versionCode = 2428 applicationVariants.all { variant -> variant.outputs.all { output -> @@ -318,7 +318,7 @@ android { defaultConfig { minSdkVersion 16 targetSdkVersion 29 - versionName "8.0.0" + versionName "8.0.1" vectorDrawables.generatedDensities = ['mdpi', 'hdpi', 'xhdpi', 'xxhdpi'] diff --git a/TMessagesProj/jni/CMakeLists.txt b/TMessagesProj/jni/CMakeLists.txt index f433bb352..dbd537a5e 100644 --- a/TMessagesProj/jni/CMakeLists.txt +++ b/TMessagesProj/jni/CMakeLists.txt @@ -1,11 +1,11 @@ cmake_minimum_required(VERSION 3.6.0) -set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID") -set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1") +set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID -g") +set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1 -g") set(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections") -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections -Wl,--exclude-libs,libtgvoip.a,libtgcalls.a,libtgcalls_tp.a,libtgnet.a,liblz4.a,libwebp.a,libflac.a,librlottie.a,libsqlite.a, +set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--exclude-libs,libtgvoip.a,libtgcalls.a,libtgcalls_tp.a,libtgnet.a,liblz4.a,libwebp.a,libflac.a,librlottie.a,libsqlite.a, ${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libswscale.a, ${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavformat.a, ${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavcodec.a, diff --git a/TMessagesProj/jni/TgNetWrapper.cpp b/TMessagesProj/jni/TgNetWrapper.cpp index 934cf2873..f6d5de04c 100644 --- a/TMessagesProj/jni/TgNetWrapper.cpp +++ b/TMessagesProj/jni/TgNetWrapper.cpp @@ -190,7 +190,7 @@ jint getConnectionState(JNIEnv *env, jclass c, jint instanceNum) { return ConnectionsManager::getInstance(instanceNum).getConnectionState(); } -void setUserId(JNIEnv *env, jclass c, jint instanceNum, int32_t id) { +void setUserId(JNIEnv *env, jclass c, jint instanceNum, int64_t id) { ConnectionsManager::getInstance(instanceNum).setUserId(id); } @@ -371,7 +371,7 @@ void setSystemLangCode(JNIEnv *env, jclass c, jint instanceNum, jstring langCode } } -void init(JNIEnv *env, jclass c, jint instanceNum, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring systemLangCode, jstring configPath, jstring logPath, jstring regId, jstring cFingerprint, jstring installerId, jstring packageId, jint timezoneOffset, jint userId, jboolean enablePushConnection, jboolean hasNetwork, jint networkType) { +void init(JNIEnv *env, jclass c, jint instanceNum, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring systemLangCode, jstring configPath, jstring logPath, jstring regId, jstring cFingerprint, jstring installerId, jstring packageId, jint timezoneOffset, jlong userId, jboolean enablePushConnection, jboolean hasNetwork, jint networkType) { const char *deviceModelStr = env->GetStringUTFChars(deviceModel, 0); const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0); const char *appVersionStr = env->GetStringUTFChars(appVersion, 0); @@ -443,8 +443,8 @@ static JNINativeMethod ConnectionsManagerMethods[] = { {"native_applyDatacenterAddress", "(IILjava/lang/String;I)V", (void *) applyDatacenterAddress}, {"native_setProxySettings", "(ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", (void *) setProxySettings}, {"native_getConnectionState", "(I)I", (void *) getConnectionState}, - {"native_setUserId", "(II)V", (void *) setUserId}, - {"native_init", "(IIIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIZZI)V", (void *) init}, + {"native_setUserId", "(IJ)V", (void *) setUserId}, + {"native_init", "(IIIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IJZZI)V", (void *) init}, {"native_setLangCode", "(ILjava/lang/String;)V", (void *) setLangCode}, {"native_setRegId", "(ILjava/lang/String;)V", (void *) setRegId}, {"native_setSystemLangCode", "(ILjava/lang/String;)V", (void *) setSystemLangCode}, diff --git a/TMessagesProj/jni/tgnet/ApiScheme.cpp b/TMessagesProj/jni/tgnet/ApiScheme.cpp index bfd2de0fe..76a33078e 100644 --- a/TMessagesProj/jni/tgnet/ApiScheme.cpp +++ b/TMessagesProj/jni/tgnet/ApiScheme.cpp @@ -366,10 +366,10 @@ void TL_restrictionReason::serializeToStream(NativeByteBuffer *stream) { User *User::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error) { User *result = nullptr; switch (constructor) { - case 0x200250ba: + case 0xd3bc4b7a: result = new TL_userEmpty(); break; - case 0x938458c1: + case 0x3ff6ecb0: result = new TL_user(); break; default: @@ -382,17 +382,17 @@ User *User::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_ } void TL_userEmpty::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - id = stream->readInt32(&error); + id = stream->readInt64(&error); } void TL_userEmpty::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(id); + stream->writeInt64(id); } void TL_user::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { flags = stream->readInt32(&error); - id = stream->readInt32(&error); + id = stream->readInt64(&error); if ((flags & 1) != 0) { access_hash = stream->readInt64(&error); } @@ -444,7 +444,7 @@ void TL_user::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &er void TL_user::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); stream->writeInt32(flags); - stream->writeInt32(id); + stream->writeInt64(id); if ((flags & 1) != 0) { stream->writeInt64(access_hash); } @@ -491,19 +491,19 @@ InputPeer *InputPeer::TLdeserialize(NativeByteBuffer *stream, uint32_t construct case 0x7da07ec9: result = new TL_inputPeerSelf(); break; - case 0x7b8e7de6: + case 0xdde8a54c: result = new TL_inputPeerUser(); break; - case 0x179be863: + case 0x35a95cb9: result = new TL_inputPeerChat(); break; - case 0x17bae2e6: + case 0xa87b0a1c: result = new TL_inputPeerUserFromMessage(); break; - case 0x9c95f7bb: + case 0xbd2a0840: result = new TL_inputPeerChannelFromMessage(); break; - case 0x20adaef8: + case 0x27bcbbfc: result = new TL_inputPeerChannel(); break; case 0x7f3b18ea: @@ -523,59 +523,59 @@ void TL_inputPeerSelf::serializeToStream(NativeByteBuffer *stream) { } void TL_inputPeerUser::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - user_id = stream->readInt32(&error); + user_id = stream->readInt64(&error); access_hash = stream->readInt64(&error); } void TL_inputPeerUser::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(user_id); + stream->writeInt64(user_id); stream->writeInt64(access_hash); } void TL_inputPeerChat::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - chat_id = stream->readInt32(&error); + chat_id = stream->readInt64(&error); } void TL_inputPeerChat::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(chat_id); + stream->writeInt64(chat_id); } void TL_inputPeerUserFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { peer = std::unique_ptr(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); msg_id = stream->readInt32(&error); - user_id = stream->readInt32(&error); + user_id = stream->readInt64(&error); } void TL_inputPeerUserFromMessage::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); peer->serializeToStream(stream); stream->writeInt32(msg_id); - stream->writeInt32(user_id); + stream->writeInt64(user_id); } void TL_inputPeerChannelFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { peer = std::unique_ptr(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); msg_id = stream->readInt32(&error); - channel_id = stream->readInt32(&error); + channel_id = stream->readInt64(&error); } void TL_inputPeerChannelFromMessage::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); peer->serializeToStream(stream); stream->writeInt32(msg_id); - stream->writeInt32(channel_id); + stream->writeInt64(channel_id); } void TL_inputPeerChannel::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - channel_id = stream->readInt32(&error); + channel_id = stream->readInt64(&error); access_hash = stream->readInt64(&error); } void TL_inputPeerChannel::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(channel_id); + stream->writeInt64(channel_id); stream->writeInt64(access_hash); } @@ -589,13 +589,13 @@ InputUser *InputUser::TLdeserialize(NativeByteBuffer *stream, uint32_t construct case 0xf7c1b13f: result = new TL_inputUserSelf(); break; - case 0xd8292816: + case 0xf21158c6: result = new TL_inputUser(); break; case 0xb98886cf: result = new TL_inputUserEmpty(); break; - case 0x2d117597: + case 0x1da448e2: result = new TL_inputUserFromMessage(); break; default: @@ -612,13 +612,13 @@ void TL_inputUserSelf::serializeToStream(NativeByteBuffer *stream) { } void TL_inputUser::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - user_id = stream->readInt32(&error); + user_id = stream->readInt64(&error); access_hash = stream->readInt64(&error); } void TL_inputUser::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(user_id); + stream->writeInt64(user_id); stream->writeInt64(access_hash); } @@ -629,14 +629,14 @@ void TL_inputUserEmpty::serializeToStream(NativeByteBuffer *stream) { void TL_inputUserFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { peer = std::unique_ptr(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); msg_id = stream->readInt32(&error); - user_id = stream->readInt32(&error); + user_id = stream->readInt64(&error); } void TL_inputUserFromMessage::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); peer->serializeToStream(stream); stream->writeInt32(msg_id); - stream->writeInt32(user_id); + stream->writeInt64(user_id); } MessageEntity *MessageEntity::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error) { @@ -666,7 +666,7 @@ MessageEntity *MessageEntity::TLdeserialize(NativeByteBuffer *stream, uint32_t c case 0xfa04579d: result = new TL_messageEntityMention(); break; - case 0x352dca58: + case 0xdc7b1140: result = new TL_messageEntityMentionName(); break; case 0x208e68c9: @@ -800,14 +800,14 @@ void TL_messageEntityMention::serializeToStream(NativeByteBuffer *stream) { void TL_messageEntityMentionName::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { offset = stream->readInt32(&error); length = stream->readInt32(&error); - user_id = stream->readInt32(&error); + user_id = stream->readInt64(&error); } void TL_messageEntityMentionName::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); stream->writeInt32(offset); stream->writeInt32(length); - stream->writeInt32(user_id); + stream->writeInt64(user_id); } void TL_inputMessageEntityMentionName::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { @@ -1045,7 +1045,7 @@ TL_auth_exportedAuthorization *TL_auth_exportedAuthorization::TLdeserialize(Nati } void TL_auth_exportedAuthorization::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { - id = stream->readInt32(&error); + id = stream->readInt64(&error); bytes = std::unique_ptr(stream->readByteArray(&error)); } @@ -1072,7 +1072,7 @@ TLObject *TL_auth_importAuthorization::deserializeResponse(NativeByteBuffer *str void TL_auth_importAuthorization::serializeToStream(NativeByteBuffer *stream) { stream->writeInt32(constructor); - stream->writeInt32(id); + stream->writeInt64(id); stream->writeByteArray(bytes.get()); } diff --git a/TMessagesProj/jni/tgnet/ApiScheme.h b/TMessagesProj/jni/tgnet/ApiScheme.h index 4f6c00807..3bc7c4e15 100644 --- a/TMessagesProj/jni/tgnet/ApiScheme.h +++ b/TMessagesProj/jni/tgnet/ApiScheme.h @@ -295,7 +295,7 @@ public: class User : public TLObject { public: - int32_t id; + int64_t id; std::string first_name; std::string last_name; std::string username; @@ -315,7 +315,7 @@ public: class TL_userEmpty : public User { public: - static const uint32_t constructor = 0x200250ba; + static const uint32_t constructor = 0xd3bc4b7a; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -324,7 +324,7 @@ public: class TL_user : public User { public: - static const uint32_t constructor = 0x938458c1; + static const uint32_t constructor = 0x3ff6ecb0; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -333,9 +333,9 @@ public: class InputPeer : public TLObject { public: - int32_t user_id; - int32_t chat_id; - int32_t channel_id; + int64_t user_id; + int64_t chat_id; + int64_t channel_id; int64_t access_hash; static InputPeer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); @@ -352,7 +352,7 @@ public: class TL_inputPeerUser : public InputPeer { public: - static const uint32_t constructor = 0x7b8e7de6; + static const uint32_t constructor = 0xdde8a54c; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -361,7 +361,7 @@ public: class TL_inputPeerChat : public InputPeer { public: - static const uint32_t constructor = 0x179be863; + static const uint32_t constructor = 0x35a95cb9; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -370,7 +370,7 @@ public: class TL_inputPeerUserFromMessage : public InputPeer { public: - static const uint32_t constructor = 0x17bae2e6; + static const uint32_t constructor = 0xa87b0a1c; std::unique_ptr peer; int32_t msg_id; @@ -382,7 +382,7 @@ public: class TL_inputPeerChannelFromMessage : public InputPeer { public: - static const uint32_t constructor = 0x9c95f7bb; + static const uint32_t constructor = 0xbd2a0840; std::unique_ptr peer; int32_t msg_id; @@ -394,7 +394,7 @@ public: class TL_inputPeerChannel : public InputPeer { public: - static const uint32_t constructor = 0x20adaef8; + static const uint32_t constructor = 0x27bcbbfc; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -411,7 +411,7 @@ public: class InputUser : public TLObject { public: - int32_t user_id; + int64_t user_id; int64_t access_hash; static InputUser *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); @@ -428,7 +428,7 @@ public: class TL_inputUser : public InputUser { public: - static const uint32_t constructor = 0xd8292816; + static const uint32_t constructor = 0xf21158c6; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -445,7 +445,7 @@ public: class TL_inputUserFromMessage : public InputUser { public: - static const uint32_t constructor = 0x2d117597; + static const uint32_t constructor = 0x1da448e2; std::unique_ptr peer; int32_t msg_id; @@ -539,9 +539,9 @@ public: class TL_messageEntityMentionName : public MessageEntity { public: - static const uint32_t constructor = 0x352dca58; + static const uint32_t constructor = 0xdc7b1140; - int32_t user_id; + int64_t user_id; void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void serializeToStream(NativeByteBuffer *stream); @@ -693,9 +693,9 @@ public: class TL_auth_exportedAuthorization : public TLObject { public: - static const uint32_t constructor = 0xdf969c2d; + static const uint32_t constructor = 0xb434e2b8; - int32_t id; + int64_t id; std::unique_ptr bytes; static TL_auth_exportedAuthorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); @@ -717,9 +717,9 @@ public: class TL_auth_importAuthorization : public TLObject { public: - static const uint32_t constructor = 0xe3ef9613; + static const uint32_t constructor = 0xa57a7dad; - int32_t id; + int64_t id; std::unique_ptr bytes; bool isNeedLayer(); diff --git a/TMessagesProj/jni/tgnet/ConnectionsManager.cpp b/TMessagesProj/jni/tgnet/ConnectionsManager.cpp index 882af401a..ed8023cbc 100644 --- a/TMessagesProj/jni/tgnet/ConnectionsManager.cpp +++ b/TMessagesProj/jni/tgnet/ConnectionsManager.cpp @@ -1865,7 +1865,7 @@ void ConnectionsManager::bindRequestToGuid(int32_t requestToken, int32_t guid) { }); } -void ConnectionsManager::setUserId(int32_t userId) { +void ConnectionsManager::setUserId(int64_t userId) { scheduleTask([&, userId] { int32_t oldUserId = currentUserId; currentUserId = userId; @@ -3261,7 +3261,7 @@ void ConnectionsManager::applyDnsConfig(NativeByteBuffer *buffer, std::string ph }); } -void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int32_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType) { +void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType) { currentVersion = version; currentLayer = layer; currentApiId = apiId; diff --git a/TMessagesProj/jni/tgnet/ConnectionsManager.h b/TMessagesProj/jni/tgnet/ConnectionsManager.h index 645565d56..bb9c81fef 100644 --- a/TMessagesProj/jni/tgnet/ConnectionsManager.h +++ b/TMessagesProj/jni/tgnet/ConnectionsManager.h @@ -57,13 +57,13 @@ public: void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port); void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate); ConnectionState getConnectionState(); - void setUserId(int32_t userId); + void setUserId(int64_t userId); void switchBackend(bool restart); void resumeNetwork(bool partial); void pauseNetwork(); void setNetworkAvailable(bool value, int32_t type, bool slow); void setIpStrategy(uint8_t value); - void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerprint, std::string installerId, std::string packageId, int32_t timezoneOffset, int32_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType); + void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerprint, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType); void setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret); void setLangCode(std::string langCode); void setRegId(std::string regId); @@ -222,7 +222,7 @@ private: std::string currentSystemLangCode; std::string currentConfigPath; std::string currentLogPath; - int32_t currentUserId = 0; + int64_t currentUserId = 0; bool registeredForInternalPush = false; bool pushConnectionEnabled = true; diff --git a/TMessagesProj/jni/tgnet/Defines.h b/TMessagesProj/jni/tgnet/Defines.h index b8550aea4..8ab7b9c1c 100644 --- a/TMessagesProj/jni/tgnet/Defines.h +++ b/TMessagesProj/jni/tgnet/Defines.h @@ -17,7 +17,7 @@ #include "ByteArray.h" #define USE_DEBUG_SESSION false -#define READ_BUFFER_SIZE 1024 * 128 +#define READ_BUFFER_SIZE 1024 * 1024 * 2 //#define DEBUG_VERSION #define PFS_ENABLED 1 #define DEFAULT_DATACENTER_ID INT_MAX diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml index cac5f8905..79376604e 100644 --- a/TMessagesProj/src/main/AndroidManifest.xml +++ b/TMessagesProj/src/main/AndroidManifest.xml @@ -340,16 +340,6 @@ - - - - - - - - - - diff --git a/TMessagesProj/src/main/assets/bluebubbles.attheme b/TMessagesProj/src/main/assets/bluebubbles.attheme index 483306f73..d269a04b3 100644 --- a/TMessagesProj/src/main/assets/bluebubbles.attheme +++ b/TMessagesProj/src/main/assets/bluebubbles.attheme @@ -80,8 +80,8 @@ dialogTextGray4=-7565423 chat_attachContactText=-2121728 chat_searchPanelIcons=-12937244 windowBackgroundWhiteLinkText=-13990712 -chat_outVenueInfoText=-8216913 -chat_outContactPhoneText=-8612185 +chat_outVenueInfoText=-9396792 +chat_outContactPhoneText=-9396792 chat_inAudioTitleText=-15061445 chat_messageLinkIn=-16090691 chat_inBubbleSelected=-1509892 @@ -92,7 +92,7 @@ chat_outSiteNameText=-14515511 dialogTextGray=-7565423 chat_messageLinkOut=-16155709 avatar_backgroundArchived=-4998207 -chat_outFileInfoSelectedText=-8674358 +chat_outFileInfoSelectedText=-9396792 chat_outAudioDurationSelectedText=-8674358 avatar_backgroundArchivedHidden=-10832396 statisticChartLine_orange=-1853657 @@ -105,7 +105,7 @@ chat_outReplyLine=-13133085 chat_inAudioSeekbarFill=-10572824 chat_inContactBackground=-431707662 progressCircle=-14375188 -chat_outVenueInfoSelectedText=-8674358 +chat_outVenueInfoSelectedText=-9396792 chats_menuItemIcon=-7433063 wallpaperFileOffset=-1 chat_outBubbleShadow=-16699318 @@ -130,8 +130,8 @@ chat_outBubbleSelected=-2690305 chat_inFileNameText=-15654091 statisticChartLine_blue=-13467675 chat_inInstantSelected=-14707230 -chat_outFileInfoText=-7953740 -chat_outContactPhoneSelectedText=-9725764 +chat_outFileInfoText=-9396792 +chat_outContactPhoneSelectedText=-9396792 chat_wallpaper=-11300655 chat_outMenuSelected=-7026959 chat_outLoaderPhotoSelected=-263935502 @@ -142,14 +142,14 @@ avatar_actionBarSelectorBlue=-12091735 switchTrackChecked=-11424793 chat_inLoader=-431707662 chat_outPreviewInstantSelectedText=-14514998 -chat_outTimeText=-141776195 +chat_outTimeText=-143614520 chat_attachAudioText=-2209977 chat_outBubble=-1641732 chat_attachHideBackground=-4866356 chats_menuItemText=-12632257 chat_outReplyNameText=-14382642 chats_menuTopBackgroundCats=-10906430 -chat_outReplyMediaMessageText=-7558467 +chat_outReplyMediaMessageText=-9396792 actionBarTabSelector=-12554340 chat_outLoaderPhotoIcon=-263935502 chat_attachFileText=-15423260 @@ -178,9 +178,9 @@ chats_actionPressedBackground=-11166764 chat_replyPanelName=-13397538 windowBackgroundWhiteValueText=-13003565 chat_outAudioDurationText=-7558467 -chat_outMenu=-5716778 +chat_outMenu=-5782571 statisticChartActiveLine=335544320 -chat_outReplyMediaMessageSelectedText=-8674357 +chat_outReplyMediaMessageSelectedText=-9396792 chats_attachMessage=-14843710 chat_outSentClock=-594761027 chat_searchPanelText=-12609056 diff --git a/TMessagesProj/src/main/assets/night.attheme b/TMessagesProj/src/main/assets/night.attheme index 209c4a232..f70fae2af 100644 --- a/TMessagesProj/src/main/assets/night.attheme +++ b/TMessagesProj/src/main/assets/night.attheme @@ -44,7 +44,7 @@ chat_outFileProgressSelected=-1 chat_outTimeSelectedText=-7023626 chat_inFileProgressSelected=-1 changephoneinfo_image=-11184811 -chat_inAudioPerfomerText=-8618883 +chat_inAudioPerfomerText=-8749955 statisticChartBackZoomColor=-12145938 player_button=-1 key_sheet_other=1140850687 @@ -61,7 +61,7 @@ player_actionBarTitle=-1 dialogGrayLine=-12040120 chat_outFileIcon=-12689015 chats_nameMessage_threeLines=-1315861 -chat_adminText=-8355711 +chat_adminText=-8552575 chat_inFileProgress=-1 dialogIcon=-7566196 chat_emojiPanelEmptyText=-8553090 @@ -79,8 +79,8 @@ chat_inReplyMediaMessageSelectedText=-7490861 avatar_actionBarSelectorOrange=-12758164 dialogCheckboxSquareUnchecked=-10855846 chat_inMediaIconSelected=-1 -chat_inBubble=-14540253 -chat_outSentCheckRead=-5841921 +chat_inBubble=-14737117 +chat_outSentCheckRead=-506859265 chat_emojiPanelStickerPackSelector=181267199 chat_unreadMessagesStartArrowIcon=-9605777 avatar_backgroundActionBarOrange=-14602949 @@ -106,7 +106,7 @@ dialogInputField=-8553091 windowBackgroundWhiteInputFieldActivated=-9522449 chat_attachGalleryBackground=-11692299 chat_outInstantSelected=-1 -chat_outSentCheck=-251658241 +chat_outSentCheck=-506859265 key_graySectionText=-8158332 player_placeholder=-10197916 chat_outFileSelectedIcon=-13925429 @@ -116,7 +116,7 @@ dialogButton=-10177041 contextProgressInner1=-11184811 chat_inLoaderPhotoIconSelected=-1 actionBarDefaultSubtitle=-7895161 -chat_inContactPhoneText=-8355711 +chat_inContactPhoneText=-8486783 chat_inlineResultIcon=-8796932 chat_outBubbleGradientSelectedOverlay=352321535 chats_draft=-637778102 @@ -164,7 +164,7 @@ switchThumb=-12034697 windowBackgroundWhiteRedText2=-955034 passport_authorizeBackground=-12352582 chats_nameIcon=-1250068 -chat_inSentClock=-10263709 +chat_inSentClock=-11050909 key_chats_menuTopShadow=789516 avatar_nameInMessageRed=-21124 chat_outLoaderPhoto=-12623479 @@ -280,7 +280,7 @@ chats_unreadCounterMuted=-12237499 chat_outVoiceSeekbarFill=-1 chat_outReplyLine=-8466689 chat_messagePanelIcons=-8947847 -chat_inReplyMediaMessageText=-8355711 +chat_inReplyMediaMessageText=-8421247 inappPlayerTitle=-8618626 chat_emojiPanelIconSelected=-10177041 progressCircle=-10177027 @@ -429,7 +429,7 @@ dialogSearchIcon=-8882056 chat_inPreviewInstantText=-8796932 chats_archiveBackground=-12219694 dialog_liveLocationProgress=-9919529 -chat_inViews=-8355712 +chat_inViews=-8881024 chat_outLoaderSelected=-1 dialogButtonSelector=-13158601 chats_archivePinBackground=-13619152 @@ -447,7 +447,7 @@ windowBackgroundWhiteGrayText5=-8549479 windowBackgroundWhiteGrayText6=-8553091 windowBackgroundWhiteGrayText3=-8553091 windowBackgroundWhiteGrayText4=-10987432 -chat_inTimeText=-8355711 +chat_inTimeText=-8552575 dialogRadioBackground=-10855846 statisticChartRipple=748994002 chat_outBubbleGradient=-12874567 @@ -474,7 +474,7 @@ chat_outAudioDurationText=-7023626 chat_outMenu=-7420685 chat_goDownButton=-14606046 chats_secretName=-9316522 -chat_inMenu=-10197916 +chat_inMenu=-10656924 chat_recordVoiceCancel=-8553090 chat_inFileSelectedIcon=-15056797 chat_outReplyMediaMessageSelectedText=-7023626 @@ -484,8 +484,7 @@ dialogRedIcon=-554801041 avatar_subtitleInProfileCyan=-7628894 chats_attachMessage=-8224126 chat_topPanelBackground=-15066597 -chat_outSentClock=-8213557 +chat_outSentClock=-6698513 dialogBackgroundGray=-14013910 chat_searchPanelText=-10767620 chat_inContactIcon=-1 -voipgroup_topPanelGray=-10521727 diff --git a/TMessagesProj/src/main/java/androidx/recyclerview/widget/ChatListItemAnimator.java b/TMessagesProj/src/main/java/androidx/recyclerview/widget/ChatListItemAnimator.java index 432635de1..d591a64a5 100644 --- a/TMessagesProj/src/main/java/androidx/recyclerview/widget/ChatListItemAnimator.java +++ b/TMessagesProj/src/main/java/androidx/recyclerview/widget/ChatListItemAnimator.java @@ -15,13 +15,12 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; -import com.google.android.exoplayer2.util.Log; - import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.MessageObject; import org.telegram.messenger.SharedConfig; +import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.BotHelpCell; import org.telegram.ui.Cells.ChatMessageCell; import org.telegram.ui.ChatActivity; @@ -57,8 +56,10 @@ public class ChatListItemAnimator extends DefaultItemAnimator { private ChatGreetingsView chatGreetingsView; private boolean reversePositions; + private final Theme.ResourcesProvider resourcesProvider; - public ChatListItemAnimator(ChatActivity activity, RecyclerListView listView) { + public ChatListItemAnimator(ChatActivity activity, RecyclerListView listView, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; this.activity = activity; this.recyclerListView = listView; translationInterpolator = DEFAULT_INTERPOLATOR; @@ -293,12 +294,12 @@ public class ChatListItemAnimator extends DefaultItemAnimator { if (activity.getChatActivityEnterView().canShowMessageTransition()) { if (chatMessageCell.getMessageObject().isVoice()) { if (Math.abs(view.getTranslationY()) < view.getMeasuredHeight() * 3f) { - VoiceMessageEnterTransition transition = new VoiceMessageEnterTransition(chatMessageCell, activity.getChatActivityEnterView(), recyclerListView, activity.messageEnterTransitionContainer); + VoiceMessageEnterTransition transition = new VoiceMessageEnterTransition(chatMessageCell, activity.getChatActivityEnterView(), recyclerListView, activity.messageEnterTransitionContainer, resourcesProvider); transition.start(); } } else { if (SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_LOW && Math.abs(view.getTranslationY()) < recyclerListView.getMeasuredHeight()) { - TextMessageEnterTransition transition = new TextMessageEnterTransition(chatMessageCell, activity, recyclerListView, activity.messageEnterTransitionContainer); + TextMessageEnterTransition transition = new TextMessageEnterTransition(chatMessageCell, activity, recyclerListView, activity.messageEnterTransitionContainer, resourcesProvider); transition.start(); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/AndroidUtilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/AndroidUtilities.java index f783298b0..3439034a3 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/AndroidUtilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/AndroidUtilities.java @@ -243,6 +243,8 @@ public class AndroidUtilities { R.drawable.media_doc_yellow_b }; + public static final String STICKERS_PLACEHOLDER_PACK_NAME = "tg_placeholders_android"; + private static boolean containsUnsupportedCharacters(String text) { if (text.contains("\u202C")) { return true; @@ -337,13 +339,13 @@ public class AndroidUtilities { return str; } - public static CharSequence highlightText(CharSequence str, ArrayList query) { + public static CharSequence highlightText(CharSequence str, ArrayList query, Theme.ResourcesProvider resourcesProvider) { if (query == null) { return null; } int emptyCount = 0; for (int i = 0; i < query.size(); i++) { - CharSequence strTmp = highlightText(str, query.get(i)); + CharSequence strTmp = highlightText(str, query.get(i), resourcesProvider); if (strTmp != null) { str = strTmp; } else { @@ -356,7 +358,7 @@ public class AndroidUtilities { return str; } - public static CharSequence highlightText(CharSequence str, String query) { + public static CharSequence highlightText(CharSequence str, String query, Theme.ResourcesProvider resourcesProvider) { if (TextUtils.isEmpty(query) || TextUtils.isEmpty(str)) { return null; } @@ -365,7 +367,7 @@ public class AndroidUtilities { int i = s.indexOf(query); while (i >= 0) { try { - spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), i, Math.min(i + query.length(), str.length()), 0); + spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), i, Math.min(i + query.length(), str.length()), 0); } catch (Exception e) { FileLog.e(e); } @@ -1616,6 +1618,15 @@ public class AndroidUtilities { return -1; } + public static int compare(long lhs, long rhs) { + if (lhs == rhs) { + return 0; + } else if (lhs > rhs) { + return 1; + } + return -1; + } + public static float dpf2(float value) { if (value == 0) { return 0; @@ -2231,12 +2242,33 @@ public class AndroidUtilities { }*/ public static void startAppCenter(Activity context) { - +// if (BuildConfig.DEBUG) { +// return; +// } +// try { +// if (BuildVars.DEBUG_VERSION) { +// Distribute.setEnabledForDebuggableBuild(true); +// AppCenter.start(context.getApplication(), BuildVars.DEBUG_VERSION ? BuildVars.APPCENTER_HASH_DEBUG : BuildVars.APPCENTER_HASH, Distribute.class, Crashes.class); +// AppCenter.setUserId("uid=" + UserConfig.getInstance(UserConfig.selectedAccount).clientUserId); +// } +// } catch (Throwable e) { +// FileLog.e(e); +// } } private static long lastUpdateCheckTime; public static void checkForUpdates() { - +// try { +// if (BuildVars.DEBUG_VERSION) { +// if (SystemClock.elapsedRealtime() - lastUpdateCheckTime < 60 * 60 * 1000) { +// return; +// } +// lastUpdateCheckTime = SystemClock.elapsedRealtime(); +// Distribute.checkForUpdate(); +// } +// } catch (Throwable e) { +// FileLog.e(e); +// } } public static void addToClipboard(CharSequence str) { @@ -2804,7 +2836,7 @@ public class AndroidUtilities { } } - public static boolean openForView(File f, String fileName, String mimeType, final Activity activity) { + public static boolean openForView(File f, String fileName, String mimeType, final Activity activity, Theme.ResourcesProvider resourcesProvider) { if (f != null && f.exists()) { String realMimeType = null; Intent intent = new Intent(Intent.ACTION_VIEW); @@ -2822,7 +2854,7 @@ public class AndroidUtilities { } } if (Build.VERSION.SDK_INT >= 26 && realMimeType != null && realMimeType.equals("application/vnd.android.package-archive") && !ApplicationLoader.applicationContext.getPackageManager().canRequestPackageInstalls()) { - AlertDialog.Builder builder = new AlertDialog.Builder(activity); + AlertDialog.Builder builder = new AlertDialog.Builder(activity, resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ApkRestricted", R.string.ApkRestricted)); builder.setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialogInterface, i) -> { @@ -2860,7 +2892,7 @@ public class AndroidUtilities { return false; } - public static boolean openForView(MessageObject message, Activity activity) { + public static boolean openForView(MessageObject message, Activity activity, Theme.ResourcesProvider resourcesProvider) { File f = null; if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { f = new File(message.messageOwner.attachPath); @@ -2869,13 +2901,13 @@ public class AndroidUtilities { f = FileLoader.getPathToMessage(message.messageOwner); } String mimeType = message.type == 9 || message.type == 0 ? message.getMimeType() : null; - return openForView(f, message.getFileName(), mimeType, activity); + return openForView(f, message.getFileName(), mimeType, activity, resourcesProvider); } public static boolean openForView(TLRPC.Document document, boolean forceCache, Activity activity) { String fileName = FileLoader.getAttachFileName(document); File f = FileLoader.getPathToAttach(document, true); - return openForView(f, fileName, document.mime_type, activity); + return openForView(f, fileName, document.mime_type, activity, null); } public static CharSequence replaceNewLines(CharSequence original) { @@ -3740,4 +3772,12 @@ public class AndroidUtilities { view.setTag(null); } } + + public static long getPrefIntOrLong(SharedPreferences preferences, String key, long defaultValue) { + try { + return preferences.getLong(key, defaultValue); + } catch (Exception e) { + return preferences.getInt(key, (int) defaultValue); + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java index cb3e67061..62d38d2e3 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java @@ -169,8 +169,7 @@ public class ApplicationLoader extends Application { ContactsController.getInstance(a).checkAppAccount(); DownloadController.getInstance(a); } - - WearDataLayerListenerService.updateWatchConnectionState(); + ChatThemeController.init(); } public ApplicationLoader() { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/AuthenticatorService.java b/TMessagesProj/src/main/java/org/telegram/messenger/AuthenticatorService.java index 51191c368..5482ff418 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/AuthenticatorService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/AuthenticatorService.java @@ -22,11 +22,9 @@ import android.os.IBinder; public class AuthenticatorService extends Service { private static class Authenticator extends AbstractAccountAuthenticator { - private final Context context; public Authenticator(Context context) { super(context); - this.context = context; } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageHeardReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageHeardReceiver.java index dba269aa0..41f4a0474 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageHeardReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageHeardReceiver.java @@ -19,40 +19,38 @@ public class AutoMessageHeardReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ApplicationLoader.postInitApplication(); - long dialog_id = intent.getLongExtra("dialog_id", 0); - int max_id = intent.getIntExtra("max_id", 0); + long dialogId = intent.getLongExtra("dialog_id", 0); + int maxId = intent.getIntExtra("max_id", 0); int currentAccount = intent.getIntExtra("currentAccount", 0); - if (dialog_id == 0 || max_id == 0 || !UserConfig.isValidAccount(currentAccount)) { + if (dialogId == 0 || maxId == 0 || !UserConfig.isValidAccount(currentAccount)) { return; } - int lowerId = (int) dialog_id; - int highId = (int) (dialog_id >> 32); AccountInstance accountInstance = AccountInstance.getInstance(currentAccount); - if (lowerId > 0) { - TLRPC.User user = accountInstance.getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = accountInstance.getMessagesController().getUser(dialogId); if (user == null) { Utilities.globalQueue.postRunnable(() -> { - TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(lowerId); + TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(dialogId); AndroidUtilities.runOnUIThread(() -> { accountInstance.getMessagesController().putUser(user1, true); - MessagesController.getInstance(currentAccount).markDialogAsRead(dialog_id, max_id, max_id, 0, false, 0, 0, true, 0); + MessagesController.getInstance(currentAccount).markDialogAsRead(dialogId, maxId, maxId, 0, false, 0, 0, true, 0); }); }); return; } - } else if (lowerId < 0) { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-lowerId); + } else if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialogId); if (chat == null) { Utilities.globalQueue.postRunnable(() -> { - TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-lowerId); + TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-dialogId); AndroidUtilities.runOnUIThread(() -> { accountInstance.getMessagesController().putChat(chat1, true); - MessagesController.getInstance(currentAccount).markDialogAsRead(dialog_id, max_id, max_id, 0, false, 0, 0, true, 0); + MessagesController.getInstance(currentAccount).markDialogAsRead(dialogId, maxId, maxId, 0, false, 0, 0, true, 0); }); }); return; } } - MessagesController.getInstance(currentAccount).markDialogAsRead(dialog_id, max_id, max_id, 0, false, 0, 0, true, 0); + MessagesController.getInstance(currentAccount).markDialogAsRead(dialogId, maxId, maxId, 0, false, 0, 0, true, 0); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageReplyReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageReplyReceiver.java index fb1833d75..32788e81c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageReplyReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/AutoMessageReplyReceiver.java @@ -12,6 +12,8 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; +import android.text.TextUtils; + import androidx.core.app.RemoteInput; public class AutoMessageReplyReceiver extends BroadcastReceiver { @@ -24,16 +26,16 @@ public class AutoMessageReplyReceiver extends BroadcastReceiver { return; } CharSequence text = remoteInput.getCharSequence(NotificationsController.EXTRA_VOICE_REPLY); - if (text == null || text.length() == 0) { + if (TextUtils.isEmpty(text)) { return; } - long dialog_id = intent.getLongExtra("dialog_id", 0); - int max_id = intent.getIntExtra("max_id", 0); + long dialogId = intent.getLongExtra("dialog_id", 0); + int maxId = intent.getIntExtra("max_id", 0); int currentAccount = intent.getIntExtra("currentAccount", 0); - if (dialog_id == 0 || max_id == 0 || !UserConfig.isValidAccount(currentAccount)) { + if (dialogId == 0 || maxId == 0 || !UserConfig.isValidAccount(currentAccount)) { return; } - SendMessagesHelper.getInstance(currentAccount).sendMessage(text.toString(), dialog_id, null, null, null, true, null, null, null, true, 0, null); - MessagesController.getInstance(currentAccount).markDialogAsRead(dialog_id, max_id, max_id, 0, false, 0, 0, true, 0); + SendMessagesHelper.getInstance(currentAccount).sendMessage(text.toString(), dialogId, null, null, null, true, null, null, null, true, 0, null); + MessagesController.getInstance(currentAccount).markDialogAsRead(dialogId, maxId, maxId, 0, false, 0, 0, true, 0); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/BuildVars.java b/TMessagesProj/src/main/java/org/telegram/messenger/BuildVars.java index 835cad3ca..df32745ba 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/BuildVars.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/BuildVars.java @@ -19,13 +19,13 @@ public class BuildVars { public static boolean USE_CLOUD_STRINGS = true; public static boolean CHECK_UPDATES = true; public static boolean NO_SCOPED_STORAGE = true/* || Build.VERSION.SDK_INT <= 28*/; - public static int BUILD_VERSION = 2406; - public static String BUILD_VERSION_STRING = "8.0.0"; + public static int BUILD_VERSION = 2428; + public static String BUILD_VERSION_STRING = "8.0.1"; public static int APP_ID = 4; public static String APP_HASH = "014b35b6184100b085b0d0572f9b5103"; - public static String APPCENTER_HASH = "a5b5c4f5-51da-dedc-9918-d9766a22ca7c"; - public static String APPCENTER_HASH_DEBUG = "f9726602-67c9-48d2-b5d0-4761f1c1a8f3"; - // + // public static String APPCENTER_HASH = "a5b5c4f5-51da-dedc-9918-d9766a22ca7c"; + //public static String APPCENTER_HASH_DEBUG = "f9726602-67c9-48d2-b5d0-4761f1c1a8f3"; + // public static String APPCENTER_HASH_DEBUG = DEBUG_PRIVATE_VERSION ? "1cfd375f-093f-4614-abe2-14e21c0dcf5c" : "f9726602-67c9-48d2-b5d0-4761f1c1a8f3"; public static String SMS_HASH = isStandaloneApp() ? "w0lkcmTZkKh" : (DEBUG_VERSION ? "O2P2z+/jBpJ" : "oLeq9AcOZkT"); public static String PLAYSTORE_APP_URL = "https://play.google.com/store/apps/details?id=org.telegram.messenger"; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ChatObject.java b/TMessagesProj/src/main/java/org/telegram/messenger/ChatObject.java index 8d58fe29d..4372a5dfa 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ChatObject.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ChatObject.java @@ -13,6 +13,8 @@ import android.os.SystemClock; import android.text.TextUtils; import android.util.SparseArray; +import com.google.android.exoplayer2.util.Log; + import org.telegram.messenger.voip.Instance; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.TLRPC; @@ -24,6 +26,8 @@ import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import androidx.collection.LongSparseArray; + public class ChatObject { public static final int CHAT_TYPE_CHAT = 0; @@ -55,16 +59,16 @@ public class ChatObject { public static class Call { public TLRPC.GroupCall call; - public int chatId; - public SparseArray participants = new SparseArray<>(); + public long chatId; + public LongSparseArray participants = new LongSparseArray<>(); public final ArrayList sortedParticipants = new ArrayList<>(); - public final ArrayList visibleVideoParticipants = new ArrayList<>(); + public final ArrayList visibleVideoParticipants = new ArrayList<>(); public final ArrayList visibleParticipants = new ArrayList<>(); public final HashMap thumbs = new HashMap<>(); private final HashMap videoParticipantsCache = new HashMap<>(); - public ArrayList invitedUsers = new ArrayList<>(); - public HashSet invitedUsersMap = new HashSet<>(); + public ArrayList invitedUsers = new ArrayList<>(); + public HashSet invitedUsersMap = new HashSet<>(); public SparseArray participantsBySources = new SparseArray<>(); public SparseArray participantsByVideoSources = new SparseArray<>(); public SparseArray participantsByPresentationSources = new SparseArray<>(); @@ -91,8 +95,8 @@ public class ChatObject { public TLRPC.Peer selfPeer; - private HashSet loadingUids = new HashSet<>(); - private HashSet loadingSsrcs = new HashSet<>(); + private HashSet loadingUids = new HashSet<>(); + private HashSet loadingSsrcs = new HashSet<>(); private Runnable checkQueueRunnable; @@ -100,7 +104,7 @@ public class ChatObject { private boolean loadingGroupCall; private static int videoPointer; - public final SparseArray currentSpeakingPeers = new SparseArray<>(); + public final LongSparseArray currentSpeakingPeers = new LongSparseArray<>(); private final Runnable updateCurrentSpeakingRunnable = new Runnable() { @Override @@ -108,11 +112,19 @@ public class ChatObject { long uptime = SystemClock.uptimeMillis(); boolean update = false; for(int i = 0; i < currentSpeakingPeers.size(); i++) { - int key = currentSpeakingPeers.keyAt(i); + long key = currentSpeakingPeers.keyAt(i); TLRPC.TL_groupCallParticipant participant = currentSpeakingPeers.get(key); if (uptime - participant.lastSpeakTime >= 500) { update = true; currentSpeakingPeers.remove(key); + + if (key > 0) { + TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(key); + Log.d("GroupCall", "remove from speaking " + key + " " + (user == null ? null : user.first_name)); + } else { + TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-key); + Log.d("GroupCall", "remove from speaking " + key + " " + (user == null ? null : user.title)); + } i--; } } @@ -126,7 +138,7 @@ public class ChatObject { } }; - public void setCall(AccountInstance account, int chatId, TLRPC.TL_phone_groupCall groupCall) { + public void setCall(AccountInstance account, long chatId, TLRPC.TL_phone_groupCall groupCall) { this.chatId = chatId; currentAccount = account; call = groupCall.call; @@ -162,7 +174,7 @@ public class ChatObject { } public void addSelfDummyParticipant(boolean notify) { - int selfId = getSelfId(); + long selfId = getSelfId(); if (participants.indexOfKey(selfId) >= 0) { return; } @@ -212,8 +224,8 @@ public class ChatObject { return (call.flags & 128) != 0; } - private int getSelfId() { - int selfId; + private long getSelfId() { + long selfId; if (selfPeer != null) { return MessageObject.getPeerId(selfPeer); } else { @@ -222,13 +234,13 @@ public class ChatObject { } private void onParticipantsLoad(ArrayList loadedParticipants, boolean fromBegin, String reqOffset, String nextOffset, int version, int participantCount) { - SparseArray old = null; - int selfId = getSelfId(); + LongSparseArray old = null; + long selfId = getSelfId(); TLRPC.TL_groupCallParticipant oldSelf = participants.get(selfId); if (TextUtils.isEmpty(reqOffset)) { if (participants.size() != 0) { old = participants; - participants = new SparseArray<>(); + participants = new LongSparseArray<>(); } else { participants.clear(); } @@ -357,7 +369,7 @@ public class ChatObject { }); } - public void addInvitedUser(int uid) { + public void addInvitedUser(long uid) { if (participants.get(uid) != null || invitedUsersMap.contains(uid)) { return; } @@ -365,13 +377,13 @@ public class ChatObject { invitedUsers.add(uid); } - public void processTypingsUpdate(AccountInstance accountInstance, ArrayList uids, int date) { + public void processTypingsUpdate(AccountInstance accountInstance, ArrayList uids, int date) { boolean updated = false; - ArrayList participantsToLoad = null; + ArrayList participantsToLoad = null; long time = SystemClock.elapsedRealtime(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); for (int a = 0, N = uids.size(); a < N; a++) { - Integer id = uids.get(a); + Long id = uids.get(a); TLRPC.TL_groupCallParticipant participant = participants.get(id); if (participant != null) { if (date - participant.lastTypingDate > 10) { @@ -397,8 +409,8 @@ public class ChatObject { } } - private void loadUnknownParticipants(ArrayList participantsToLoad, boolean isIds, OnParticipantsLoad onLoad) { - HashSet set = isIds ? loadingUids : loadingSsrcs; + private void loadUnknownParticipants(ArrayList participantsToLoad, boolean isIds, OnParticipantsLoad onLoad) { + HashSet set = isIds ? loadingUids : loadingSsrcs; for (int a = 0, N = participantsToLoad.size(); a < N; a++) { if (set.contains(participantsToLoad.get(a))) { participantsToLoad.remove(a); @@ -414,9 +426,9 @@ public class ChatObject { set.addAll(participantsToLoad); TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants(); req.call = getInputGroupCall(); - if (isIds) { - for (int a = 0, N = participantsToLoad.size(); a < N; a++) { - Integer uid = participantsToLoad.get(a); + for (int a = 0, N = participantsToLoad.size(); a < N; a++) { + long uid = participantsToLoad.get(a); + if (isIds) { if (uid > 0) { TLRPC.TL_inputPeerUser peerUser = new TLRPC.TL_inputPeerUser(); peerUser.user_id = uid; @@ -433,9 +445,9 @@ public class ChatObject { } req.ids.add(inputPeer); } + } else { + req.sources.add((int) uid); } - } else { - req.sources = participantsToLoad; } req.offset = ""; req.limit = 100; @@ -449,7 +461,7 @@ public class ChatObject { currentAccount.getMessagesController().putChats(groupParticipants.chats, false); for (int a = 0, N = groupParticipants.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = groupParticipants.participants.get(a); - int pid = MessageObject.getPeerId(participant.peer); + long pid = MessageObject.getPeerId(participant.peer); TLRPC.TL_groupCallParticipant oldParticipant = participants.get(pid); if (oldParticipant != null) { sortedParticipants.remove(oldParticipant); @@ -459,7 +471,7 @@ public class ChatObject { sortedParticipants.add(participant); processAllSources(participant, true); if (invitedUsersMap.contains(pid)) { - Integer id = pid; + Long id = pid; invitedUsersMap.remove(id); invitedUsers.remove(id); } @@ -530,7 +542,7 @@ public class ChatObject { boolean updated = false; boolean updateCurrentSpeakingList = false; int currentTime = currentAccount.getConnectionsManager().getCurrentTime(); - ArrayList participantsToLoad = null; + ArrayList participantsToLoad = null; long time = SystemClock.elapsedRealtime(); long uptime = SystemClock.uptimeMillis(); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); @@ -547,7 +559,7 @@ public class ChatObject { participant.hasVoiceDelayed = voice[a]; participant.lastVoiceUpdateTime = time; } - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); if (levels[a] > 0.1f) { if (voice[a] && participant.lastTypingDate + 1 < currentTime) { if (time != participant.lastVisibleDate) { @@ -560,6 +572,13 @@ public class ChatObject { participant.amplitude = levels[a]; if (currentSpeakingPeers.get(peerId, null) == null) { + if (peerId > 0) { + TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(peerId); + Log.d("GroupCall", "add to current speaking " + peerId + " " + (user == null ? null : user.first_name)); + } else { + TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-peerId); + Log.d("GroupCall", "add to current speaking " + peerId + " " + (user == null ? null : user.title)); + } currentSpeakingPeers.put(peerId, participant); updateCurrentSpeakingList = true; } @@ -567,6 +586,15 @@ public class ChatObject { if (uptime - participant.lastSpeakTime >= 500) { if (currentSpeakingPeers.get(peerId, null) != null) { currentSpeakingPeers.remove(peerId); + + if (peerId > 0) { + TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(peerId); + Log.d("GroupCall", "remove from speaking " + peerId + " " + (user == null ? null : user.first_name)); + } else { + TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-peerId); + Log.d("GroupCall", "remove from speaking " + peerId + " " + (user == null ? null : user.title)); + } + updateCurrentSpeakingList = true; } } @@ -576,7 +604,7 @@ public class ChatObject { if (participantsToLoad == null) { participantsToLoad = new ArrayList<>(); } - participantsToLoad.add(ssrc[a]); + participantsToLoad.add((long) ssrc[a]); } } if (participantsToLoad != null) { @@ -610,11 +638,11 @@ public class ChatObject { } public interface OnParticipantsLoad { - void onLoad(ArrayList ssrcs); + void onLoad(ArrayList ssrcs); } public void processUnknownVideoParticipants(int[] ssrc, OnParticipantsLoad onLoad) { - ArrayList participantsToLoad = null; + ArrayList participantsToLoad = null; for (int a = 0; a < ssrc.length; a++) { if (participantsBySources.get(ssrc[a]) != null || participantsByVideoSources.get(ssrc[a]) != null || participantsByPresentationSources.get(ssrc[a]) != null) { continue; @@ -622,7 +650,7 @@ public class ChatObject { if (participantsToLoad == null) { participantsToLoad = new ArrayList<>(); } - participantsToLoad.add(ssrc[a]); + participantsToLoad.add((long) ssrc[a]); } if (participantsToLoad != null) { loadUnknownParticipants(participantsToLoad, false, onLoad); @@ -797,7 +825,7 @@ public class ChatObject { boolean changedOrAdded = false; boolean speakingUpdated = false; - int selfId = getSelfId(); + long selfId = getSelfId(); long time = SystemClock.elapsedRealtime(); long justJoinedId = 0; int lastParticipantDate; @@ -809,7 +837,7 @@ public class ChatObject { currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); for (int a = 0, N = update.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = update.participants.get(a); - int pid = MessageObject.getPeerId(participant.peer); + long pid = MessageObject.getPeerId(participant.peer); if (BuildVars.LOGS_ENABLED) { FileLog.d("process participant " + pid + " left = " + participant.left + " versioned " + participant.versioned + " flags = " + participant.flags + " self = " + selfId + " volume = " + participant.volume); } @@ -827,6 +855,13 @@ public class ChatObject { sortedParticipants.remove(oldParticipant); visibleParticipants.remove(oldParticipant); if (currentSpeakingPeers.get(pid, null) != null) { + if (pid > 0) { + TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(pid); + Log.d("GroupCall", "left remove from speaking " + pid + " " + (user == null ? null : user.first_name)); + } else { + TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-pid); + Log.d("GroupCall", "left remove from speaking " + pid + " " + (user == null ? null : user.title)); + } currentSpeakingPeers.remove(pid); speakingUpdated = true; } @@ -845,7 +880,7 @@ public class ChatObject { updated = true; } else { if (invitedUsersMap.contains(pid)) { - Integer id = pid; + Long id = pid; invitedUsersMap.remove(id); invitedUsers.remove(id); } @@ -856,6 +891,13 @@ public class ChatObject { oldParticipant.muted = participant.muted; if (participant.muted && currentSpeakingPeers.get(pid, null) != null) { currentSpeakingPeers.remove(pid); + if (pid > 0) { + TLRPC.User user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getUser(pid); + Log.d("GroupCall", "muted remove from speaking " + pid + " " + (user == null ? null : user.first_name)); + } else { + TLRPC.Chat user = MessagesController.getInstance(currentAccount.getCurrentAccount()).getChat(-pid); + Log.d("GroupCall", "muted remove from speaking " + pid + " " + (user == null ? null : user.title)); + } speakingUpdated = true; } if (!participant.min) { @@ -1032,7 +1074,8 @@ public class ChatObject { visibleParticipants.clear(); TLRPC.Chat chat = currentAccount.getMessagesController().getChat(chatId); boolean isAdmin = ChatObject.canManageCalls(chat); - int selfId = getSelfId(); + + long selfId = getSelfId(); VoIPService service = VoIPService.getSharedInstance(); TLRPC.TL_groupCallParticipant selfParticipant = participants.get(selfId); canStreamVideo = true;//selfParticipant != null && selfParticipant.video_joined || BuildVars.DEBUG_PRIVATE_VERSION; @@ -1447,7 +1490,7 @@ public class ChatObject { return (chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden) && chat.megagroup; } - public static boolean isMegagroup(int currentAccount, int chatId) { + public static boolean isMegagroup(int currentAccount, long chatId) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return ChatObject.isChannel(chat) && chat.megagroup; } @@ -1521,12 +1564,12 @@ public class ChatObject { return canUserDoAction(chat, ACTION_PIN) || ChatObject.isChannel(chat) && !chat.megagroup && chat.admin_rights != null && chat.admin_rights.edit_messages; } - public static boolean isChannel(int chatId, int currentAccount) { + public static boolean isChannel(long chatId, int currentAccount) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden; } - public static boolean isCanWriteToChannel(int chatId, int currentAccount) { + public static boolean isCanWriteToChannel(long chatId, int currentAccount) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); return ChatObject.canSendMessages(chat) || chat.megagroup; } @@ -1553,15 +1596,6 @@ public class ChatObject { return currentBannedRights; } - public static TLRPC.Chat getChatByDialog(long did, int currentAccount) { - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id < 0) { - return MessagesController.getInstance(currentAccount).getChat(-lower_id); - } - return null; - } - public static boolean hasPhoto(TLRPC.Chat chat) { return chat != null && chat.photo != null && !(chat.photo instanceof TLRPC.TL_chatPhotoEmpty); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ChatThemeController.java b/TMessagesProj/src/main/java/org/telegram/messenger/ChatThemeController.java new file mode 100644 index 000000000..0e82ae93a --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ChatThemeController.java @@ -0,0 +1,289 @@ +package org.telegram.messenger; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.text.TextUtils; +import android.util.LongSparseArray; + +import com.google.android.exoplayer2.util.Log; + +import org.telegram.tgnet.ConnectionsManager; +import org.telegram.tgnet.RequestDelegate; +import org.telegram.tgnet.ResultCallback; +import org.telegram.tgnet.SerializedData; +import org.telegram.tgnet.TLObject; +import org.telegram.tgnet.TLRPC; +import org.telegram.ui.ActionBar.ChatTheme; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class ChatThemeController extends BaseController { + + private static final long reloadTimeoutMs = 2 * 60 * 60 * 1000; + private static volatile DispatchQueue chatThemeQueue = new DispatchQueue("stageQueue"); + + private static final HashMap themeIdWallpaperMap = new HashMap<>(); + private static final HashMap themeIdWallpaperThumbMap = new HashMap<>(); + private static List allChatThemes; + private static volatile int themesHash; + private static volatile long lastReloadTimeMs; + + public static void init() { + SharedPreferences preferences = getSharedPreferences(); + themesHash = 0; + lastReloadTimeMs = 0; + if (!BuildVars.DEBUG_VERSION) { + preferences.getInt("hash", 0); + lastReloadTimeMs = preferences.getLong("lastReload", 0); + } + + allChatThemes = getAllChatThemesFromPrefs(); + Emoji.preloadEmoji("❌"); + if (!allChatThemes.isEmpty()) { + for (ChatTheme chatTheme : allChatThemes) { + Emoji.preloadEmoji(chatTheme.getEmoticon()); + } + } else { + Emoji.preloadEmoji("\uD83E\uDD81"); + Emoji.preloadEmoji("⛄"); + Emoji.preloadEmoji("\uD83D\uDC8E"); + Emoji.preloadEmoji("\uD83D\uDC68\u200D\uD83C\uDFEB"); + Emoji.preloadEmoji("\uD83C\uDF37"); + Emoji.preloadEmoji("\uD83D\uDD2E"); + Emoji.preloadEmoji("\uD83C\uDF84"); + Emoji.preloadEmoji("\uD83C\uDFAE"); + } + } + + public static void requestAllChatThemes(final ResultCallback> callback, boolean withDefault) { + if (themesHash == 0 || lastReloadTimeMs == 0) { + init(); + } + + boolean needReload = System.currentTimeMillis() - lastReloadTimeMs > reloadTimeoutMs; + if (allChatThemes == null || allChatThemes.isEmpty() || needReload) { + TLRPC.TL_account_getChatThemes request = new TLRPC.TL_account_getChatThemes(); + request.hash = themesHash; + ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(request, (response, error) -> chatThemeQueue.postRunnable(() -> { + boolean isError = false; + final List chatThemes; + if (response instanceof TLRPC.TL_account_chatThemes) { + TLRPC.TL_account_chatThemes resp = (TLRPC.TL_account_chatThemes) response; + themesHash = resp.hash; + lastReloadTimeMs = System.currentTimeMillis(); + + SharedPreferences.Editor editor = getSharedPreferences().edit(); + editor.clear(); + editor.putInt("hash", themesHash); + editor.putLong("lastReload", lastReloadTimeMs); + editor.putInt("count", resp.themes.size()); + chatThemes = new ArrayList<>(resp.themes.size()); + for (int i = 0; i < resp.themes.size(); ++i) { + TLRPC.TL_chatTheme tlChatTheme = resp.themes.get(i); + Emoji.preloadEmoji(tlChatTheme.emoticon); + SerializedData data = new SerializedData(tlChatTheme.getObjectSize()); + tlChatTheme.serializeToStream(data); + editor.putString("theme_" + i, Utilities.bytesToHex(data.toByteArray())); + ChatTheme chatTheme = new ChatTheme(tlChatTheme, false); + chatTheme.preloadWallpaper(); + chatThemes.add(chatTheme); + } + editor.apply(); + } else if (response instanceof TLRPC.TL_account_chatThemesNotModified) { + chatThemes = getAllChatThemesFromPrefs(); + } else { + chatThemes = null; + isError = true; + AndroidUtilities.runOnUIThread(() -> callback.onError(error)); + } + if (!isError) { + if (withDefault && !chatThemes.get(0).isDefault) { + chatThemes.add(0, ChatTheme.getDefault()); + } + for (ChatTheme theme : chatThemes) { + theme.initColors(); + } + AndroidUtilities.runOnUIThread(() -> { + allChatThemes = new ArrayList<>(chatThemes); + callback.onComplete(chatThemes); + }); + } + })); + } else { + List chatThemes = new ArrayList<>(allChatThemes); + if (withDefault && !chatThemes.get(0).isDefault) { + chatThemes.add(0, ChatTheme.getDefault()); + } + for (ChatTheme theme : chatThemes) { + theme.initColors(); + } + callback.onComplete(chatThemes); + } + } + + private static SharedPreferences getSharedPreferences() { + return ApplicationLoader.applicationContext.getSharedPreferences("chatthemeconfig", Context.MODE_PRIVATE); + } + private static SharedPreferences getEmojiSharedPreferences() { + return ApplicationLoader.applicationContext.getSharedPreferences("chatthemeconfig_emoji", Context.MODE_PRIVATE); + } + + private static List getAllChatThemesFromPrefs() { + SharedPreferences preferences = getSharedPreferences(); + int count = preferences.getInt("count", 0); + List themes = new ArrayList<>(count); + for (int i = 0; i < count; ++i) { + String value = preferences.getString("theme_" + i, ""); + SerializedData serializedData = new SerializedData(Utilities.hexToBytes(value)); + try { + TLRPC.TL_chatTheme chatTheme = TLRPC.TL_chatTheme.TLdeserialize(serializedData, serializedData.readInt32(true), true); + if (chatTheme != null) { + themes.add(new ChatTheme(chatTheme, false)); + } + } catch (Throwable e) { + FileLog.e(e); + } + } + return themes; + } + + public static void requestChatTheme(final String emoticon, final ResultCallback callback) { + if (TextUtils.isEmpty(emoticon)) { + callback.onComplete(null); + return; + } + requestAllChatThemes(new ResultCallback>() { + @Override + public void onComplete(List result) { + for (ChatTheme theme : result) { + if (emoticon.equals(theme.getEmoticon())) { + theme.initColors(); + callback.onComplete(theme); + break; + } + } + } + @Override + public void onError(TLRPC.TL_error error) { + callback.onComplete(null); + } + }, false); + } + + + private static final ChatThemeController[] instances = new ChatThemeController[UserConfig.MAX_ACCOUNT_COUNT]; + + public static ChatThemeController getInstance(int accountNum) { + ChatThemeController local = instances[accountNum]; + if (local == null) { + synchronized (ChatThemeController.class) { + local = instances[accountNum]; + if (local == null) { + local = new ChatThemeController(accountNum); + instances[accountNum] = local; + } + } + } + return local; + } + + + private final LongSparseArray dialogEmoticonsMap = new LongSparseArray<>(); + + public ChatThemeController(int num) { + super(num); + } + + public void setDialogTheme(long dialogId, String emoticon, boolean sendRequest) { + String oldEmoticon = dialogEmoticonsMap.get(dialogId); + if (TextUtils.equals(oldEmoticon, emoticon)) { + return; + } + + if (emoticon == null) { + dialogEmoticonsMap.delete(dialogId); + } else { + dialogEmoticonsMap.put(dialogId, emoticon); + } + + getEmojiSharedPreferences().edit() + .putString("chatTheme_" + currentAccount + "_" + dialogId, emoticon) + .apply(); + + if (sendRequest) { + TLRPC.TL_messages_setChatTheme request = new TLRPC.TL_messages_setChatTheme(); + request.emoticon = emoticon != null ? emoticon : ""; + request.peer = getMessagesController().getInputPeer(dialogId); + getConnectionsManager().sendRequest(request, null); + } + } + + public ChatTheme getDialogTheme(long dialogId) { + String emoticon = dialogEmoticonsMap.get(dialogId); + if (emoticon == null) { + emoticon = getEmojiSharedPreferences().getString("chatTheme_" + currentAccount + "_" + dialogId, null); + dialogEmoticonsMap.put(dialogId, emoticon); + } + if (emoticon != null) { + for (ChatTheme theme : allChatThemes) { + if (emoticon.equals(theme.getEmoticon())) { + return theme; + } + } + } + return null; + } + + public static void preloadAllWallpaperImages(boolean isDark) { + for (ChatTheme chatTheme : allChatThemes) { + long themeId = chatTheme.getTlTheme(isDark).id; + if (themeIdWallpaperMap.containsKey(themeId)) { + continue; + } + chatTheme.loadWallpaper(isDark, result -> { + if (result != null) { + themeIdWallpaperMap.put(result.first, result.second); + } + }); + } + } + + public static void preloadAllWallpaperThumbs(boolean isDark) { + for (ChatTheme chatTheme : allChatThemes) { + long themeId = chatTheme.getTlTheme(isDark).id; + if (themeIdWallpaperThumbMap.containsKey(themeId)) { + continue; + } + chatTheme.loadWallpaperThumb(isDark, result -> { + if (result != null) { + themeIdWallpaperThumbMap.put(result.first, result.second); + } + }); + } + } + + public static void clearWallpaperImages() { + themeIdWallpaperMap.clear(); + } + + public static void clearWallpaperThumbImages() { + themeIdWallpaperThumbMap.clear(); + } + + public static Bitmap getWallpaperBitmap(long themeId) { + return themeIdWallpaperMap.get(themeId); + } + + public static Bitmap getWallpaperThumbBitmap(long themeId) { + return themeIdWallpaperThumbMap.get(themeId); + } + + public void clearCache() { + themesHash = 0; + lastReloadTimeMs = 0; + getSharedPreferences().edit().clear().apply(); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ChatsWidgetService.java b/TMessagesProj/src/main/java/org/telegram/messenger/ChatsWidgetService.java index f6615abea..e3b0ef2f5 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ChatsWidgetService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ChatsWidgetService.java @@ -17,8 +17,6 @@ import android.os.Build; import android.os.Bundle; import android.text.SpannableStringBuilder; import android.text.Spanned; -import android.util.LongSparseArray; -import android.util.SparseArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; @@ -32,6 +30,8 @@ import org.telegram.ui.EditWidgetActivity; import java.io.File; import java.util.ArrayList; +import androidx.collection.LongSparseArray; + public class ChatsWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { @@ -101,8 +101,8 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; - if (id > 0) { - user = accountInstance.getMessagesController().getUser((int) (long) id); + if (DialogObject.isUserDialog(id)) { + user = accountInstance.getMessagesController().getUser(id); if (user != null) { if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); @@ -113,12 +113,12 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { } else { name = ContactsController.formatName(user.first_name, user.last_name); } - if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user != null && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { + if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } else { - chat = accountInstance.getMessagesController().getChat(-(int) (long) id); + chat = accountInstance.getMessagesController().getChat(-id); if (chat != null) { name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { @@ -179,8 +179,8 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { if (message != null) { TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; - int fromId = message.getFromChatId(); - if (fromId > 0) { + long fromId = message.getFromChatId(); + if (DialogObject.isUserDialog(fromId)) { fromUser = accountInstance.getMessagesController().getUser(fromId); } else { fromChat = accountInstance.getMessagesController().getChat(-fromId); @@ -198,7 +198,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { textColor = mContext.getResources().getColor(R.color.widget_action_text); } else { boolean needEmoji = true; - if (chat != null && chat.id > 0 && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat))) { + if (chat != null && fromChat == null && (!ChatObject.isChannel(chat) || ChatObject.isMegagroup(chat))) { if (message.isOutOwner()) { messageNameString = LocaleController.getString("FromYou", R.string.FromYou); } else if (fromUser != null) { @@ -303,7 +303,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } else { messageString = message.messageText; - AndroidUtilities.highlightText(messageString, message.highlightedWords); + AndroidUtilities.highlightText(messageString, message.highlightedWords, null); } if (message.messageOwner.media != null && !message.isMediaEmpty()) { textColor = mContext.getResources().getColor(R.color.widget_action_text); @@ -339,10 +339,10 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { Bundle extras = new Bundle(); - if (id > 0) { - extras.putInt("userId", (int) (long) id); + if (DialogObject.isUserDialog(id)) { + extras.putLong("userId", id); } else { - extras.putInt("chatId", -(int) (long) id); + extras.putLong("chatId", -id); } extras.putInt("currentAccount", accountInstance.getCurrentAccount()); @@ -385,7 +385,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { accountInstance.getMessagesController().putChats(chats, true); messageObjects.clear(); for (int a = 0, N = messages.size(); a < N; a++) { - MessageObject messageObject = new MessageObject(accountInstance.getCurrentAccount(), messages.valueAt(a), (SparseArray) null, null, false, true); + MessageObject messageObject = new MessageObject(accountInstance.getCurrentAccount(), messages.valueAt(a), (LongSparseArray) null, null, false, true); messageObjects.put(messages.keyAt(a), messageObject); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java index f3f33cb91..07c4a6de9 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java @@ -27,7 +27,6 @@ import android.text.TextUtils; import android.util.SparseArray; import org.telegram.PhoneFormat.PhoneFormat; -import org.telegram.messenger.support.SparseLongArray; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Components.Bulletin; @@ -38,6 +37,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; +import androidx.collection.LongSparseArray; + public class ContactsController extends BaseController { private Account systemAccount; @@ -51,7 +52,7 @@ public class ContactsController extends BaseController { private boolean contactsBookLoaded; private boolean migratingContacts; private String lastContactsVersions = ""; - private ArrayList delayedContactsUpdate = new ArrayList<>(); + private ArrayList delayedContactsUpdate = new ArrayList<>(); private String inviteLink; private boolean updatingInviteLink; private HashMap sectionsToReplace = new HashMap<>(); @@ -167,7 +168,7 @@ public class ContactsController extends BaseController { public ArrayList phoneBookSectionsArray = new ArrayList<>(); public ArrayList contacts = new ArrayList<>(); - public ConcurrentHashMap contactsDict = new ConcurrentHashMap<>(20, 1.0f, 2); + public ConcurrentHashMap contactsDict = new ConcurrentHashMap<>(20, 1.0f, 2); public HashMap> usersSectionsDict = new HashMap<>(); public ArrayList sortedUsersSectionsArray = new ArrayList<>(); @@ -581,9 +582,7 @@ public class ContactsController extends BaseController { if (pCur != null) { int count = pCur.getCount(); if (count > 0) { - if (contactsMap == null) { - contactsMap = new HashMap<>(count); - } + contactsMap = new HashMap<>(count); while (pCur.moveToNext()) { String number = pCur.getString(1); String accountType = pCur.getString(5); @@ -695,7 +694,7 @@ public class ContactsController extends BaseController { String fname = pCur.getString(1); String sname = pCur.getString(2); String mname = pCur.getString(3); - Contact contact = contactsMap.get(lookup_key); + Contact contact = contactsMap != null ? contactsMap.get(lookup_key) : null; if (contact != null && !contact.namesFilled) { if (contact.isGoodProvider) { if (fname != null) { @@ -1297,7 +1296,7 @@ public class ContactsController extends BaseController { if (first) { contactsLoaded = true; } - if (!delayedContactsUpdate.isEmpty() && contactsLoaded && contactsBookLoaded) { + if (!delayedContactsUpdate.isEmpty() && contactsLoaded) { applyContactsUpdates(delayedContactsUpdate, null, null, null); delayedContactsUpdate.clear(); } @@ -1316,7 +1315,7 @@ public class ContactsController extends BaseController { } } - private int getContactsHash(ArrayList contacts) { + private long getContactsHash(ArrayList contacts) { long acc = 0; contacts = new ArrayList<>(contacts); Collections.sort(contacts, (tl_contact, tl_contact2) -> { @@ -1330,16 +1329,16 @@ public class ContactsController extends BaseController { int count = contacts.size(); for (int a = -1; a < count; a++) { if (a == -1) { - acc = ((acc * 20261) + 0x80000000L + getUserConfig().contactsSavedCount) % 0x80000000L; + acc = MediaDataController.calcHash(acc, getUserConfig().contactsSavedCount); } else { TLRPC.TL_contact set = contacts.get(a); - acc = ((acc * 20261) + 0x80000000L + set.user_id) % 0x80000000L; + acc = MediaDataController.calcHash(acc, set.user_id); } } - return (int) acc; + return acc; } - public void loadContacts(boolean fromCache, final int hash) { + public void loadContacts(boolean fromCache, final long hash) { synchronized (loadContactsSync) { loadingContacts = true; } @@ -1391,7 +1390,7 @@ public class ContactsController extends BaseController { AndroidUtilities.runOnUIThread(() -> { getMessagesController().putUsers(usersArr, from == 1); - final SparseArray usersDict = new SparseArray<>(); + final LongSparseArray usersDict = new LongSparseArray<>(); final boolean isEmpty = contactsArr.isEmpty(); @@ -1463,7 +1462,7 @@ public class ContactsController extends BaseController { return name1.compareTo(name2); }); - final ConcurrentHashMap contactsDictionary = new ConcurrentHashMap<>(20, 1.0f, 2); + final ConcurrentHashMap contactsDictionary = new ConcurrentHashMap<>(20, 1.0f, 2); final HashMap> sectionsDict = new HashMap<>(); final HashMap> sectionsDictMutual = new HashMap<>(); final ArrayList sortedSectionsArray = new ArrayList<>(); @@ -1593,8 +1592,8 @@ public class ContactsController extends BaseController { }); } - public boolean isContact(int uid) { - return contactsDict.get(uid) != null; + public boolean isContact(long userId) { + return contactsDict.get(userId) != null; } public void reloadContactsStatusesMaybe() { @@ -1838,10 +1837,10 @@ public class ContactsController extends BaseController { final ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver(); Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build(); cursor = contentResolver.query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null); - SparseLongArray bookContacts = new SparseLongArray(); + LongSparseArray bookContacts = new LongSparseArray<>(); if (cursor != null) { while (cursor.moveToNext()) { - bookContacts.put(cursor.getInt(1), cursor.getLong(0)); + bookContacts.put(cursor.getLong(1), cursor.getLong(0)); } cursor.close(); cursor = null; @@ -1867,12 +1866,12 @@ public class ContactsController extends BaseController { Utilities.phoneBookQueue.postRunnable(() -> performWriteContactsToPhoneBookInternal(contactsArray)); } - private void applyContactsUpdates(ArrayList ids, ConcurrentHashMap userDict, ArrayList newC, ArrayList contactsTD) { + private void applyContactsUpdates(ArrayList ids, ConcurrentHashMap userDict, ArrayList newC, ArrayList contactsTD) { if (newC == null || contactsTD == null) { newC = new ArrayList<>(); contactsTD = new ArrayList<>(); for (int a = 0; a < ids.size(); a++) { - Integer uid = ids.get(a); + Long uid = ids.get(a); if (uid > 0) { TLRPC.TL_contact contact = new TLRPC.TL_contact(); contact.user_id = uid; @@ -1920,7 +1919,7 @@ public class ContactsController extends BaseController { } for (int a = 0; a < contactsTD.size(); a++) { - final Integer uid = contactsTD.get(a); + final Long uid = contactsTD.get(a); Utilities.phoneBookQueue.postRunnable(() -> deleteContactFromPhoneBook(uid)); TLRPC.User user = null; @@ -1960,7 +1959,7 @@ public class ContactsController extends BaseController { Utilities.stageQueue.postRunnable(() -> loadContacts(false, 0)); } else { final ArrayList newContacts = newC; - final ArrayList contactsToDelete = contactsTD; + final ArrayList contactsToDelete = contactsTD; AndroidUtilities.runOnUIThread(() -> { for (int a = 0; a < newContacts.size(); a++) { TLRPC.TL_contact contact = newContacts.get(a); @@ -1970,7 +1969,7 @@ public class ContactsController extends BaseController { } } for (int a = 0; a < contactsToDelete.size(); a++) { - Integer uid = contactsToDelete.get(a); + Long uid = contactsToDelete.get(a); TLRPC.TL_contact contact = contactsDict.get(uid); if (contact != null) { contacts.remove(contact); @@ -1988,10 +1987,10 @@ public class ContactsController extends BaseController { } } - public void processContactsUpdates(ArrayList ids, ConcurrentHashMap userDict) { + public void processContactsUpdates(ArrayList ids, ConcurrentHashMap userDict) { final ArrayList newContacts = new ArrayList<>(); - final ArrayList contactsToDelete = new ArrayList<>(); - for (Integer uid : ids) { + final ArrayList contactsToDelete = new ArrayList<>(); + for (Long uid : ids) { if (uid > 0) { TLRPC.TL_contact contact = new TLRPC.TL_contact(); contact.user_id = uid; @@ -2115,7 +2114,7 @@ public class ContactsController extends BaseController { return res; } - private void deleteContactFromPhoneBook(int uid) { + private void deleteContactFromPhoneBook(long uid) { if (!hasContactsPermission()) { return; } @@ -2223,8 +2222,9 @@ public class ContactsController extends BaseController { return; } TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts(); - final ArrayList uids = new ArrayList<>(); - for (TLRPC.User user : users) { + final ArrayList uids = new ArrayList<>(); + for (int a = 0, N = users.size(); a < N; a++) { + TLRPC.User user = users.get(a); TLRPC.InputUser inputUser = getMessagesController().getInputUser(user); if (inputUser == null) { continue; @@ -2512,7 +2512,7 @@ public class ContactsController extends BaseController { reloadContactsStatuses(); } - public void createOrUpdateConnectionServiceContact(int id, String firstName, String lastName) { + public void createOrUpdateConnectionServiceContact(long id, String firstName, String lastName) { if (!hasContactsPermission()) { return; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsLoadingObserver.java b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsLoadingObserver.java index 2771151bd..5f7ddba16 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsLoadingObserver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsLoadingObserver.java @@ -13,12 +13,9 @@ public final class ContactsLoadingObserver { void onResult(boolean contactsLoaded); } - private final NotificationCenter.NotificationCenterDelegate observer = new NotificationCenter.NotificationCenterDelegate() { - @Override - public void didReceivedNotification(int id, int account, Object... args) { - if (id == NotificationCenter.contactsDidLoad) { - onContactsLoadingStateUpdated(account, false); - } + private final NotificationCenter.NotificationCenterDelegate observer = (id, account, args) -> { + if (id == NotificationCenter.contactsDidLoad) { + onContactsLoadingStateUpdated(account, false); } }; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsWidgetService.java b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsWidgetService.java index ed7a7a0f2..2a618dbbe 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsWidgetService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsWidgetService.java @@ -14,7 +14,6 @@ import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.os.Bundle; -import android.util.LongSparseArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; @@ -27,6 +26,8 @@ import org.telegram.ui.EditWidgetActivity; import java.io.File; import java.util.ArrayList; +import androidx.collection.LongSparseArray; + public class ContactsWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { @@ -104,8 +105,8 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; - if (id > 0) { - user = accountInstance.getMessagesController().getUser((int) (long) id); + if (DialogObject.isUserDialog(id)) { + user = accountInstance.getMessagesController().getUser(id); if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); } else if (UserObject.isReplyUser(user)) { @@ -119,7 +120,7 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor photoPath = user.photo.photo_small; } } else { - chat = accountInstance.getMessagesController().getChat(-(int) (long) id); + chat = accountInstance.getMessagesController().getChat(-id); if (chat != null) { name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { @@ -193,10 +194,10 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor Bundle extras = new Bundle(); - if (id > 0) { - extras.putInt("userId", (int) (long) id); + if (DialogObject.isUserDialog(id)) { + extras.putLong("userId", id); } else { - extras.putInt("chatId", -(int) (long) id); + extras.putLong("chatId", -id); } extras.putInt("currentAccount", accountInstance.getCurrentAccount()); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/DialogObject.java b/TMessagesProj/src/main/java/org/telegram/messenger/DialogObject.java index 8ce63a3de..30b87c88b 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/DialogObject.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/DialogObject.java @@ -16,28 +16,12 @@ public class DialogObject { return dialog != null && (dialog.flags & 1) != 0; } - public static long makeSecretDialogId(int chatId) { - return ((long) chatId) << 32; - } - public static long makeFolderDialogId(int folderId) { - return (((long) 2) << 32) | folderId; + return 0x2000000000000000L | (long) folderId; } public static boolean isFolderDialogId(long dialogId) { - int lowerId = (int) dialogId; - int highId = (int) (dialogId >> 32); - return lowerId != 0 && highId == 2; - } - - public static boolean isPeerDialogId(long dialogId) { - int lowerId = (int) dialogId; - int highId = (int) (dialogId >> 32); - return lowerId != 0 && highId != 2 && highId != 1; - } - - public static boolean isSecretDialogId(long dialogId) { - return ((int) dialogId) == 0; + return (dialogId & 0x2000000000000000L) != 0 && (dialogId & 0x8000000000000000L) == 0; } public static void initDialog(TLRPC.Dialog dialog) { @@ -90,4 +74,28 @@ public class DialogObject { public static long getLastMessageOrDraftDate(TLRPC.Dialog dialog, TLRPC.DraftMessage draftMessage) { return draftMessage != null && draftMessage.date >= dialog.last_message_date ? draftMessage.date : dialog.last_message_date; } + + public static boolean isChatDialog(long dialogId) { + return !isEncryptedDialog(dialogId) && !isFolderDialogId(dialogId) && dialogId < 0; + } + + public static boolean isUserDialog(long dialogId) { + return !isEncryptedDialog(dialogId) && !isFolderDialogId(dialogId) && dialogId > 0; + } + + public static boolean isEncryptedDialog(long dialogId) { + return (dialogId & 0x4000000000000000L) != 0 && (dialogId & 0x8000000000000000L) == 0; + } + + public static long makeEncryptedDialogId(long chatId) { + return 0x4000000000000000L | (chatId & 0x00000000ffffffffL); + } + + public static int getEncryptedChatId(long dialogId) { + return (int) (dialogId & 0x00000000ffffffffL); + } + + public static int getFolderId(long dialogId) { + return (int) dialogId; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/DocumentObject.java b/TMessagesProj/src/main/java/org/telegram/messenger/DocumentObject.java index 585897e68..67654925a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/DocumentObject.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/DocumentObject.java @@ -12,12 +12,12 @@ public class DocumentObject { public static class ThemeDocument extends TLRPC.TL_document { - public TLRPC.TL_themeSettings themeSettings; + public TLRPC.ThemeSettings themeSettings; public TLRPC.Document wallpaper; public Theme.ThemeInfo baseTheme; public Theme.ThemeAccent accent; - public ThemeDocument(TLRPC.TL_themeSettings settings) { + public ThemeDocument(TLRPC.ThemeSettings settings) { themeSettings = settings; baseTheme = Theme.getTheme(Theme.getBaseThemeKey(settings)); accent = baseTheme.createNewAccent(settings); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/DownloadController.java b/TMessagesProj/src/main/java/org/telegram/messenger/DownloadController.java index 05e794787..0afa4510f 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/DownloadController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/DownloadController.java @@ -14,7 +14,6 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.ConnectivityManager; -import android.util.LongSparseArray; import android.util.Pair; import android.util.SparseArray; @@ -24,6 +23,8 @@ import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; +import androidx.collection.LongSparseArray; + public class DownloadController extends BaseController implements NotificationCenter.NotificationCenterDelegate { public interface FileDownloadProgressListener { @@ -629,7 +630,7 @@ public class DownloadController extends BaseController implements NotificationCe index = 2; } } else { - TLRPC.Chat chat = message.peer_id != null && message.peer_id.channel_id != 0 ? getMessagesController().getChat(message.peer_id.channel_id) : null; + TLRPC.Chat chat = message.peer_id.channel_id != 0 ? getMessagesController().getChat(message.peer_id.channel_id) : null; if (ChatObject.isChannel(chat) && chat.megagroup) { if (message.from_id instanceof TLRPC.TL_peerUser && getContactsController().contactsDict.containsKey(message.from_id.user_id)) { index = 0; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java b/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java index 2a22f07dc..0b63947e3 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Emoji.java @@ -50,6 +50,7 @@ public class Emoji { public static HashMap emojiColor = new HashMap<>(); private static boolean recentEmojiLoaded; private static Runnable invalidateUiRunnable = () -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.emojiLoaded); + public static float emojiDrawingYOffset; private final static int MAX_RECENT_EMOJI_COUNT = 48; @@ -544,7 +545,16 @@ public class Emoji { restoreAlpha = true; getDrawable().setAlpha(paint.getAlpha()); } + boolean needRestore = false; + if (emojiDrawingYOffset != 0) { + needRestore = true; + canvas.save(); + canvas.translate(0, emojiDrawingYOffset); + } super.draw(canvas, text, start, end, x, top, y, bottom, paint); + if (needRestore) { + canvas.restore(); + } if (restoreAlpha) { getDrawable().setAlpha(255); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/EmojiData.java b/TMessagesProj/src/main/java/org/telegram/messenger/EmojiData.java index 19e3dbcbd..f4763190a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/EmojiData.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/EmojiData.java @@ -529,6 +529,10 @@ public class EmojiData { return "⚰".equals(emoji); } + public static boolean hasEmojiSupportVibration(String emoji) { + return isHeartEmoji(emoji) || isPeachEmoji(emoji) || isCofinEmoji(emoji); + } + static { for (int a = 0; a < emojiToFE0F.length; a++) { emojiToFE0FMap.put(emojiToFE0F[a], true); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetProvider.java b/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetProvider.java index 33e1f7910..60c37345a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetProvider.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetProvider.java @@ -10,7 +10,6 @@ import android.content.SharedPreferences; import android.net.Uri; import android.widget.RemoteViews; -import org.telegram.ui.FeedWidgetConfigActivity; import org.telegram.ui.LaunchActivity; public class FeedWidgetProvider extends AppWidgetProvider { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetService.java b/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetService.java index eb92e80ea..40a1ea679 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FeedWidgetService.java @@ -35,7 +35,6 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N private ArrayList messages = new ArrayList<>(); private Context mContext; - private int appWidgetId; private long dialogId; private int classGuid; private AccountInstance accountInstance; @@ -43,7 +42,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N public FeedRemoteViewsFactory(Context context, Intent intent) { mContext = context; - appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); SharedPreferences preferences = context.getSharedPreferences("shortcut_widget", Activity.MODE_PRIVATE); int accountId = preferences.getInt("account" + appWidgetId, -1); if (accountId >= 0) { @@ -107,7 +106,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N } Bundle extras = new Bundle(); - extras.putInt("chatId", (int) -messageObject.getDialogId()); + extras.putLong("chatId", -messageObject.getDialogId()); extras.putInt("message_id", messageObject.getId()); extras.putInt("currentAccount", accountInstance.getCurrentAccount()); @@ -144,7 +143,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N if (classGuid == 0) { classGuid = ConnectionsManager.generateClassGuid(); } - accountInstance.getMessagesController().loadMessages(dialogId, 0, false, 20, 0, 0, true, 0, classGuid, 0, 0, true, 0, 0, 0, 1); + accountInstance.getMessagesController().loadMessages(dialogId, 0, false, 20, 0, 0, true, 0, classGuid, 0, 0, 0, 0, 0, 1); }); try { countDownLatch.await(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileRefController.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileRefController.java index 0803dc188..d42553426 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileRefController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileRefController.java @@ -71,11 +71,11 @@ public class FileRefController extends BaseController { public static String getKeyForParentObject(Object parentObject) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; - int channelId = messageObject.getChannelId(); + long channelId = messageObject.getChannelId(); return "message" + messageObject.getRealId() + "_" + channelId + "_" + messageObject.scheduled; } else if (parentObject instanceof TLRPC.Message) { TLRPC.Message message = (TLRPC.Message) parentObject; - int channelId = message.peer_id != null ? message.peer_id.channel_id : 0; + long channelId = message.peer_id != null ? message.peer_id.channel_id : 0; return "message" + message.id + "_" + channelId + "_" + message.from_scheduled; } else if (parentObject instanceof TLRPC.WebPage) { TLRPC.WebPage webPage = (TLRPC.WebPage) parentObject; @@ -310,10 +310,10 @@ public class FileRefController extends BaseController { private void requestReferenceFromServer(Object parentObject, String locationKey, String parentKey, Object[] args) { if (parentObject instanceof MessageObject) { MessageObject messageObject = (MessageObject) parentObject; - int channelId = messageObject.getChannelId(); + long channelId = messageObject.getChannelId(); if (messageObject.scheduled) { TLRPC.TL_messages_getScheduledMessages req = new TLRPC.TL_messages_getScheduledMessages(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); req.id.add(messageObject.getRealId()); getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false)); } else if (channelId != 0) { @@ -403,7 +403,7 @@ public class FileRefController extends BaseController { } getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false)); } else if (string.startsWith("avatar_")) { - int id = Utilities.parseInt(string); + long id = Utilities.parseLong(string); if (id > 0) { TLRPC.TL_photos_getUserPhotos req = new TLRPC.TL_photos_getUserPhotos(); req.limit = 80; @@ -423,7 +423,7 @@ public class FileRefController extends BaseController { } else if (string.startsWith("sent_")) { String[] params = string.split("_"); if (params.length == 3) { - int channelId = Utilities.parseInt(params[1]); + long channelId = Utilities.parseLong(params[1]); if (channelId != 0) { TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); req.channel = getMessagesController().getInputChannel(channelId); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java b/TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java index 8690f97f1..3bfb40ca8 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ForwardingMessagesParams.java @@ -22,13 +22,13 @@ public class ForwardingMessagesParams { public boolean willSeeSenders; public boolean multiplyUsers; - public ArrayList pollChoosenAnswers = new ArrayList(); + public ArrayList pollChoosenAnswers = new ArrayList<>(); public ForwardingMessagesParams(ArrayList messages, long newDialogId) { this.messages = messages; hasCaption = false; hasSenders = false; - isSecret = DialogObject.isSecretDialogId(newDialogId); + isSecret = DialogObject.isEncryptedDialog(newDialogId); ArrayList hiddenSendersName = new ArrayList<>(); for (int i = 0; i < messages.size(); i++) { MessageObject messageObject = messages.get(i); @@ -53,10 +53,11 @@ public class ForwardingMessagesParams { message.reply_markup = messageObject.messageOwner.reply_markup; message.post = messageObject.messageOwner.post; message.legacy = messageObject.messageOwner.legacy; + message.restriction_reason = messageObject.messageOwner.restriction_reason; TLRPC.MessageFwdHeader header = null; - int clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId; + long clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId; if (!isSecret) { if (messageObject.messageOwner.fwd_from != null) { header = messageObject.messageOwner.fwd_from; @@ -135,10 +136,10 @@ public class ForwardingMessagesParams { } } - ArrayList uids = new ArrayList<>(); - for (int a = 1; a < messages.size(); a++) { + ArrayList uids = new ArrayList<>(); + for (int a = 0; a < messages.size(); a++) { MessageObject object = messages.get(a); - int uid; + long uid; if (object.isFromUser()) { uid = object.messageOwner.from_id.user_id; } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FourierTransform.java b/TMessagesProj/src/main/java/org/telegram/messenger/FourierTransform.java index 1f9ee87bb..cc32ddc5f 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FourierTransform.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FourierTransform.java @@ -56,7 +56,7 @@ public abstract class FourierTransform { } if (whichAverage == LINAVG) { - int avgWidth = (int) spectrum.length / averages.length; + int avgWidth = spectrum.length / averages.length; for (int i = 0; i < averages.length; i++) { float avg = 0; int j; @@ -140,15 +140,6 @@ public abstract class FourierTransform { whichAverage = LOGAVG; } - /** - * Sets the window to use on the samples before taking the forward transform. - * If an invalid window is asked for, an error will be reported and the - * current window will not be changed. - * - * @param windowFunction - */ - - /** * Returns the length of the time domain signal expected by this transform. * @@ -225,8 +216,7 @@ public abstract class FourierTransform { if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1; // all other cases float fraction = freq / (float) sampleRate; - int i = Math.round(timeSize * fraction); - return i; + return Math.round(timeSize * fraction); } /** diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/GcmPushListenerService.java b/TMessagesProj/src/main/java/org/telegram/messenger/GcmPushListenerService.java index 902fa3802..0ea1d929a 100755 --- a/TMessagesProj/src/main/java/org/telegram/messenger/GcmPushListenerService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/GcmPushListenerService.java @@ -11,7 +11,6 @@ package org.telegram.messenger; import android.os.SystemClock; import android.text.TextUtils; import android.util.Base64; -import android.util.SparseArray; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; @@ -28,6 +27,8 @@ import java.util.Locale; import java.util.Map; import java.util.concurrent.CountDownLatch; +import androidx.collection.LongSparseArray; + public class GcmPushListenerService extends FirebaseMessagingService { public static final int NOTIFICATION_ID = 1; @@ -121,11 +122,13 @@ public class GcmPushListenerService extends FirebaseMessagingService { } else { userIdObject = null; } - int accountUserId; + long accountUserId; if (userIdObject == null) { accountUserId = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); } else { - if (userIdObject instanceof Integer) { + if (userIdObject instanceof Long) { + accountUserId = (Long) userIdObject; + } else if (userIdObject instanceof Integer) { accountUserId = (Integer) userIdObject; } else if (userIdObject instanceof String) { accountUserId = Utilities.parseInt((String) userIdObject); @@ -206,31 +209,31 @@ public class GcmPushListenerService extends FirebaseMessagingService { } } - int channel_id; - int chat_id; - int user_id; + long channel_id; + long chat_id; + long user_id; long dialogId = 0; boolean scheduled; if (custom.has("channel_id")) { - channel_id = custom.getInt("channel_id"); + channel_id = custom.getLong("channel_id"); dialogId = -channel_id; } else { channel_id = 0; } if (custom.has("from_id")) { - user_id = custom.getInt("from_id"); + user_id = custom.getLong("from_id"); dialogId = user_id; } else { user_id = 0; } if (custom.has("chat_id")) { - chat_id = custom.getInt("chat_id"); + chat_id = custom.getLong("chat_id"); dialogId = -chat_id; } else { chat_id = 0; } if (custom.has("encryption_id")) { - dialogId = ((long) custom.getInt("encryption_id")) << 32; + dialogId = DialogObject.makeEncryptedDialogId(custom.getInt("encryption_id")); } if (custom.has("schedule")) { scheduled = custom.getInt("schedule") == 1; @@ -238,7 +241,7 @@ public class GcmPushListenerService extends FirebaseMessagingService { scheduled = false; } if (dialogId == 0 && "ENCRYPTED_MESSAGE".equals(loc_key)) { - dialogId = -(1L << 32); + dialogId = NotificationsController.globalSecretChatId; } boolean canRelease = true; if (dialogId != 0) { @@ -269,12 +272,12 @@ public class GcmPushListenerService extends FirebaseMessagingService { } else if ("MESSAGE_DELETED".equals(loc_key)) { String messages = custom.getString("messages"); String[] messagesArgs = messages.split(","); - SparseArray> deletedMessages = new SparseArray<>(); + LongSparseArray> deletedMessages = new LongSparseArray<>(); ArrayList ids = new ArrayList<>(); for (int a = 0; a < messagesArgs.length; a++) { ids.add(Utilities.parseInt(messagesArgs[a])); } - deletedMessages.put(channel_id, ids); + deletedMessages.put(-channel_id, ids); NotificationsController.getInstance(currentAccount).removeDeletedMessagesFromNotifications(deletedMessages); MessagesController.getInstance(currentAccount).deleteMessagesByPush(dialogId, ids, channel_id); @@ -312,9 +315,9 @@ public class GcmPushListenerService extends FirebaseMessagingService { } } if (processNotification) { - int chat_from_id = custom.optInt("chat_from_id", 0); - int chat_from_broadcast_id = custom.optInt("chat_from_broadcast_id", 0); - int chat_from_group_id = custom.optInt("chat_from_group_id", 0); + long chat_from_id = custom.optLong("chat_from_id", 0); + long chat_from_broadcast_id = custom.optLong("chat_from_broadcast_id", 0); + long chat_from_group_id = custom.optLong("chat_from_group_id", 0); boolean isGroup = chat_from_id != 0 || chat_from_group_id != 0; boolean mention = custom.has("mention") && custom.getInt("mention") != 0; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/GoogleVoiceClientService.java b/TMessagesProj/src/main/java/org/telegram/messenger/GoogleVoiceClientService.java index 45039401b..a0e8e81fb 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/GoogleVoiceClientService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/GoogleVoiceClientService.java @@ -34,7 +34,7 @@ public class GoogleVoiceClientService extends SearchActionVerificationClientServ if (!TextUtils.isEmpty(text)) { String contactUri = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_URI"); String id = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID"); - int uid = Integer.parseInt(id); + long uid = Long.parseLong(id); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid); if (user == null) { user = MessagesStorage.getInstance(currentAccount).getUserSync(uid); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java index a88d08313..8d2291bbe 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java @@ -77,6 +77,7 @@ public class ImageLoader { private HashMap bitmapUseCounts = new HashMap<>(); private LruCache memCache; + private LruCache wallpaperMemCache; private LruCache lottieMemCache; private HashMap imageLoadingByUrl = new HashMap<>(); private HashMap imageLoadingByKeys = new HashMap<>(); @@ -824,7 +825,11 @@ public class ImageLoader { h = Math.min(h, 160); limitFps = true; } - precache = SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_HIGH; + if (args.length >= 3 && "pcache".equals(args[2])) { + precache = true; + } else { + precache = SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_HIGH; + } } if (args.length >= 3) { @@ -1422,15 +1427,21 @@ public class ImageLoader { toSet = drawable; } else if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; - toSet = memCache.get(cacheImage.key); + toSet = getFromMemCache(cacheImage.key); + boolean incrementUseCount = true; if (toSet == null) { - memCache.put(cacheImage.key, bitmapDrawable); + if (cacheImage.key.endsWith("_f")) { + wallpaperMemCache.put(cacheImage.key, bitmapDrawable); + incrementUseCount = false; + } else { + memCache.put(cacheImage.key, bitmapDrawable); + } toSet = bitmapDrawable; } else { Bitmap image = bitmapDrawable.getBitmap(); image.recycle(); } - if (toSet != null) { + if (toSet != null && incrementUseCount) { incrementUseCount(cacheImage.key); decrementKey = cacheImage.key; } @@ -1455,6 +1466,14 @@ public class ImageLoader { } } + private BitmapDrawable getFromMemCache(String key) { + BitmapDrawable drawable = memCache.get(key); + if (drawable == null) { + return wallpaperMemCache.get(key); + } + return drawable; + } + public static Bitmap getStrippedPhotoBitmap(byte[] photoBytes, String filter) { int len = photoBytes.length - 3 + Bitmaps.header.length + Bitmaps.footer.length; byte[] bytes = bytesLocal.get(); @@ -1699,6 +1718,12 @@ public class ImageLoader { } } }; + wallpaperMemCache = new LruCache(cacheSize / 4) { + @Override + protected int sizeOf(String key, BitmapDrawable value) { + return value.getBitmap().getByteCount(); + } + }; lottieMemCache = new LruCache(512 * 512 * 2 * 4 * 5) { @Override @@ -1894,11 +1919,13 @@ public class ImageLoader { File path = Environment.getExternalStorageDirectory(); if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(SharedConfig.storageCacheDir)) { ArrayList dirs = AndroidUtilities.getRootDirs(); - for (int a = 0, N = dirs.size(); a < N; a++) { - File dir = dirs.get(a); - if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { - path = dir; - break; + if (dirs != null) { + for (int a = 0, N = dirs.size(); a < N; a++) { + File dir = dirs.get(a); + if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { + path = dir; + break; + } } } } @@ -1925,15 +1952,13 @@ public class ImageLoader { }*/ if (Build.VERSION.SDK_INT >= 19 && !telegramPath.isDirectory()) { ArrayList dirs = AndroidUtilities.getDataDirs(); - if (dirs != null) { - for (int a = 0, N = dirs.size(); a < N; a++) { - File dir = dirs.get(a); - if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { - path = dir; - telegramPath = new File(path, "Telegram"); - telegramPath.mkdirs(); - break; - } + for (int a = 0, N = dirs.size(); a < N; a++) { + File dir = dirs.get(a); + if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { + path = dir; + telegramPath = new File(path, "Telegram"); + telegramPath.mkdirs(); + break; } } } @@ -2139,7 +2164,7 @@ public class ImageLoader { if (animated) { return lottieMemCache.get(key) != null; } else { - return memCache.get(key) != null; + return getFromMemCache(key) != null; } } @@ -2233,7 +2258,7 @@ public class ImageLoader { if (filter != null) { key += "@" + filter; } - return memCache.get(key); + return getFromMemCache(key); } private void replaceImageInCacheInternal(final String oldKey, final String newKey, final ImageLocation newLocation) { @@ -2659,6 +2684,11 @@ public class ImageLoader { drawable = memCache.get(mediaKey); if (drawable != null) { memCache.moveToFront(mediaKey); + } else { + drawable = wallpaperMemCache.get(mediaKey); + if (drawable != null) { + wallpaperMemCache.moveToFront(mediaKey); + } } } if (drawable != null) { @@ -2680,6 +2710,11 @@ public class ImageLoader { drawable = memCache.get(imageKey); if (drawable != null) { memCache.moveToFront(imageKey); + } else { + drawable = wallpaperMemCache.get(imageKey); + if (drawable != null) { + wallpaperMemCache.moveToFront(imageKey); + } } } if (drawable != null) { @@ -2702,6 +2737,11 @@ public class ImageLoader { drawable = memCache.get(thumbKey); if (drawable != null) { memCache.moveToFront(thumbKey); + } else { + drawable = wallpaperMemCache.get(thumbKey); + if (drawable != null) { + wallpaperMemCache.moveToFront(thumbKey); + } } } if (drawable != null) { @@ -2803,7 +2843,7 @@ public class ImageLoader { } String docExt = FileLoader.getDocumentFileName(object.document); int idx; - if (docExt == null || (idx = docExt.lastIndexOf('.')) == -1) { + if ((idx = docExt.lastIndexOf('.')) == -1) { docExt = ""; } else { docExt = docExt.substring(idx); @@ -2866,6 +2906,10 @@ public class ImageLoader { thumbKey += "@" + thumbFilter; } + if (imageReceiver.getUniqKeyPrefix() != null) { + imageKey = imageReceiver.getUniqKeyPrefix() + imageKey; + } + if (imageLocation != null && imageLocation.path != null) { createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, thumbExt, thumbLocation, thumbFilter, 0, 1, ImageReceiver.TYPE_THUMB, thumbSet ? 2 : 1, guid); createLoadOperationForImageReceiver(imageReceiver, imageKey, imageUrl, imageExt, imageLocation, imageFilter, imageReceiver.getSize(), 1, ImageReceiver.TYPE_IMAGE, 0, guid); @@ -2877,7 +2921,7 @@ public class ImageLoader { } int thumbCacheType = mediaCacheType == 0 ? 1 : mediaCacheType; if (!thumbSet) { - createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, thumbExt, thumbLocation, thumbFilter, 0, thumbCacheType, ImageReceiver.TYPE_THUMB, thumbSet ? 2 : 1, guid); + createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, thumbExt, thumbLocation, thumbFilter, 0, thumbCacheType, ImageReceiver.TYPE_THUMB, 1, guid); } if (!imageSet) { createLoadOperationForImageReceiver(imageReceiver, imageKey, imageUrl, imageExt, imageLocation, imageFilter, 0, imageCacheType, ImageReceiver.TYPE_IMAGE, 0, guid); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/ImageReceiver.java index 4c803ea06..3b9bf101d 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ImageReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ImageReceiver.java @@ -272,6 +272,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg private int crossfadeDuration = DEFAULT_CROSSFADE_DURATION; private float pressedProgress; private int animateFromIsPressed; + private String uniqKeyPrefix; public ImageReceiver() { this(null); @@ -449,6 +450,10 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg imageKey += "@" + imageFilter; } + if (uniqKeyPrefix != null) { + imageKey = uniqKeyPrefix + imageKey; + } + String mediaKey = mediaLocation != null ? mediaLocation.getKey(parentObject, null, false) : null; if (mediaKey == null && mediaLocation != null) { mediaLocation = null; @@ -1424,12 +1429,15 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg } if (thumbDrawable != null) { int alpha; - if (thumbDrawable instanceof SvgHelper.SvgDrawable) { + if (thumbDrawable instanceof SvgHelper.SvgDrawable || thumbDrawable instanceof Emoji.EmojiDrawable) { alpha = (int) (overrideAlpha * 255 * (1.0f - currentAlpha)); } else { alpha = (int) (overrideAlpha * 255); } drawDrawable(canvas, thumbDrawable, alpha, thumbShaderToUse, thumbOrientation); + if (alpha != 255 && thumbDrawable instanceof Emoji.EmojiDrawable) { + thumbDrawable.setAlpha(255); + } } } drawDrawable(canvas, drawable, (int) (overrideAlpha * currentAlpha * 255), shaderToUse, orientation); @@ -2056,7 +2064,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg if (currentMediaDrawable instanceof AnimatedFileDrawable && ((AnimatedFileDrawable) currentMediaDrawable).hasBitmap()) { allowCorssfade = false; } else if (currentImageDrawable instanceof RLottieDrawable) { - allowCorssfade = staticThumbDrawable instanceof LoadingStickerDrawable || staticThumbDrawable instanceof SvgHelper.SvgDrawable; + allowCorssfade = staticThumbDrawable instanceof LoadingStickerDrawable || staticThumbDrawable instanceof SvgHelper.SvgDrawable || staticThumbDrawable instanceof Emoji.EmojiDrawable; } if (allowCorssfade && (currentThumbDrawable == null && staticThumbDrawable == null || currentAlpha == 1.0f || forceCrossfade)) { currentAlpha = 0.0f; @@ -2303,4 +2311,12 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg currentAlpha = 0f; updateDrawableRadius(staticThumbDrawable); } + + public void setUniqKeyPrefix(String prefix) { + uniqKeyPrefix = prefix; + } + + public String getUniqKeyPrefix() { + return uniqKeyPrefix; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/KeepAliveJob.java b/TMessagesProj/src/main/java/org/telegram/messenger/KeepAliveJob.java index a748a9ed8..2268eed93 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/KeepAliveJob.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/KeepAliveJob.java @@ -21,23 +21,20 @@ public class KeepAliveJob extends JobIntentService { private static final Object sync = new Object(); public static void startJob() { - Utilities.globalQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (startingJob || countDownLatch != null) { - return; + Utilities.globalQueue.postRunnable(() -> { + if (startingJob || countDownLatch != null) { + return; + } + try { + if (BuildVars.LOGS_ENABLED) { + FileLog.d("starting keep-alive job"); } - try { - if (BuildVars.LOGS_ENABLED) { - FileLog.d("starting keep-alive job"); - } - synchronized (sync) { - startingJob = true; - } - enqueueWork(ApplicationLoader.applicationContext, KeepAliveJob.class, 1000, new Intent()); - } catch (Exception ignore) { + synchronized (sync) { + startingJob = true; + } + enqueueWork(ApplicationLoader.applicationContext, KeepAliveJob.class, 1000, new Intent()); + } catch (Exception ignore) { - } } }); } @@ -60,20 +57,10 @@ public class KeepAliveJob extends JobIntentService { } public static void finishJob() { - Utilities.globalQueue.postRunnable(new Runnable() { - @Override - public void run() { - finishJobInternal(); - } - }); + Utilities.globalQueue.postRunnable(KeepAliveJob::finishJobInternal); } - private static Runnable finishJobByTimeoutRunnable = new Runnable() { - @Override - public void run() { - finishJobInternal(); - } - }; + private static Runnable finishJobByTimeoutRunnable = KeepAliveJob::finishJobInternal; @Override protected void onHandleWork(Intent intent) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java b/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java index e71b37b99..105f755fc 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java @@ -454,7 +454,7 @@ public class LocaleController { } public void checkUpdateForCurrentRemoteLocale(int currentAccount, int version, int baseVersion) { - if (currentLocaleInfo == null || currentLocaleInfo != null && !currentLocaleInfo.isRemote() && !currentLocaleInfo.isUnofficial()) { + if (currentLocaleInfo == null || !currentLocaleInfo.isRemote() && !currentLocaleInfo.isUnofficial()) { return; } if (currentLocaleInfo.hasBaseLang()) { @@ -722,10 +722,8 @@ public class LocaleController { if (remoteLanguagesDict.containsKey(localeInfo.getKey())) { continue; } - if (localeInfo != null) { - remoteLanguages.add(localeInfo); - remoteLanguagesDict.put(localeInfo.getKey(), localeInfo); - } + remoteLanguages.add(localeInfo); + remoteLanguagesDict.put(localeInfo.getKey(), localeInfo); } } locales = preferences.getString("unofficial", null); @@ -737,9 +735,7 @@ public class LocaleController { continue; } localeInfo.shortName = localeInfo.shortName.replace("-", "_"); - if (localeInfo != null) { - unofficialLanguages.add(localeInfo); - } + unofficialLanguages.add(localeInfo); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/LocationController.java b/TMessagesProj/src/main/java/org/telegram/messenger/LocationController.java index f685122e6..e46091c38 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/LocationController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/LocationController.java @@ -19,7 +19,6 @@ import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.text.TextUtils; -import android.util.LongSparseArray; import android.util.SparseIntArray; import com.google.android.gms.common.ConnectionResult; @@ -44,6 +43,8 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import androidx.collection.LongSparseArray; + public class LocationController extends BaseController implements NotificationCenter.NotificationCenterDelegate, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private LongSparseArray sharingLocationsMap = new LongSparseArray<>(); @@ -214,9 +215,9 @@ public class LocationController extends BaseController implements NotificationCe messages.add(messageObject.messageOwner); } } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { - int lowerId = (int) messageObject.getDialogId(); - if (lowerId > 0) { - setProximityLocation(messageObject.getDialogId(), 0, false); + long dialogId = messageObject.getDialogId(); + if (DialogObject.isUserDialog(dialogId)) { + setProximityLocation(dialogId, 0, false); } } } @@ -230,11 +231,11 @@ public class LocationController extends BaseController implements NotificationCe } if (!sharingLocationsUI.isEmpty()) { ArrayList markAsDeletedMessages = (ArrayList) args[0]; - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; ArrayList toRemove = null; for (int a = 0; a < sharingLocationsUI.size(); a++) { SharingLocationInfo info = sharingLocationsUI.get(a); - int messageChannelId = info.messageObject != null ? info.messageObject.getChannelId() : 0; + long messageChannelId = info.messageObject != null ? info.messageObject.getChannelId() : 0; if (channelId != messageChannelId) { continue; } @@ -397,7 +398,7 @@ public class LocationController extends BaseController implements NotificationCe } } TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); - req.peer = getMessagesController().getInputPeer((int) info.did); + req.peer = getMessagesController().getInputPeer(info.did); req.id = info.mid; req.flags |= 16384; req.media = new TLRPC.TL_inputMediaGeoLive(); @@ -663,8 +664,8 @@ public class LocationController extends BaseController implements NotificationCe final ArrayList users = new ArrayList<>(); final ArrayList chats = new ArrayList<>(); try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT uid, mid, date, period, message, proximity FROM sharing_locations WHERE 1"); while (cursor.next()) { SharingLocationInfo info = new SharingLocationInfo(); @@ -681,22 +682,14 @@ public class LocationController extends BaseController implements NotificationCe data.reuse(); } result.add(info); - int lower_id = (int) info.did; - int high_id = (int) (info.did >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } - } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } + if (DialogObject.isChatDialog(info.did)) { + if (!chatsToLoad.contains(-info.did)) { + chatsToLoad.add(-info.did); + } + } else if (DialogObject.isUserDialog(info.did)) { + if (!usersToLoad.contains(info.did)) { + usersToLoad.add(info.did); } - } else { - /*if (!encryptedChatIds.contains(high_id)) { - encryptedChatIds.add(high_id); - }*/ } } cursor.dispose(); @@ -777,7 +770,7 @@ public class LocationController extends BaseController implements NotificationCe sharingLocationsMap.remove(did); if (info != null) { TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); - req.peer = getMessagesController().getInputPeer((int) info.did); + req.peer = getMessagesController().getInputPeer(info.did); req.id = info.mid; req.flags |= 16384; req.media = new TLRPC.TL_inputMediaGeoLive(); @@ -827,7 +820,7 @@ public class LocationController extends BaseController implements NotificationCe for (int a = 0; a < sharingLocations.size(); a++) { SharingLocationInfo info = sharingLocations.get(a); TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); - req.peer = getMessagesController().getInputPeer((int) info.did); + req.peer = getMessagesController().getInputPeer(info.did); req.id = info.mid; req.flags |= 16384; req.media = new TLRPC.TL_inputMediaGeoLive(); @@ -947,13 +940,13 @@ public class LocationController extends BaseController implements NotificationCe return lastKnownLocation; } - public void loadLiveLocations(final long did) { + public void loadLiveLocations(long did) { if (cacheRequests.indexOfKey(did) >= 0) { return; } cacheRequests.put(did, true); TLRPC.TL_messages_getRecentLocations req = new TLRPC.TL_messages_getRecentLocations(); - req.peer = getMessagesController().getInputPeer((int) did); + req.peer = getMessagesController().getInputPeer(did); req.limit = 100; getConnectionsManager().sendRequest(req, (response, error) -> { if (error != null) { @@ -978,8 +971,7 @@ public class LocationController extends BaseController implements NotificationCe } public void markLiveLoactionsAsRead(long dialogId) { - int lowerId = (int) dialogId; - if (lowerId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { return; } ArrayList messages = locationsCache.get(dialogId); @@ -993,12 +985,12 @@ public class LocationController extends BaseController implements NotificationCe } lastReadLocationTime.put(dialogId, currentDate); TLObject request; - if (lowerId < 0 && ChatObject.isChannel(-lowerId, currentAccount)) { + if (DialogObject.isChatDialog(dialogId) && ChatObject.isChannel(-dialogId, currentAccount)) { TLRPC.TL_channels_readMessageContents req = new TLRPC.TL_channels_readMessageContents(); for (int a = 0, N = messages.size(); a < N; a++) { req.id.add(messages.get(a).id); } - req.channel = getMessagesController().getInputChannel(-lowerId); + req.channel = getMessagesController().getInputChannel(-dialogId); request = req; } else { TLRPC.TL_messages_readMessageContents req = new TLRPC.TL_messages_readMessageContents(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/LocationSharingService.java b/TMessagesProj/src/main/java/org/telegram/messenger/LocationSharingService.java index 73dceca78..72a4120d7 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/LocationSharingService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/LocationSharingService.java @@ -97,14 +97,14 @@ public class LocationSharingService extends Service implements NotificationCente String str; if (infos.size() == 1) { LocationController.SharingLocationInfo info = infos.get(0); - int lower_id = (int) info.messageObject.getDialogId(); + long dialogId = info.messageObject.getDialogId(); int currentAccount = info.messageObject.currentAccount; - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); param = UserObject.getFirstName(user); str = LocaleController.getString("AttachLiveLocationIsSharing", R.string.AttachLiveLocationIsSharing); } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat != null) { param = chat.title; } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MediaController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MediaController.java index bae740b20..b1ff19b9c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MediaController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MediaController.java @@ -624,28 +624,26 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, final double amplitude = Math.sqrt(sum / len / 2); final ByteBuffer finalBuffer = buffer; final boolean flush = len != buffer.capacity(); - if (len != 0) { - fileEncodingQueue.postRunnable(() -> { - while (finalBuffer.hasRemaining()) { - int oldLimit = -1; - if (finalBuffer.remaining() > fileBuffer.remaining()) { - oldLimit = finalBuffer.limit(); - finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position()); - } - fileBuffer.put(finalBuffer); - if (fileBuffer.position() == fileBuffer.limit() || flush) { - if (writeFrame(fileBuffer, !flush ? fileBuffer.limit() : finalBuffer.position()) != 0) { - fileBuffer.rewind(); - recordTimeCount += fileBuffer.limit() / 2 / (sampleRate / 1000); - } - } - if (oldLimit != -1) { - finalBuffer.limit(oldLimit); + fileEncodingQueue.postRunnable(() -> { + while (finalBuffer.hasRemaining()) { + int oldLimit = -1; + if (finalBuffer.remaining() > fileBuffer.remaining()) { + oldLimit = finalBuffer.limit(); + finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position()); + } + fileBuffer.put(finalBuffer); + if (fileBuffer.position() == fileBuffer.limit() || flush) { + if (writeFrame(fileBuffer, !flush ? fileBuffer.limit() : finalBuffer.position()) != 0) { + fileBuffer.rewind(); + recordTimeCount += fileBuffer.limit() / 2 / (sampleRate / 1000); } } - recordQueue.postRunnable(() -> recordBuffers.add(finalBuffer)); - }); - } + if (oldLimit != -1) { + finalBuffer.limit(oldLimit); + } + } + recordQueue.postRunnable(() -> recordBuffers.add(finalBuffer)); + }); recordQueue.postRunnable(recordRunnable); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordProgressChanged, recordingGuid, amplitude)); } else { @@ -1046,7 +1044,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, public void run() { synchronized (sync) { AndroidUtilities.runOnUIThread(() -> { - if (currentPlayingMessageObject != null && (audioPlayer != null || videoPlayer != null) && !isPaused) { + if ((audioPlayer != null || videoPlayer != null) && !isPaused) { try { long duration; long progress; @@ -1059,7 +1057,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, return; } bufferedValue = videoPlayer.getBufferedPosition() / (float) duration; - value = duration >= 0 ? progress / (float) duration : 0.0f; + value = progress / (float) duration; if (value >= 1) { return; } @@ -1286,7 +1284,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, if (scheduled) { return; } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; ArrayList markAsDeletedMessages = (ArrayList) args[0]; if (playingMessageObject != null) { if (channelId == playingMessageObject.messageOwner.peer_id.channel_id) { @@ -1343,7 +1341,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, int type = (Integer) args[4]; ArrayList arr = (ArrayList) args[2]; - boolean enc = ((int) did) == 0; + boolean enc = DialogObject.isEncryptedDialog(did); int loadIndex = did == playlistMergeDialogId ? 1 : 0; if (!arr.isEmpty()) { playlistEndReached[loadIndex] = (Boolean) args[5]; @@ -1360,11 +1358,9 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, playlistMaxId[loadIndex] = Math.min(playlistMaxId[loadIndex], message.getId()); } sortPlaylist(); - if (playingMessageObject != null) { - int newIndex = playlist.indexOf(playingMessageObject); - if (newIndex >= 0) { - currentPlaylistNum = newIndex; - } + int newIndex = playlist.indexOf(playingMessageObject); + if (newIndex >= 0) { + currentPlaylistNum = newIndex; } loadingPlaylist = false; if (SharedConfig.shuffleMusic) { @@ -1848,7 +1844,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, true); } else { long position = videoPlayer.getCurrentPosition(); - if (playingMessageObject != null && playingMessageObject.isVideo() && position > 0 && position != C.TIME_UNSET) { + if (playingMessageObject != null && playingMessageObject.isVideo() && position > 0) { playingMessageObject.audioProgressMs = (int) position; NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, false); } @@ -2004,7 +2000,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } public void loadMoreMusic() { - if (loadingPlaylist || playingMessageObject == null || playingMessageObject.scheduled || (int) playingMessageObject.getDialogId() == 0 || playlistClassGuid == 0) { + if (loadingPlaylist || playingMessageObject == null || playingMessageObject.scheduled || DialogObject.isEncryptedDialog(playingMessageObject.getDialogId()) || playlistClassGuid == 0) { return; } if (playlistGlobalSearchParams != null) { @@ -2037,7 +2033,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, req.offset_rate = playlistGlobalSearchParams.nextSearchRate; req.flags |= 1; req.folder_id = playlistGlobalSearchParams.folderId; - int id; + long id; if (lastMessage.messageOwner.peer_id.channel_id != 0) { id = -lastMessage.messageOwner.peer_id.channel_id; } else if (lastMessage.messageOwner.peer_id.chat_id != 0) { @@ -2123,19 +2119,19 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, playMusicAgain = !playlist.isEmpty(); clearPlaylist(); playlistGlobalSearchParams = params; - boolean isSecretChat = !messageObjects.isEmpty() && (int) messageObjects.get(0).getDialogId() == 0; - long minId = Long.MAX_VALUE; - long maxId = Long.MIN_VALUE; + boolean isSecretChat = !messageObjects.isEmpty() && DialogObject.isEncryptedDialog(messageObjects.get(0).getDialogId()); + int minId = Integer.MAX_VALUE; + int maxId = Integer.MIN_VALUE; for (int a = messageObjects.size() - 1; a >= 0; a--) { MessageObject messageObject = messageObjects.get(a); if (messageObject.isMusic()) { - long id = messageObject.getIdWithChannel(); + int id = messageObject.getId(); if (id > 0 || isSecretChat) { minId = Math.min(minId, id); maxId = Math.max(maxId, id); } playlist.add(messageObject); - playlistMap.put(messageObject.getId(), messageObject); + playlistMap.put(id, messageObject); } } sortPlaylist(); @@ -2244,7 +2240,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } audioPlayer = null; Theme.unrefAudioVisualizeDrawable(playingMessageObject); - } else if (videoPlayer != null) { + } else { currentAspectRatioFrameLayout = null; currentTextureViewContainer = null; currentAspectRatioFrameLayoutReady = false; @@ -2301,7 +2297,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, currentPlaylistNum = 0; } } - if (currentPlaylistNum < 0 || currentPlaylistNum >= currentPlayList.size()) { + if (currentPlaylistNum >= currentPlayList.size()) { return; } playMusicAgain = true; @@ -2328,8 +2324,8 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } } final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner); - boolean exist = cacheFile != null && cacheFile.exists(); - if (cacheFile != null && cacheFile != file && !cacheFile.exists()) { + boolean exist = cacheFile.exists(); + if (cacheFile != file && !cacheFile.exists()) { FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, 0, 0); } } @@ -2367,8 +2363,8 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } } final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner); - boolean exist = cacheFile != null && cacheFile.exists(); - if (cacheFile != null && cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) { + boolean exist = cacheFile.exists(); + if (cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) { FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, 0, 0); } } @@ -2419,7 +2415,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, pipSwitchingState = 2; pipRoundVideoView.close(true); pipRoundVideoView = null; - } else if (currentAspectRatioFrameLayout != null) { + } else { if (currentAspectRatioFrameLayout.getParent() == null) { currentTextureViewContainer.addView(currentAspectRatioFrameLayout); } @@ -2469,9 +2465,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, currentAspectRatioFrameLayout = aspectRatioFrameLayout; currentTextureViewContainer = container; if (currentAspectRatioFrameLayoutReady && currentAspectRatioFrameLayout != null) { - if (currentAspectRatioFrameLayout != null) { - currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation); - } + currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation); //if (currentTextureViewContainer.getVisibility() != View.VISIBLE) { // currentTextureViewContainer.setVisibility(View.VISIBLE); //} @@ -2845,8 +2839,8 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } } final File cacheFile = file != null ? file : FileLoader.getPathToMessage(messageObject.messageOwner); - boolean canStream = SharedConfig.streamMedia && (messageObject.isMusic() || messageObject.isRoundVideo() || messageObject.isVideo() && messageObject.canStreamVideo()) && (int) messageObject.getDialogId() != 0; - if (cacheFile != null && cacheFile != file && !(exists = cacheFile.exists()) && !canStream) { + boolean canStream = SharedConfig.streamMedia && (messageObject.isMusic() || messageObject.isRoundVideo() || messageObject.isVideo() && messageObject.canStreamVideo()) && !DialogObject.isEncryptedDialog(messageObject.getDialogId()); + if (cacheFile != file && !(exists = cacheFile.exists()) && !canStream) { FileLoader.getInstance(messageObject.currentAccount).loadFile(messageObject.getDocument(), messageObject, 0, 0); downloadingCurrentMessage = true; isPaused = false; @@ -3057,7 +3051,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, if (!playlist.isEmpty() && (playlist.size() > 1 || !messageObject.isVoice())) { playNextMessageWithoutOrder(true); } else { - cleanupPlayer(true, true, messageObject != null && messageObject.isVoice(), false); + cleanupPlayer(true, true, messageObject.isVoice(), false); } } else if (audioPlayer != null && seekToProgressPending != 0 && (playbackState == ExoPlayer.STATE_READY || playbackState == ExoPlayer.STATE_IDLE)) { int seekTo = (int) (audioPlayer.getDuration() * seekToProgressPending); @@ -4074,11 +4068,9 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, byte[] header = new byte[12]; if (inputStream.read(header, 0, 12) == 12) { String str = new String(header); - if (str != null) { - str = str.toLowerCase(); - if (str.startsWith("riff") && str.endsWith("webp")) { - return true; - } + str = str.toLowerCase(); + if (str.startsWith("riff") && str.endsWith("webp")) { + return true; } } } catch (Exception e) { @@ -4102,7 +4094,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, byte[] header = new byte[3]; if (inputStream.read(header, 0, 3) == 3) { String str = new String(header); - if (str != null && str.equalsIgnoreCase("gif")) { + if (str.equalsIgnoreCase("gif")) { return true; } } @@ -4322,7 +4314,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, } try { - if (Build.VERSION.SDK_INT < 23 || Build.VERSION.SDK_INT >= 23 && ApplicationLoader.applicationContext.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { + if (Build.VERSION.SDK_INT < 23 || ApplicationLoader.applicationContext.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { cursor = MediaStore.Images.Media.query(ApplicationLoader.applicationContext.getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projectionVideo, null, null, (Build.VERSION.SDK_INT > 28 ? MediaStore.Video.Media.DATE_MODIFIED : MediaStore.Video.Media.DATE_TAKEN) + " DESC"); if (cursor != null) { int imageIdColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID); @@ -4672,7 +4664,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, int framerate = info.framerate; int bitrate = info.bitrate; int originalBitrate = info.originalBitrate; - boolean isSecret = ((int) messageObject.getDialogId()) == 0; + boolean isSecret = DialogObject.isEncryptedDialog(messageObject.getDialogId()); final File cacheFile = new File(messageObject.messageOwner.attachPath); if (cacheFile.exists()) { cacheFile.delete(); @@ -4800,7 +4792,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, compressFactor = 1f; minCompressFactor = 1f; } else if (Math.min(height, width) >= 720) { - maxBitrate = 2621_440; + maxBitrate = 3200_000; compressFactor = 1f; minCompressFactor = 1f; } else if (Math.min(height, width) >= 480) { @@ -4836,7 +4828,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, public static class PlaylistGlobalSearchParams { final String query; final FiltersView.MediaFilterData filter; - final int dialogId; + final long dialogId; final long minDate; final long maxDate; public int totalCount; @@ -4844,7 +4836,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener, public int nextSearchRate; public int folderId; - public PlaylistGlobalSearchParams(String query, int dialogId, long minDate, long maxDate, FiltersView.MediaFilterData filter) { + public PlaylistGlobalSearchParams(String query, long dialogId, long minDate, long maxDate, FiltersView.MediaFilterData filter) { this.filter = filter; this.query = query; this.dialogId = dialogId; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MediaDataController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MediaDataController.java index 51d55edee..f9efa76c1 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MediaDataController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MediaDataController.java @@ -32,7 +32,6 @@ import android.text.Spanned; import android.text.SpannedString; import android.text.TextUtils; import android.text.style.CharacterStyle; -import android.util.LongSparseArray; import android.util.SparseArray; import org.telegram.SQLite.SQLiteCursor; @@ -69,10 +68,13 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; +import androidx.collection.LongSparseArray; import androidx.core.content.pm.ShortcutInfoCompat; import androidx.core.content.pm.ShortcutManagerCompat; import androidx.core.graphics.drawable.IconCompat; +import com.google.android.exoplayer2.util.Log; + @SuppressWarnings("unchecked") public class MediaDataController extends BaseController { @@ -160,7 +162,7 @@ public class MediaDataController extends BaseController { private Runnable[] scheduledLoadStickers = new Runnable[5]; private boolean[] loadingStickers = new boolean[5]; private boolean[] stickersLoaded = new boolean[5]; - private int[] loadHash = new int[5]; + private long[] loadHash = new long[5]; private int[] loadDate = new int[5]; private HashMap> verifyingMessages = new HashMap<>(); @@ -179,7 +181,7 @@ public class MediaDataController extends BaseController { private boolean loadingRecentGifs; private boolean recentGifsLoaded; - private int loadFeaturedHash; + private long loadFeaturedHash; private int loadFeaturedDate; private ArrayList featuredStickerSets = new ArrayList<>(); private LongSparseArray featuredStickerSetsById = new LongSparseArray<>(); @@ -286,7 +288,7 @@ public class MediaDataController extends BaseController { return false; } - public void addRecentSticker(final int type, Object parentObject, TLRPC.Document document, int date, boolean remove) { + public void addRecentSticker(int type, Object parentObject, TLRPC.Document document, int date, boolean remove) { if (type == TYPE_GREETINGS || !MessageObject.isStickerDocument(document) && !MessageObject.isAnimatedStickerDocument(document, true)) { return; } @@ -350,7 +352,7 @@ public class MediaDataController extends BaseController { maxCount = getMessagesController().maxRecentStickersCount; } if (recentStickers[type].size() > maxCount || remove) { - final TLRPC.Document old = remove ? document : recentStickers[type].remove(recentStickers[type].size() - 1); + TLRPC.Document old = remove ? document : recentStickers[type].remove(recentStickers[type].size() - 1); getMessagesStorage().getStorageQueue().postRunnable(() -> { int cacheType; if (type == TYPE_IMAGE) { @@ -381,7 +383,7 @@ public class MediaDataController extends BaseController { return new ArrayList<>(recentGifs); } - public void removeRecentGif(final TLRPC.Document document) { + public void removeRecentGif(TLRPC.Document document) { for (int i = 0, N = recentGifs.size(); i < N; i++) { if (recentGifs.get(i).id == document.id) { recentGifs.remove(i); @@ -441,7 +443,7 @@ public class MediaDataController extends BaseController { recentGifs.add(0, document); } if (recentGifs.size() > getMessagesController().maxRecentGifsCount) { - final TLRPC.Document old = recentGifs.remove(recentGifs.size() - 1); + TLRPC.Document old = recentGifs.remove(recentGifs.size() - 1); getMessagesStorage().getStorageQueue().postRunnable(() -> { try { getMessagesStorage().getDatabase().executeFast("DELETE FROM web_recent_v3 WHERE id = '" + old.id + "' AND type = 2").stepThis().dispose(); @@ -550,11 +552,11 @@ public class MediaDataController extends BaseController { groupStickerSets.put(stickerSet.set.id, stickerSet); } - private void loadGroupStickerSet(final TLRPC.StickerSet stickerSet, boolean cache) { + private void loadGroupStickerSet(TLRPC.StickerSet stickerSet, boolean cache) { if (cache) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { - final TLRPC.TL_messages_stickerSet set; + TLRPC.TL_messages_stickerSet set; SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT document FROM web_recent_v3 WHERE id = 's_" + stickerSet.id + "'"); if (cursor.next() && !cursor.isNull(0)) { NativeByteBuffer data = cursor.byteBufferValue(0); @@ -703,11 +705,11 @@ public class MediaDataController extends BaseController { return value != null ? value : ""; } - public static int calcDocumentsHash(ArrayList arrayList) { + public static long calcDocumentsHash(ArrayList arrayList) { return calcDocumentsHash(arrayList, 200); } - public static int calcDocumentsHash(ArrayList arrayList, int maxCount) { + public static long calcDocumentsHash(ArrayList arrayList, int maxCount) { if (arrayList == null) { return 0; } @@ -717,15 +719,12 @@ public class MediaDataController extends BaseController { if (document == null) { continue; } - int high_id = (int) (document.id >> 32); - int lower_id = (int) document.id; - acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L; - acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L; + acc = calcHash(acc, document.id); } - return (int) acc; + return acc; } - public void loadRecents(final int type, final boolean gif, boolean cache, boolean force) { + public void loadRecents(int type, boolean gif, boolean cache, boolean force) { if (gif) { if (loadingRecentGifs) { return; @@ -746,7 +745,7 @@ public class MediaDataController extends BaseController { if (cache) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { - final int cacheType; + int cacheType; if (gif) { cacheType = 2; } else if (type == TYPE_IMAGE) { @@ -759,7 +758,7 @@ public class MediaDataController extends BaseController { cacheType = 5; } SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT document FROM web_recent_v3 WHERE type = " + cacheType + " ORDER BY date DESC"); - final ArrayList arrayList = new ArrayList<>(); + ArrayList arrayList = new ArrayList<>(); while (cursor.next()) { if (!cursor.isNull(0)) { NativeByteBuffer data = cursor.byteBufferValue(0); @@ -826,7 +825,7 @@ public class MediaDataController extends BaseController { TLRPC.TL_messages_savedGifs res = (TLRPC.TL_messages_savedGifs) response; arrayList = res.gifs; } - processLoadedRecentDocuments(type, arrayList, gif, 0, true); + processLoadedRecentDocuments(type, arrayList, true, 0, true); }); } else { TLObject request; @@ -883,7 +882,7 @@ public class MediaDataController extends BaseController { return result; } - protected void processLoadedRecentDocuments(final int type, final ArrayList documents, final boolean gif, final int date, boolean replace) { + protected void processLoadedRecentDocuments(int type, ArrayList documents, boolean gif, int date, boolean replace) { if (documents != null) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { @@ -991,7 +990,7 @@ public class MediaDataController extends BaseController { } } - public void reorderStickers(int type, final ArrayList order) { + public void reorderStickers(int type, ArrayList order) { Collections.sort(stickerSets[type], (lhs, rhs) -> { int index1 = order.indexOf(lhs.set.id); int index2 = order.indexOf(rhs.set.id); @@ -1011,12 +1010,12 @@ public class MediaDataController extends BaseController { loadHash[type] = calcStickersHash(stickerSets[type]); } - public void storeTempStickerSet(final TLRPC.TL_messages_stickerSet set) { + public void storeTempStickerSet(TLRPC.TL_messages_stickerSet set) { stickerSetsById.put(set.set.id, set); stickerSetsByName.put(set.set.short_name, set); } - public void addNewStickerSet(final TLRPC.TL_messages_stickerSet set) { + public void addNewStickerSet(TLRPC.TL_messages_stickerSet set) { if (stickerSetsById.indexOfKey(set.set.id) >= 0 || stickerSetsByName.containsKey(set.set.short_name)) { return; } @@ -1064,7 +1063,7 @@ public class MediaDataController extends BaseController { ArrayList newStickerArray = null; ArrayList unread = new ArrayList<>(); int date = 0; - int hash = 0; + long hash = 0; SQLiteCursor cursor = null; try { cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT data, unread, date, hash FROM stickers_featured WHERE 1"); @@ -1100,7 +1099,7 @@ public class MediaDataController extends BaseController { processLoadedFeaturedStickers(newStickerArray, unread, true, date, hash); }); } else { - final TLRPC.TL_messages_getFeaturedStickers req = new TLRPC.TL_messages_getFeaturedStickers(); + TLRPC.TL_messages_getFeaturedStickers req = new TLRPC.TL_messages_getFeaturedStickers(); req.hash = force ? 0 : loadFeaturedHash; getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_messages_featuredStickers) { @@ -1113,7 +1112,7 @@ public class MediaDataController extends BaseController { } } - private void processLoadedFeaturedStickers(final ArrayList res, final ArrayList unreadStickers, final boolean cache, final int date, final int hash) { + private void processLoadedFeaturedStickers(ArrayList res, ArrayList unreadStickers, boolean cache, int date, long hash) { AndroidUtilities.runOnUIThread(() -> { loadingFeaturedStickers = false; featuredStickersLoaded = true; @@ -1132,8 +1131,8 @@ public class MediaDataController extends BaseController { } if (res != null) { try { - final ArrayList stickerSetsNew = new ArrayList<>(); - final LongSparseArray stickerSetsByIdNew = new LongSparseArray<>(); + ArrayList stickerSetsNew = new ArrayList<>(); + LongSparseArray stickerSetsByIdNew = new LongSparseArray<>(); for (int a = 0; a < res.size(); a++) { TLRPC.StickerSetCovered stickerSet = res.get(a); @@ -1156,15 +1155,15 @@ public class MediaDataController extends BaseController { } catch (Throwable e) { FileLog.e(e); } - } else if (!cache) { + } else { AndroidUtilities.runOnUIThread(() -> loadFeaturedDate = date); putFeaturedStickersToCache(null, null, date, 0); } }); } - private void putFeaturedStickersToCache(ArrayList stickers, final ArrayList unreadStickers, final int date, final int hash) { - final ArrayList stickersFinal = stickers != null ? new ArrayList<>(stickers) : null; + private void putFeaturedStickersToCache(ArrayList stickers, ArrayList unreadStickers, int date, long hash) { + ArrayList stickersFinal = stickers != null ? new ArrayList<>(stickers) : null; getMessagesStorage().getStorageQueue().postRunnable(() -> { try { if (stickersFinal != null) { @@ -1188,7 +1187,7 @@ public class MediaDataController extends BaseController { state.bindByteBuffer(2, data); state.bindByteBuffer(3, data2); state.bindInteger(4, date); - state.bindInteger(5, hash); + state.bindLong(5, hash); state.step(); data.reuse(); data2.reuse(); @@ -1206,22 +1205,29 @@ public class MediaDataController extends BaseController { }); } - private int calcFeaturedStickersHash(ArrayList sets) { + private long calcFeaturedStickersHash(ArrayList sets) { + if (sets == null || sets.isEmpty()) { + return 0; + } long acc = 0; for (int a = 0; a < sets.size(); a++) { TLRPC.StickerSet set = sets.get(a).set; if (set.archived) { continue; } - int high_id = (int) (set.id >> 32); - int lower_id = (int) set.id; - acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L; - acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L; + acc = calcHash(acc, set.id); if (unreadStickerSets.contains(set.id)) { - acc = ((acc * 20261) + 0x80000000L + 1) % 0x80000000L; + acc = calcHash(acc, 1); } } - return (int) acc; + return acc; + } + + public static long calcHash(long hash, long id) { + hash ^= id >> 21; + hash ^= id << 35; + hash ^= id >> 4; + return hash + id; } public void markFaturedStickersAsRead(boolean query) { @@ -1240,22 +1246,19 @@ public class MediaDataController extends BaseController { } } - public int getFeaturesStickersHashWithoutUnread() { + public long getFeaturesStickersHashWithoutUnread() { long acc = 0; for (int a = 0; a < featuredStickerSets.size(); a++) { TLRPC.StickerSet set = featuredStickerSets.get(a).set; if (set.archived) { continue; } - int high_id = (int) (set.id >> 32); - int lower_id = (int) set.id; - acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L; - acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L; + acc = calcHash(acc, set.id); } - return (int) acc; + return acc; } - public void markFaturedStickersByIdAsRead(final long id) { + public void markFaturedStickersByIdAsRead(long id) { if (!unreadStickerSets.contains(id) || readingStickerSets.contains(id)) { return; } @@ -1348,7 +1351,7 @@ public class MediaDataController extends BaseController { })); } - public void loadArchivedStickersCount(final int type, boolean cache) { + public void loadArchivedStickersCount(int type, boolean cache) { if (cache) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); int count = preferences.getInt("archivedStickersCount" + type, -1); @@ -1374,14 +1377,14 @@ public class MediaDataController extends BaseController { } } - private void processLoadStickersResponse(final int type, final TLRPC.TL_messages_allStickers res) { - final ArrayList newStickerArray = new ArrayList<>(); + private void processLoadStickersResponse(int type, TLRPC.TL_messages_allStickers res) { + ArrayList newStickerArray = new ArrayList<>(); if (res.sets.isEmpty()) { processLoadedStickers(type, newStickerArray, false, (int) (System.currentTimeMillis() / 1000), res.hash); } else { - final LongSparseArray newStickerSets = new LongSparseArray<>(); + LongSparseArray newStickerSets = new LongSparseArray<>(); for (int a = 0; a < res.sets.size(); a++) { - final TLRPC.StickerSet stickerSet = res.sets.get(a); + TLRPC.StickerSet stickerSet = res.sets.get(a); TLRPC.TL_messages_stickerSet oldSet = stickerSetsById.get(stickerSet.id); if (oldSet != null && oldSet.set.hash == stickerSet.hash) { @@ -1398,7 +1401,7 @@ public class MediaDataController extends BaseController { } newStickerArray.add(null); - final int index = a; + int index = a; TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet(); req.stickerset = new TLRPC.TL_inputStickerSetID(); @@ -1476,7 +1479,7 @@ public class MediaDataController extends BaseController { } } - private void processLoadedDiceStickers(String name, boolean isEmoji, TLRPC.TL_messages_stickerSet res, final boolean cache, final int date) { + private void processLoadedDiceStickers(String name, boolean isEmoji, TLRPC.TL_messages_stickerSet res, boolean cache, int date) { AndroidUtilities.runOnUIThread(() -> loadingDiceStickerSets.remove(name)); Utilities.stageQueue.postRunnable(() -> { if (cache && (res == null || Math.abs(System.currentTimeMillis() / 1000 - date) >= 60 * 60 * 24) || !cache && res == null) { @@ -1500,7 +1503,7 @@ public class MediaDataController extends BaseController { }); } - private void putDiceStickersToCache(final String emoji, TLRPC.TL_messages_stickerSet stickers, final int date) { + private void putDiceStickersToCache(String emoji, TLRPC.TL_messages_stickerSet stickers, int date) { if (TextUtils.isEmpty(emoji)) { return; } @@ -1530,11 +1533,11 @@ public class MediaDataController extends BaseController { }); } - public void loadStickers(final int type, boolean cache, boolean useHash) { + public void loadStickers(int type, boolean cache, boolean useHash) { loadStickers(type, cache, useHash, false); } - public void loadStickers(final int type, boolean cache, boolean force, boolean scheduleIfLoading) { + public void loadStickers(int type, boolean cache, boolean force, boolean scheduleIfLoading) { if (loadingStickers[type]) { if (scheduleIfLoading) { scheduledLoadStickers[type] = () -> loadStickers(type, false, force, false); @@ -1553,7 +1556,7 @@ public class MediaDataController extends BaseController { getMessagesStorage().getStorageQueue().postRunnable(() -> { ArrayList newStickerArray = null; int date = 0; - int hash = 0; + long hash = 0; SQLiteCursor cursor = null; try { cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT data, date, hash FROM stickers_v2 WHERE id = " + (type + 1)); @@ -1593,7 +1596,7 @@ public class MediaDataController extends BaseController { req.stickerset = new TLRPC.TL_inputStickerSetAnimatedEmoji(); getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_messages_stickerSet) { - final ArrayList newStickerArray = new ArrayList<>(); + ArrayList newStickerArray = new ArrayList<>(); newStickerArray.add((TLRPC.TL_messages_stickerSet) response); processLoadedStickers(type, newStickerArray, false, (int) (System.currentTimeMillis() / 1000), calcStickersHash(newStickerArray)); } else { @@ -1602,7 +1605,7 @@ public class MediaDataController extends BaseController { }); } else { TLObject req; - final int hash; + long hash; if (type == TYPE_IMAGE) { req = new TLRPC.TL_messages_getAllStickers(); hash = ((TLRPC.TL_messages_getAllStickers) req).hash = force ? 0 : loadHash[type]; @@ -1621,8 +1624,8 @@ public class MediaDataController extends BaseController { } } - private void putStickersToCache(final int type, ArrayList stickers, final int date, final int hash) { - final ArrayList stickersFinal = stickers != null ? new ArrayList<>(stickers) : null; + private void putStickersToCache(int type, ArrayList stickers, int date, long hash) { + ArrayList stickersFinal = stickers != null ? new ArrayList<>(stickers) : null; getMessagesStorage().getStorageQueue().postRunnable(() -> { try { if (stickersFinal != null) { @@ -1640,14 +1643,14 @@ public class MediaDataController extends BaseController { state.bindInteger(1, type + 1); state.bindByteBuffer(2, data); state.bindInteger(3, date); - state.bindInteger(4, hash); + state.bindLong(4, hash); state.step(); data.reuse(); state.dispose(); } else { SQLitePreparedStatement state = getMessagesStorage().getDatabase().executeFast("UPDATE stickers_v2 SET date = ?"); state.requery(); - state.bindInteger(1, date); + state.bindLong(1, date); state.step(); state.dispose(); } @@ -1695,19 +1698,19 @@ public class MediaDataController extends BaseController { return null; } - private static int calcStickersHash(ArrayList sets) { + private static long calcStickersHash(ArrayList sets) { long acc = 0; for (int a = 0; a < sets.size(); a++) { TLRPC.StickerSet set = sets.get(a).set; if (set.archived) { continue; } - acc = ((acc * 20261) + 0x80000000L + set.hash) % 0x80000000L; + acc = calcHash(acc, set.hash); } - return (int) acc; + return acc; } - private void processLoadedStickers(final int type, final ArrayList res, final boolean cache, final int date, final int hash) { + private void processLoadedStickers(int type, ArrayList res, boolean cache, int date, long hash) { AndroidUtilities.runOnUIThread(() -> { loadingStickers[type] = false; stickersLoaded[type] = true; @@ -1730,12 +1733,12 @@ public class MediaDataController extends BaseController { } if (res != null) { try { - final ArrayList stickerSetsNew = new ArrayList<>(); - final LongSparseArray stickerSetsByIdNew = new LongSparseArray<>(); - final HashMap stickerSetsByNameNew = new HashMap<>(); - final LongSparseArray stickersByEmojiNew = new LongSparseArray<>(); - final LongSparseArray stickersByIdNew = new LongSparseArray<>(); - final HashMap> allStickersNew = new HashMap<>(); + ArrayList stickerSetsNew = new ArrayList<>(); + LongSparseArray stickerSetsByIdNew = new LongSparseArray<>(); + HashMap stickerSetsByNameNew = new HashMap<>(); + LongSparseArray stickersByEmojiNew = new LongSparseArray<>(); + LongSparseArray stickersByIdNew = new LongSparseArray<>(); + HashMap> allStickersNew = new HashMap<>(); for (int a = 0; a < res.size(); a++) { TLRPC.TL_messages_stickerSet stickerSet = res.get(a); @@ -1821,7 +1824,7 @@ public class MediaDataController extends BaseController { } public boolean cancelRemovingStickerSet(long id) { - final Runnable undoAction = removingStickerSetsUndos.get(id); + Runnable undoAction = removingStickerSetsUndos.get(id); if (undoAction != null) { undoAction.run(); return true; @@ -1833,7 +1836,7 @@ public class MediaDataController extends BaseController { public void preloadStickerSetThumb(TLRPC.TL_messages_stickerSet stickerSet) { TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(stickerSet.set.thumbs, 90); if (thumb != null) { - final ArrayList documents = stickerSet.documents; + ArrayList documents = stickerSet.documents; if (documents != null && !documents.isEmpty()) { loadStickerSetThumbInternal(thumb, stickerSet, documents.get(0), stickerSet.set.thumb_version); } @@ -1843,7 +1846,7 @@ public class MediaDataController extends BaseController { public void preloadStickerSetThumb(TLRPC.StickerSetCovered stickerSet) { TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(stickerSet.set.thumbs, 90); if (thumb != null) { - final TLRPC.Document sticker; + TLRPC.Document sticker; if (stickerSet.cover != null) { sticker = stickerSet.cover; } else if (!stickerSet.covers.isEmpty()) { @@ -1856,17 +1859,17 @@ public class MediaDataController extends BaseController { } private void loadStickerSetThumbInternal(TLRPC.PhotoSize thumb, Object parentObject, TLRPC.Document sticker, int thumbVersion) { - final ImageLocation imageLocation = ImageLocation.getForSticker(thumb, sticker, thumbVersion); + ImageLocation imageLocation = ImageLocation.getForSticker(thumb, sticker, thumbVersion); if (imageLocation != null) { - final String ext = imageLocation.imageType == FileLoader.IMAGE_TYPE_LOTTIE ? "tgs" : "webp"; + String ext = imageLocation.imageType == FileLoader.IMAGE_TYPE_LOTTIE ? "tgs" : "webp"; getFileLoader().loadFile(imageLocation, parentObject, ext, 2, 1); } } /** @param toggle 0 - remove, 1 - archive, 2 - add */ - public void toggleStickerSet(final Context context, final TLObject stickerSetObject, final int toggle, final BaseFragment baseFragment, final boolean showSettings, boolean showTooltip) { - final TLRPC.StickerSet stickerSet; - final TLRPC.TL_messages_stickerSet messages_stickerSet; + public void toggleStickerSet(Context context, TLObject stickerSetObject, int toggle, BaseFragment baseFragment, boolean showSettings, boolean showTooltip) { + TLRPC.StickerSet stickerSet; + TLRPC.TL_messages_stickerSet messages_stickerSet; if (stickerSetObject instanceof TLRPC.TL_messages_stickerSet) { messages_stickerSet = ((TLRPC.TL_messages_stickerSet) stickerSetObject); @@ -1885,7 +1888,7 @@ public class MediaDataController extends BaseController { throw new IllegalArgumentException("Invalid type of the given stickerSetObject: " + stickerSetObject.getClass()); } - final int type = stickerSet.masks ? TYPE_MASK : TYPE_IMAGE; + int type = stickerSet.masks ? TYPE_MASK : TYPE_IMAGE; stickerSet.archived = toggle == 1; @@ -1917,9 +1920,9 @@ public class MediaDataController extends BaseController { } else if (!showTooltip || baseFragment == null) { toggleStickerSetInternal(context, toggle, baseFragment, showSettings, stickerSetObject, stickerSet, type, false); } else { - final StickerSetBulletinLayout bulletinLayout = new StickerSetBulletinLayout(context, stickerSetObject, toggle); - final int finalCurrentIndex = currentIndex; - final Bulletin.UndoButton undoButton = new Bulletin.UndoButton(context, false).setUndoAction(() -> { + StickerSetBulletinLayout bulletinLayout = new StickerSetBulletinLayout(context, stickerSetObject, toggle); + int finalCurrentIndex = currentIndex; + Bulletin.UndoButton undoButton = new Bulletin.UndoButton(context, false).setUndoAction(() -> { stickerSet.archived = false; stickerSets[type].add(finalCurrentIndex, messages_stickerSet); @@ -1968,13 +1971,13 @@ public class MediaDataController extends BaseController { } /** @param toggle 0 - uninstall, 1 - archive, 2 - unarchive */ - public void toggleStickerSets(final ArrayList stickerSetList, final int type, final int toggle, final BaseFragment baseFragment, final boolean showSettings) { - final int stickerSetListSize = stickerSetList.size(); - final ArrayList inputStickerSets = new ArrayList<>(stickerSetListSize); + public void toggleStickerSets(ArrayList stickerSetList, int type, int toggle, BaseFragment baseFragment, boolean showSettings) { + int stickerSetListSize = stickerSetList.size(); + ArrayList inputStickerSets = new ArrayList<>(stickerSetListSize); for (int i = 0; i < stickerSetListSize; i++) { - final TLRPC.StickerSet stickerSet = stickerSetList.get(i); - final TLRPC.InputStickerSet inputStickerSet = new TLRPC.TL_inputStickerSetID(); + TLRPC.StickerSet stickerSet = stickerSetList.get(i); + TLRPC.InputStickerSet inputStickerSet = new TLRPC.TL_inputStickerSetID(); inputStickerSet.access_hash = stickerSet.access_hash; inputStickerSet.id = stickerSet.id; inputStickerSets.add(inputStickerSet); @@ -2001,7 +2004,7 @@ public class MediaDataController extends BaseController { putStickersToCache(type, this.stickerSets[type], loadDate[type], loadHash[type]); getNotificationCenter().postNotificationName(NotificationCenter.stickersDidLoad, type); - final TLRPC.TL_messages_toggleStickerSets req = new TLRPC.TL_messages_toggleStickerSets(); + TLRPC.TL_messages_toggleStickerSets req = new TLRPC.TL_messages_toggleStickerSets(); req.stickersets = inputStickerSets; switch (toggle) { case 0: @@ -2033,7 +2036,7 @@ public class MediaDataController extends BaseController { loadArchivedStickersCount(type, false); getNotificationCenter().postNotificationName(NotificationCenter.needAddArchivedStickers, response.sets); if (baseFragment != null && baseFragment.getParentActivity() != null) { - final StickersArchiveAlert alert = new StickersArchiveAlert(baseFragment.getParentActivity(), showSettings ? baseFragment : null, response.sets); + StickersArchiveAlert alert = new StickersArchiveAlert(baseFragment.getParentActivity(), showSettings ? baseFragment : null, response.sets); baseFragment.showDialog(alert.create()); } } @@ -2075,11 +2078,11 @@ public class MediaDataController extends BaseController { searchResultMessages.clear(); } - public boolean isMessageFound(final int messageId, boolean mergeDialog) { + public boolean isMessageFound(int messageId, boolean mergeDialog) { return searchResultMessagesMap[mergeDialog ? 1 : 0].indexOfKey(messageId) >= 0; } - public void searchMessagesInChat(String query, final long dialogId, final long mergeDialogId, final int guid, final int direction, int replyMessageId, TLRPC.User user, TLRPC.Chat chat) { + public void searchMessagesInChat(String query, long dialogId, long mergeDialogId, int guid, int direction, int replyMessageId, TLRPC.User user, TLRPC.Chat chat) { searchMessagesInChat(query, dialogId, mergeDialogId, guid, direction, replyMessageId, false, user, chat, true); } @@ -2103,7 +2106,7 @@ public class MediaDataController extends BaseController { loadingMoreSearchMessages = true; } - private void searchMessagesInChat(String query, final long dialogId, final long mergeDialogId, final int guid, final int direction, int replyMessageId, final boolean internal, final TLRPC.User user, final TLRPC.Chat chat, boolean jumpToMessage) { + private void searchMessagesInChat(String query, long dialogId, long mergeDialogId, int guid, int direction, int replyMessageId, boolean internal, TLRPC.User user, TLRPC.Chat chat, boolean jumpToMessage) { int max_id = 0; long queryWithDialog = dialogId; boolean firstQuery = !internal; @@ -2172,11 +2175,11 @@ public class MediaDataController extends BaseController { } if (queryWithDialog == dialogId && firstQuery) { if (mergeDialogId != 0) { - TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer((int) mergeDialogId); + TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(mergeDialogId); if (inputPeer == null) { return; } - final TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); + TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); req.peer = inputPeer; lastMergeDialogId = mergeDialogId; req.limit = 1; @@ -2211,8 +2214,8 @@ public class MediaDataController extends BaseController { messagesSearchCount[1] = 0; } } - final TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); - req.peer = getMessagesController().getInputPeer((int) queryWithDialog); + TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); + req.peer = getMessagesController().getInputPeer(queryWithDialog); if (req.peer == null) { return; } @@ -2236,9 +2239,9 @@ public class MediaDataController extends BaseController { req.flags |= 2; } req.filter = new TLRPC.TL_inputMessagesFilterEmpty(); - final int currentReqId = ++lastReqId; + int currentReqId = ++lastReqId; lastSearchQuery = query; - final long queryWithDialogFinal = queryWithDialog; + long queryWithDialogFinal = queryWithDialog; String finalQuery = query; reqId = getConnectionsManager().sendRequest(req, (response, error) -> { ArrayList messageObjects = new ArrayList<>(); @@ -2324,15 +2327,14 @@ public class MediaDataController extends BaseController { public final static int MEDIA_GIF = 5; public final static int MEDIA_TYPES_COUNT = 6; - public void loadMedia(long uid, int count, int max_id, int type, int fromCache, int classGuid) { - final boolean isChannel = (int) uid < 0 && ChatObject.isChannel(-(int) uid, currentAccount); + public void loadMedia(long dialogId, int count, int max_id, int type, int fromCache, int classGuid) { + boolean isChannel = DialogObject.isChatDialog(dialogId) && ChatObject.isChannel(-dialogId, currentAccount); if (BuildVars.LOGS_ENABLED) { - FileLog.d("load media did " + uid + " count = " + count + " max_id " + max_id + " type = " + type + " cache = " + fromCache + " classGuid = " + classGuid); + FileLog.d("load media did " + dialogId + " count = " + count + " max_id " + max_id + " type = " + type + " cache = " + fromCache + " classGuid = " + classGuid); } - int lower_part = (int)uid; - if (fromCache != 0 || lower_part == 0) { - loadMediaDatabase(uid, count, max_id, type, classGuid, isChannel, fromCache); + if (fromCache != 0 || DialogObject.isEncryptedDialog(dialogId)) { + loadMediaDatabase(dialogId, count, max_id, type, classGuid, isChannel, fromCache); } else { TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); req.limit = count; @@ -2351,28 +2353,28 @@ public class MediaDataController extends BaseController { req.filter = new TLRPC.TL_inputMessagesFilterGif(); } req.q = ""; - req.peer = getMessagesController().getInputPeer(lower_part); + req.peer = getMessagesController().getInputPeer(dialogId); if (req.peer == null) { return; } int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { - final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; - getMessagesController().removeDeletedMessagesFromArray(uid, res.messages); - processLoadedMedia(res, uid, count, max_id, type, 0, classGuid, isChannel, res.messages.size() == 0); + TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; + getMessagesController().removeDeletedMessagesFromArray(dialogId, res.messages); + processLoadedMedia(res, dialogId, count, max_id, type, 0, classGuid, isChannel, res.messages.size() == 0); } }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } } - public void getMediaCounts(final long uid, final int classGuid) { + public void getMediaCounts(long dialogId, int classGuid) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { - int[] counts = new int[] {-1, -1, -1, -1, -1, -1}; - int[] countsFinal = new int[] {-1, -1, -1, -1, -1, -1}; - int[] old = new int[] {0, 0, 0, 0, 0, 0}; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT type, count, old FROM media_counts_v2 WHERE uid = %d", uid)); + int[] counts = new int[]{-1, -1, -1, -1, -1, -1}; + int[] countsFinal = new int[]{-1, -1, -1, -1, -1, -1}; + int[] old = new int[]{0, 0, 0, 0, 0, 0}; + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT type, count, old FROM media_counts_v2 WHERE uid = %d", dialogId)); while (cursor.next()) { int type = cursor.intValue(0); if (type >= 0 && type < MEDIA_TYPES_COUNT) { @@ -2381,25 +2383,24 @@ public class MediaDataController extends BaseController { } } cursor.dispose(); - int lower_part = (int) uid; - if (lower_part == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { for (int a = 0; a < counts.length; a++) { if (counts[a] == -1) { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, a)); + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v3 WHERE uid = %d AND type = %d LIMIT 1", dialogId, a)); if (cursor.next()) { counts[a] = cursor.intValue(0); } else { counts[a] = 0; } cursor.dispose(); - putMediaCountDatabase(uid, a, counts[a]); + putMediaCountDatabase(dialogId, a, counts[a]); } } - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, uid, counts)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, counts)); } else { boolean missing = false; TLRPC.TL_messages_getSearchCounters req = new TLRPC.TL_messages_getSearchCounters(); - req.peer = getMessagesController().getInputPeer(lower_part); + req.peer = getMessagesController().getInputPeer(dialogId); for (int a = 0; a < counts.length; a++) { if (req.peer == null) { counts[a] = 0; @@ -2450,15 +2451,15 @@ public class MediaDataController extends BaseController { continue; } counts[type] = searchCounter.count; - putMediaCountDatabase(uid, type, counts[type]); + putMediaCountDatabase(dialogId, type, counts[type]); } } - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, uid, counts)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, counts)); }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } if (!missing) { - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, uid, countsFinal)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.mediaCountsDidLoad, dialogId, countsFinal)); } } } catch (Exception e) { @@ -2467,10 +2468,9 @@ public class MediaDataController extends BaseController { }); } - public void getMediaCount(final long uid, final int type, final int classGuid, boolean fromCache) { - int lower_part = (int)uid; - if (fromCache || lower_part == 0) { - getMediaCountDatabase(uid, type, classGuid); + public void getMediaCount(long dialogId, int type, int classGuid, boolean fromCache) { + if (fromCache || DialogObject.isEncryptedDialog(dialogId)) { + getMediaCountDatabase(dialogId, type, classGuid); } else { TLRPC.TL_messages_getSearchCounters req = new TLRPC.TL_messages_getSearchCounters(); if (type == MEDIA_PHOTOVIDEO) { @@ -2486,16 +2486,16 @@ public class MediaDataController extends BaseController { } else if (type == MEDIA_GIF) { req.filters.add(new TLRPC.TL_inputMessagesFilterGif()); } - req.peer = getMessagesController().getInputPeer(lower_part); + req.peer = getMessagesController().getInputPeer(dialogId); if (req.peer == null) { return; } int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.Vector res = (TLRPC.Vector) response; + TLRPC.Vector res = (TLRPC.Vector) response; if (!res.objects.isEmpty()) { TLRPC.TL_messages_searchCounter counter = (TLRPC.TL_messages_searchCounter) res.objects.get(0); - processLoadedMediaCount(counter.count, uid, type, classGuid, false, 0); + processLoadedMediaCount(counter.count, dialogId, type, classGuid, false, 0); } } }); @@ -2568,30 +2568,29 @@ public class MediaDataController extends BaseController { } } - private void processLoadedMedia(final TLRPC.messages_Messages res, final long uid, int count, int max_id, final int type, final int fromCache, final int classGuid, final boolean isChannel, final boolean topReached) { + private void processLoadedMedia(TLRPC.messages_Messages res, long dialogId, int count, int max_id, int type, int fromCache, int classGuid, boolean isChannel, boolean topReached) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("process load media did " + uid + " count = " + count + " max_id " + max_id + " type = " + type + " cache = " + fromCache + " classGuid = " + classGuid); + FileLog.d("process load media did " + dialogId + " count = " + count + " max_id " + max_id + " type = " + type + " cache = " + fromCache + " classGuid = " + classGuid); } - int lower_part = (int)uid; - if (fromCache != 0 && res.messages.isEmpty() && lower_part != 0) { + if (fromCache != 0 && res.messages.isEmpty() && !DialogObject.isEncryptedDialog(dialogId)) { if (fromCache == 2) { return; } - loadMedia(uid, count, max_id, type, 0, classGuid); + loadMedia(dialogId, count, max_id, type, 0, classGuid); } else { if (fromCache == 0) { ImageLoader.saveMessagesThumbs(res.messages); getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); - putMediaDatabase(uid, type, res.messages, max_id, topReached); + putMediaDatabase(dialogId, type, res.messages, max_id, topReached); } Utilities.searchQueue.postRunnable(() -> { - final SparseArray usersDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User u = res.users.get(a); usersDict.put(u.id, u); } - final ArrayList objects = new ArrayList<>(); + ArrayList objects = new ArrayList<>(); for (int a = 0; a < res.messages.size(); a++) { TLRPC.Message message = res.messages.get(a); MessageObject messageObject = new MessageObject(currentAccount, message, usersDict, true, true); @@ -2603,29 +2602,29 @@ public class MediaDataController extends BaseController { int totalCount = res.count; getMessagesController().putUsers(res.users, fromCache != 0); getMessagesController().putChats(res.chats, fromCache != 0); - getNotificationCenter().postNotificationName(NotificationCenter.mediaDidLoad, uid, totalCount, objects, classGuid, type, topReached); + getNotificationCenter().postNotificationName(NotificationCenter.mediaDidLoad, dialogId, totalCount, objects, classGuid, type, topReached); }); }); } } - private void processLoadedMediaCount(final int count, final long uid, final int type, final int classGuid, final boolean fromCache, int old) { + private void processLoadedMediaCount(int count, long dialogId, int type, int classGuid, boolean fromCache, int old) { AndroidUtilities.runOnUIThread(() -> { - int lower_part = (int) uid; - boolean reload = fromCache && (count == -1 || count == 0 && type == 2) && lower_part != 0; - if (reload || old == 1 && lower_part != 0) { - getMediaCount(uid, type, classGuid, false); + boolean isEncryptedDialog = DialogObject.isEncryptedDialog(dialogId); + boolean reload = fromCache && (count == -1 || count == 0 && type == 2) && !isEncryptedDialog; + if (reload || old == 1 && !isEncryptedDialog) { + getMediaCount(dialogId, type, classGuid, false); } if (!reload) { if (!fromCache) { - putMediaCountDatabase(uid, type, count); + putMediaCountDatabase(dialogId, type, count); } - getNotificationCenter().postNotificationName(NotificationCenter.mediaCountDidLoad, uid, (fromCache && count == -1 ? 0 : count), fromCache, type); + getNotificationCenter().postNotificationName(NotificationCenter.mediaCountDidLoad, dialogId, (fromCache && count == -1 ? 0 : count), fromCache, type); } }); } - private void putMediaCountDatabase(final long uid, final int type, final int count) { + private void putMediaCountDatabase(long uid, int type, int count) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { SQLitePreparedStatement state2 = getMessagesStorage().getDatabase().executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?, ?)"); @@ -2642,66 +2641,56 @@ public class MediaDataController extends BaseController { }); } - private void getMediaCountDatabase(final long uid, final int type, final int classGuid) { + private void getMediaCountDatabase(long dialogId, int type, int classGuid) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { int count = -1; int old = 0; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type)); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", dialogId, type)); if (cursor.next()) { count = cursor.intValue(0); old = cursor.intValue(1); } cursor.dispose(); - int lower_part = (int)uid; - if (count == -1 && lower_part == 0) { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type)); + if (count == -1 && DialogObject.isEncryptedDialog(dialogId)) { + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM media_v3 WHERE uid = %d AND type = %d LIMIT 1", dialogId, type)); if (cursor.next()) { count = cursor.intValue(0); } cursor.dispose(); if (count != -1) { - putMediaCountDatabase(uid, type, count); + putMediaCountDatabase(dialogId, type, count); } } - processLoadedMediaCount(count, uid, type, classGuid, true, old); + processLoadedMediaCount(count, dialogId, type, classGuid, true, old); } catch (Exception e) { FileLog.e(e); } }); } - private void loadMediaDatabase(final long uid, final int count, final int max_id, final int type, final int classGuid, final boolean isChannel, final int fromCache) { + private void loadMediaDatabase(long uid, int count, int max_id, int type, int classGuid, boolean isChannel, int fromCache) { Runnable runnable = new Runnable() { @Override public void run() { boolean topReached = false; TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages(); try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); int countToLoad = count + 1; SQLiteCursor cursor; SQLiteDatabase database = getMessagesStorage().getDatabase(); boolean isEnd = false; - if ((int) uid != 0) { - int channelId = 0; - long messageMaxId = max_id; - if (isChannel) { - channelId = -(int) uid; - } - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } - + if (!DialogObject.isEncryptedDialog(uid)) { cursor = database.queryFinalized(String.format(Locale.US, "SELECT start FROM media_holes_v2 WHERE uid = %d AND type = %d AND start IN (0, 1)", uid, type)); if (cursor.next()) { isEnd = cursor.intValue(0) == 1; } else { cursor.dispose(); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM media_v2 WHERE uid = %d AND type = %d AND mid > 0", uid, type)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM media_v3 WHERE uid = %d AND type = %d AND mid > 0", uid, type)); if (cursor.next()) { int mid = cursor.intValue(0); if (mid != 0) { @@ -2718,42 +2707,36 @@ public class MediaDataController extends BaseController { } cursor.dispose(); - long holeMessageId = 0; - if (messageMaxId != 0) { + int holeMessageId = 0; + if (max_id != 0) { cursor = database.queryFinalized(String.format(Locale.US, "SELECT end FROM media_holes_v2 WHERE uid = %d AND type = %d AND end <= %d ORDER BY end DESC LIMIT 1", uid, type, max_id)); if (cursor.next()) { holeMessageId = cursor.intValue(0); - if (channelId != 0) { - holeMessageId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageId > 1) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND mid < %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, messageMaxId, holeMessageId, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid > 0 AND mid < %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, max_id, holeMessageId, type, countToLoad)); } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, messageMaxId, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid > 0 AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, max_id, type, countToLoad)); } } else { cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(end) FROM media_holes_v2 WHERE uid = %d AND type = %d", uid, type)); if (cursor.next()) { holeMessageId = cursor.intValue(0); - if (channelId != 0) { - holeMessageId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageId > 1) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, holeMessageId, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid >= %d AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, holeMessageId, type, countToLoad)); } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC LIMIT %d", uid, type, countToLoad)); } } } else { isEnd = true; if (max_id != 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v2 as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, max_id, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v3 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, max_id, type, countToLoad)); } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v2 as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, type, countToLoad)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, r.random_id FROM media_v3 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid WHERE m.uid = %d AND type = %d ORDER BY m.mid ASC LIMIT %d", uid, type, countToLoad)); } } @@ -2765,7 +2748,7 @@ public class MediaDataController extends BaseController { data.reuse(); message.id = cursor.intValue(1); message.dialog_id = uid; - if ((int) uid == 0) { + if (DialogObject.isEncryptedDialog(uid)) { message.random_id = cursor.longValue(2); } res.messages.add(message); @@ -2781,7 +2764,6 @@ public class MediaDataController extends BaseController { getMessagesStorage().getChatsInternal(TextUtils.join(",", chatsToLoad), res.chats); } if (res.messages.size() > count) { - topReached = false; res.messages.remove(res.messages.size() - 1); } else { topReached = isEnd; @@ -2803,7 +2785,7 @@ public class MediaDataController extends BaseController { messagesStorage.bindTaskToGuid(runnable, classGuid); } - private void putMediaDatabase(final long uid, final int type, final ArrayList messages, final int max_id, final boolean topReached) { + private void putMediaDatabase(long uid, int type, ArrayList messages, int max_id, boolean topReached) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { if (messages.isEmpty() || topReached) { @@ -2813,18 +2795,13 @@ public class MediaDataController extends BaseController { } } getMessagesStorage().getDatabase().beginTransaction(); - SQLitePreparedStatement state2 = getMessagesStorage().getDatabase().executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); + SQLitePreparedStatement state2 = getMessagesStorage().getDatabase().executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); for (TLRPC.Message message : messages) { if (canAddMessageToMedia(message)) { - long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - state2.requery(); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - state2.bindLong(1, messageId); + state2.bindInteger(1, message.id); state2.bindLong(2, uid); state2.bindInteger(3, message.date); state2.bindInteger(4, type); @@ -2849,26 +2826,25 @@ public class MediaDataController extends BaseController { }); } - public void loadMusic(final long uid, final long maxId, final long minId) { + public void loadMusic(long dialogId, long maxId, long minId) { getMessagesStorage().getStorageQueue().postRunnable(() -> { - final ArrayList arrayListBegin = new ArrayList<>(); - final ArrayList arrayListEnd = new ArrayList<>(); + ArrayList arrayListBegin = new ArrayList<>(); + ArrayList arrayListEnd = new ArrayList<>(); try { - int lower_id = (int) uid; for (int a = 0; a < 2; a++) { ArrayList arrayList = a == 0 ? arrayListBegin : arrayListEnd; SQLiteCursor cursor; if (a == 0) { - if (lower_id != 0) { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", uid, maxId, MEDIA_MUSIC)); + if (!DialogObject.isEncryptedDialog(dialogId)) { + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", dialogId, maxId, MEDIA_MUSIC)); } else { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", uid, maxId, MEDIA_MUSIC)); + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid > %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", dialogId, maxId, MEDIA_MUSIC)); } } else { - if (lower_id != 0) { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid > %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", uid, minId, MEDIA_MUSIC)); + if (!DialogObject.isEncryptedDialog(dialogId)) { + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid > %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", dialogId, minId, MEDIA_MUSIC)); } else { - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v2 WHERE uid = %d AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", uid, minId, MEDIA_MUSIC)); + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid FROM media_v3 WHERE uid = %d AND mid < %d AND type = %d ORDER BY date DESC, mid DESC LIMIT 1000", dialogId, minId, MEDIA_MUSIC)); } } @@ -2880,7 +2856,7 @@ public class MediaDataController extends BaseController { data.reuse(); if (MessageObject.isMusicMessage(message)) { message.id = cursor.intValue(1); - message.dialog_id = uid; + message.dialog_id = dialogId; arrayList.add(0, new MessageObject(currentAccount, message, false, true)); } } @@ -2890,7 +2866,7 @@ public class MediaDataController extends BaseController { } catch (Exception e) { FileLog.e(e); } - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.musicDidLoad, uid, arrayListBegin, arrayListEnd)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.musicDidLoad, dialogId, arrayListBegin, arrayListEnd)); }); } //---------------- MEDIA END ---------------- @@ -2912,7 +2888,7 @@ public class MediaDataController extends BaseController { if (maxShortcuts <= 0) { maxShortcuts = 5; } - final ArrayList hintsFinal = new ArrayList<>(); + ArrayList hintsFinal = new ArrayList<>(); if (SharedConfig.passcodeHash.length() <= 0) { for (int a = 0; a < hints.size(); a++) { hintsFinal.add(hints.get(a)); @@ -2937,16 +2913,7 @@ public class MediaDataController extends BaseController { newShortcutsIds.add("compose"); for (int a = 0; a < hintsFinal.size(); a++) { TLRPC.TL_topPeer hint = hintsFinal.get(a); - long did; - if (hint.peer.user_id != 0) { - did = hint.peer.user_id; - } else { - did = -hint.peer.chat_id; - if (did == 0) { - did = -hint.peer.channel_id; - } - } - newShortcutsIds.add("did3_" + did); + newShortcutsIds.add("did3_" + MessageObject.getPeerId(hint.peer)); } for (int a = 0; a < currentShortcuts.size(); a++) { String id = currentShortcuts.get(a).getId(); @@ -2989,19 +2956,13 @@ public class MediaDataController extends BaseController { TLRPC.User user = null; TLRPC.Chat chat = null; - long did; - if (hint.peer.user_id != 0) { - shortcutIntent.putExtra("userId", hint.peer.user_id); - user = getMessagesController().getUser(hint.peer.user_id); - did = hint.peer.user_id; + long peerId = MessageObject.getPeerId(hint.peer); + if (DialogObject.isUserDialog(peerId)) { + shortcutIntent.putExtra("userId", peerId); + user = getMessagesController().getUser(peerId); } else { - int chat_id = hint.peer.chat_id; - if (chat_id == 0) { - chat_id = hint.peer.channel_id; - } - chat = getMessagesController().getChat(chat_id); - shortcutIntent.putExtra("chatId", chat_id); - did = -chat_id; + chat = getMessagesController().getChat(-peerId); + shortcutIntent.putExtra("chatId", -peerId); } if ((user == null || UserObject.isDeleted(user)) && chat == null) { continue; @@ -3023,8 +2984,8 @@ public class MediaDataController extends BaseController { } shortcutIntent.putExtra("currentAccount", currentAccount); - shortcutIntent.setAction("com.tmessages.openchat" + did); - shortcutIntent.putExtra("dialogId", did); + shortcutIntent.setAction("com.tmessages.openchat" + peerId); + shortcutIntent.putExtra("dialogId", peerId); shortcutIntent.putExtra("hash", SharedConfig.directShareHash); shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); @@ -3061,7 +3022,7 @@ public class MediaDataController extends BaseController { } } - String id = "did3_" + did; + String id = "did3_" + peerId; if (TextUtils.isEmpty(name)) { name = " "; } @@ -3101,17 +3062,17 @@ public class MediaDataController extends BaseController { } loading = true; getMessagesStorage().getStorageQueue().postRunnable(() -> { - final ArrayList hintsNew = new ArrayList<>(); - final ArrayList inlineBotsNew = new ArrayList<>(); - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - int selfUserId = getUserConfig().getClientUserId(); + ArrayList hintsNew = new ArrayList<>(); + ArrayList inlineBotsNew = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + long selfUserId = getUserConfig().getClientUserId(); try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT did, type, rating FROM chat_hints WHERE 1 ORDER BY rating DESC"); while (cursor.next()) { - int did = cursor.intValue(0); + long did = cursor.longValue(0); if (did == selfUserId) { continue; } @@ -3174,7 +3135,7 @@ public class MediaDataController extends BaseController { getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_contacts_topPeers) { AndroidUtilities.runOnUIThread(() -> { - final TLRPC.TL_contacts_topPeers topPeers = (TLRPC.TL_contacts_topPeers) response; + TLRPC.TL_contacts_topPeers topPeers = (TLRPC.TL_contacts_topPeers) response; getMessagesController().putUsers(topPeers.users, false); getMessagesController().putChats(topPeers.chats, false); for (int a = 0; a < topPeers.categories.size(); a++) { @@ -3184,7 +3145,7 @@ public class MediaDataController extends BaseController { getUserConfig().botRatingLoadTime = (int) (System.currentTimeMillis() / 1000); } else { hints = category.peers; - int selfUserId = getUserConfig().getClientUserId(); + long selfUserId = getUserConfig().getClientUserId(); for (int b = 0; b < hints.size(); b++) { TLRPC.TL_topPeer topPeer = hints.get(b); if (topPeer.peer.user_id == selfUserId) { @@ -3216,16 +3177,8 @@ public class MediaDataController extends BaseController { } for (int b = 0; b < category.peers.size(); b++) { TLRPC.TL_topPeer peer = category.peers.get(b); - int did; - if (peer.peer instanceof TLRPC.TL_peerUser) { - did = peer.peer.user_id; - } else if (peer.peer instanceof TLRPC.TL_peerChat) { - did = -peer.peer.chat_id; - } else { - did = -peer.peer.channel_id; - } state.requery(); - state.bindInteger(1, did); + state.bindLong(1, MessageObject.getPeerId(peer.peer)); state.bindInteger(2, type); state.bindDouble(3, peer.rating); state.bindInteger(4, 0); @@ -3273,7 +3226,7 @@ public class MediaDataController extends BaseController { buildShortcuts(); } - public void increaseInlineRaiting(final int uid) { + public void increaseInlineRaiting(long uid) { if (!getUserConfig().suggestContacts) { return; } @@ -3314,25 +3267,25 @@ public class MediaDataController extends BaseController { getNotificationCenter().postNotificationName(NotificationCenter.reloadInlineHints); } - public void removeInline(final int uid) { + public void removeInline(long dialogId) { TLRPC.TL_topPeerCategoryPeers category = null; for (int a = 0; a < inlineBots.size(); a++) { - if (inlineBots.get(a).peer.user_id == uid) { + if (inlineBots.get(a).peer.user_id == dialogId) { inlineBots.remove(a); TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating(); req.category = new TLRPC.TL_topPeerCategoryBotsInline(); - req.peer = getMessagesController().getInputPeer(uid); + req.peer = getMessagesController().getInputPeer(dialogId); getConnectionsManager().sendRequest(req, (response, error) -> { }); - deletePeer(uid, 1); + deletePeer(dialogId, 1); getNotificationCenter().postNotificationName(NotificationCenter.reloadInlineHints); return; } } } - public void removePeer(final int uid) { + public void removePeer(long uid) { for (int a = 0; a < hints.size(); a++) { if (hints.get(a).peer.user_id == uid) { hints.remove(a); @@ -3349,18 +3302,15 @@ public class MediaDataController extends BaseController { } } - public void increasePeerRaiting(final long did) { + public void increasePeerRaiting(long dialogId) { if (!getUserConfig().suggestContacts) { return; } - final int lower_id = (int) did; - if (lower_id <= 0) { + if (!DialogObject.isUserDialog(dialogId)) { return; } - //remove chats and bots for now - final TLRPC.User user = lower_id > 0 ? getMessagesController().getUser(lower_id) : null; - //final TLRPC.Chat chat = lower_id < 0 ? MessagesController.getInstance().getChat(-lower_id) : null; - if (user == null || user.bot || user.self/*&& chat == null || ChatObject.isChannel(chat) && !chat.megagroup*/) { + TLRPC.User user = getMessagesController().getUser(dialogId); + if (user == null || user.bot || user.self) { return; } getMessagesStorage().getStorageQueue().postRunnable(() -> { @@ -3368,7 +3318,7 @@ public class MediaDataController extends BaseController { try { int lastTime = 0; int lastMid = 0; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT MAX(mid), MAX(date) FROM messages WHERE uid = %d AND out = 1", did)); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT MAX(mid), MAX(date) FROM messages_v2 WHERE uid = %d AND out = 1", dialogId)); if (cursor.next()) { lastMid = cursor.intValue(0); lastTime = cursor.intValue(1); @@ -3380,25 +3330,20 @@ public class MediaDataController extends BaseController { } catch (Exception e) { FileLog.e(e); } - final double dtFinal = dt; + double dtFinal = dt; AndroidUtilities.runOnUIThread(() -> { TLRPC.TL_topPeer peer = null; for (int a = 0; a < hints.size(); a++) { TLRPC.TL_topPeer p = hints.get(a); - if (lower_id < 0 && (p.peer.chat_id == -lower_id || p.peer.channel_id == -lower_id) || lower_id > 0 && p.peer.user_id == lower_id) { + if (p.peer.user_id == dialogId) { peer = p; break; } } if (peer == null) { peer = new TLRPC.TL_topPeer(); - if (lower_id > 0) { - peer.peer = new TLRPC.TL_peerUser(); - peer.peer.user_id = lower_id; - } else { - peer.peer = new TLRPC.TL_peerChat(); - peer.peer.chat_id = -lower_id; - } + peer.peer = new TLRPC.TL_peerUser(); + peer.peer.user_id = dialogId; hints.add(peer); } peer.rating += Math.exp(dtFinal / getMessagesController().ratingDecay); @@ -3411,19 +3356,19 @@ public class MediaDataController extends BaseController { return 0; }); - savePeer((int) did, 0, peer.rating); + savePeer(dialogId, 0, peer.rating); getNotificationCenter().postNotificationName(NotificationCenter.reloadHints); }); }); } - private void savePeer(final int did, final int type, final double rating) { + private void savePeer(long did, int type, double rating) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { SQLitePreparedStatement state = getMessagesStorage().getDatabase().executeFast("REPLACE INTO chat_hints VALUES(?, ?, ?, ?)"); state.requery(); - state.bindInteger(1, did); + state.bindLong(1, did); state.bindInteger(2, type); state.bindDouble(3, rating); state.bindInteger(4, (int) System.currentTimeMillis() / 1000); @@ -3435,61 +3380,56 @@ public class MediaDataController extends BaseController { }); } - private void deletePeer(final int did, final int type) { + private void deletePeer(long dialogId, int type) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { - getMessagesStorage().getDatabase().executeFast(String.format(Locale.US, "DELETE FROM chat_hints WHERE did = %d AND type = %d", did, type)).stepThis().dispose(); + getMessagesStorage().getDatabase().executeFast(String.format(Locale.US, "DELETE FROM chat_hints WHERE did = %d AND type = %d", dialogId, type)).stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } }); } - private Intent createIntrnalShortcutIntent(long did) { + private Intent createIntrnalShortcutIntent(long dialogId) { Intent shortcutIntent = new Intent(ApplicationLoader.applicationContext, OpenChatReceiver.class); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - - if (lower_id == 0) { - shortcutIntent.putExtra("encId", high_id); - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + shortcutIntent.putExtra("encId", encryptedChatId); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { return null; } - } else if (lower_id > 0) { - shortcutIntent.putExtra("userId", lower_id); - } else if (lower_id < 0) { - shortcutIntent.putExtra("chatId", -lower_id); + } else if (DialogObject.isUserDialog(dialogId)) { + shortcutIntent.putExtra("userId", dialogId); + } else if (DialogObject.isChatDialog(dialogId)) { + shortcutIntent.putExtra("chatId", -dialogId); } else { return null; } shortcutIntent.putExtra("currentAccount", currentAccount); - shortcutIntent.setAction("com.tmessages.openchat" + did); + shortcutIntent.setAction("com.tmessages.openchat" + dialogId); shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return shortcutIntent; } - public void installShortcut(long did) { + public void installShortcut(long dialogId) { try { - - Intent shortcutIntent = createIntrnalShortcutIntent(did); - - int lower_id = (int) did; - int high_id = (int) (did >> 32); + Intent shortcutIntent = createIntrnalShortcutIntent(dialogId); TLRPC.User user = null; TLRPC.Chat chat = null; - if (lower_id == 0) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { return; } user = getMessagesController().getUser(encryptedChat.user_id); - } else if (lower_id > 0) { - user = getMessagesController().getUser(lower_id); - } else if (lower_id < 0) { - chat = getMessagesController().getChat(-lower_id); + } else if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); + } else if (DialogObject.isChatDialog(dialogId)) { + chat = getMessagesController().getChat(-dialogId); } else { return; } @@ -3576,7 +3516,7 @@ public class MediaDataController extends BaseController { } if (Build.VERSION.SDK_INT >= 26) { ShortcutInfoCompat.Builder pinShortcutInfo = - new ShortcutInfoCompat.Builder(ApplicationLoader.applicationContext, "sdid_" + did) + new ShortcutInfoCompat.Builder(ApplicationLoader.applicationContext, "sdid_" + dialogId) .setShortLabel(name) .setIntent(shortcutIntent); @@ -3589,7 +3529,7 @@ public class MediaDataController extends BaseController { } else { pinShortcutInfo.setIcon(IconCompat.createWithResource(ApplicationLoader.applicationContext, R.drawable.book_user)); } - } else if (chat != null) { + } else { if (ChatObject.isChannel(chat) && !chat.megagroup) { pinShortcutInfo.setIcon(IconCompat.createWithResource(ApplicationLoader.applicationContext, R.drawable.book_channel)); } else { @@ -3610,7 +3550,7 @@ public class MediaDataController extends BaseController { } else { addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(ApplicationLoader.applicationContext, R.drawable.book_user)); } - } else if (chat != null) { + } else { if (ChatObject.isChannel(chat) && !chat.megagroup) { addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(ApplicationLoader.applicationContext, R.drawable.book_channel)); } else { @@ -3631,33 +3571,31 @@ public class MediaDataController extends BaseController { } } - public void uninstallShortcut(long did) { + public void uninstallShortcut(long dialogId) { try { if (Build.VERSION.SDK_INT >= 26) { ArrayList arrayList = new ArrayList<>(); - arrayList.add("sdid_" + did); - arrayList.add("ndid_" + did); + arrayList.add("sdid_" + dialogId); + arrayList.add("ndid_" + dialogId); ShortcutManagerCompat.removeDynamicShortcuts(ApplicationLoader.applicationContext, arrayList); if (Build.VERSION.SDK_INT >= 30) { ShortcutManager shortcutManager = ApplicationLoader.applicationContext.getSystemService(ShortcutManager.class); shortcutManager.removeLongLivedShortcuts(arrayList); } } else { - int lower_id = (int) did; - int high_id = (int) (did >> 32); - TLRPC.User user = null; TLRPC.Chat chat = null; - if (lower_id == 0) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { return; } user = getMessagesController().getUser(encryptedChat.user_id); - } else if (lower_id > 0) { - user = getMessagesController().getUser(lower_id); - } else if (lower_id < 0) { - chat = getMessagesController().getChat(-lower_id); + } else if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); + } else if (DialogObject.isChatDialog(dialogId)) { + chat = getMessagesController().getChat(-dialogId); } else { return; } @@ -3673,7 +3611,7 @@ public class MediaDataController extends BaseController { } Intent addIntent = new Intent(); - addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, createIntrnalShortcutIntent(did)); + addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, createIntrnalShortcutIntent(dialogId)); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); addIntent.putExtra("duplicate", false); @@ -3703,7 +3641,7 @@ public class MediaDataController extends BaseController { } loadingPinnedMessages.put(dialogId, true); TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); - req.peer = getMessagesController().getInputPeer((int) dialogId); + req.peer = getMessagesController().getInputPeer(dialogId); req.limit = 40; req.offset_id = maxId; req.q = ""; @@ -3715,12 +3653,12 @@ public class MediaDataController extends BaseController { boolean endReached; if (response instanceof TLRPC.messages_Messages) { TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; - final SparseArray usersDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User user = res.users.get(a); usersDict.put(user.id, user); } - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < res.chats.size(); a++) { TLRPC.Chat chat = res.chats.get(a); chatsDict.put(chat.id, chat); @@ -3753,7 +3691,7 @@ public class MediaDataController extends BaseController { }); } - public ArrayList loadPinnedMessages(long dialogId, int channelId, ArrayList mids, boolean useQueue) { + public ArrayList loadPinnedMessages(long dialogId, long channelId, ArrayList mids, boolean useQueue) { if (useQueue) { getMessagesStorage().getStorageQueue().postRunnable(() -> loadPinnedMessageInternal(dialogId, channelId, mids, false)); } else { @@ -3762,14 +3700,14 @@ public class MediaDataController extends BaseController { return null; } - private ArrayList loadPinnedMessageInternal(long dialogId, int channelId, ArrayList mids, boolean returnValue) { + private ArrayList loadPinnedMessageInternal(long dialogId, long channelId, ArrayList mids, boolean returnValue) { try { ArrayList midsCopy = new ArrayList<>(mids); CharSequence longIds; if (channelId != 0) { StringBuilder builder = new StringBuilder(); for (int a = 0, N = mids.size(); a < N; a++) { - long messageId = ((long) mids.get(a)) | ((long) channelId) << 32; + Integer messageId = mids.get(a); if (builder.length() != 0) { builder.append(","); } @@ -3781,28 +3719,28 @@ public class MediaDataController extends BaseController { } ArrayList results = new ArrayList<>(); - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN (%s)", longIds)); + long selfUserId = getUserConfig().clientUserId; + + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages_v2 WHERE mid IN (%s) AND uid = %d", longIds, dialogId)); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TLRPC.Message result = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - result.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - if (result.action instanceof TLRPC.TL_messageActionHistoryClear) { - result = null; - } else { + if (!(result.action instanceof TLRPC.TL_messageActionHistoryClear)) { + result.readAttachPath(data, selfUserId); result.id = cursor.intValue(1); result.date = cursor.intValue(2); result.dialog_id = dialogId; MessagesStorage.addUsersAndChatsFromMessage(result, usersToLoad, chatsToLoad); results.add(result); + midsCopy.remove((Integer) result.id); } - midsCopy.remove((Integer) result.id); + data.reuse(); } } cursor.dispose(); @@ -3813,16 +3751,14 @@ public class MediaDataController extends BaseController { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { TLRPC.Message result = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - result.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - if (result.action instanceof TLRPC.TL_messageActionHistoryClear) { - result = null; - } else { + if (!(result.action instanceof TLRPC.TL_messageActionHistoryClear)) { + result.readAttachPath(data, selfUserId); result.dialog_id = dialogId; MessagesStorage.addUsersAndChatsFromMessage(result, usersToLoad, chatsToLoad); results.add(result); + midsCopy.remove((Integer) result.id); } - midsCopy.remove((Integer) result.id); + data.reuse(); } } cursor.dispose(); @@ -3830,7 +3766,7 @@ public class MediaDataController extends BaseController { if (!midsCopy.isEmpty()) { if (channelId != 0) { - final TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); + TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); req.channel = getMessagesController().getInputChannel(channelId); req.id = midsCopy; getConnectionsManager().sendRequest(req, (response, error) -> { @@ -3852,7 +3788,7 @@ public class MediaDataController extends BaseController { } }); } else { - final TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages(); + TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages(); req.id = midsCopy; getConnectionsManager().sendRequest(req, (response, error) -> { boolean ok = false; @@ -3920,16 +3856,16 @@ public class MediaDataController extends BaseController { }); } - private ArrayList broadcastPinnedMessage(final ArrayList results, final ArrayList users, final ArrayList chats, final boolean isCache, boolean returnValue) { + private ArrayList broadcastPinnedMessage(ArrayList results, ArrayList users, ArrayList chats, boolean isCache, boolean returnValue) { if (results.isEmpty()) { return null; } - final SparseArray usersDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0; a < users.size(); a++) { TLRPC.User user = users.get(a); usersDict.put(user.id, user); } - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < chats.size(); a++) { TLRPC.Chat chat = chats.get(a); chatsDict.put(chat.id, chat); @@ -3977,10 +3913,10 @@ public class MediaDataController extends BaseController { } } - public void loadReplyMessagesForMessages(final ArrayList messages, final long dialogId, boolean scheduled, Runnable callback) { - if ((int) dialogId == 0) { - final ArrayList replyMessages = new ArrayList<>(); - final LongSparseArray> replyMessageRandomOwners = new LongSparseArray<>(); + public void loadReplyMessagesForMessages(ArrayList messages, long dialogId, boolean scheduled, Runnable callback) { + if (DialogObject.isEncryptedDialog(dialogId)) { + ArrayList replyMessages = new ArrayList<>(); + LongSparseArray> replyMessageRandomOwners = new LongSparseArray<>(); for (int a = 0; a < messages.size(); a++) { MessageObject messageObject = messages.get(a); if (messageObject == null) { @@ -4009,7 +3945,7 @@ public class MediaDataController extends BaseController { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { ArrayList loadedMessages = new ArrayList<>(); - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessages))); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms_v2 as r INNER JOIN messages_v2 as m ON r.mid = m.mid AND r.uid = m.uid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessages))); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -4056,48 +3992,39 @@ public class MediaDataController extends BaseController { } }); } else { - final HashMap> replyMessages = new HashMap<>(); - final LongSparseArray> replyMessageOwners = new LongSparseArray<>(); - final StringBuilder stringBuilder = new StringBuilder(); + LongSparseArray>> replyMessageOwners = new LongSparseArray<>(); + LongSparseArray> dialogReplyMessagesIds = new LongSparseArray<>(); for (int a = 0; a < messages.size(); a++) { MessageObject messageObject = messages.get(a); if (messageObject == null) { continue; } if (messageObject.getId() > 0 && messageObject.isReply() && messageObject.replyMessageObject == null) { - int id = messageObject.messageOwner.reply_to.reply_to_msg_id; - long messageId = id; - int channelId = 0; - if (messageObject.messageOwner.reply_to.reply_to_peer_id != null) { - if (messageObject.messageOwner.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) messageObject.messageOwner.reply_to.reply_to_peer_id.channel_id) << 32; - channelId = messageObject.messageOwner.reply_to.reply_to_peer_id.channel_id; + int messageId = messageObject.messageOwner.reply_to.reply_to_msg_id; + long did = MessageObject.getReplyToDialogId(messageObject.messageOwner); + long channelId = messageObject.messageOwner.peer_id != null ? messageObject.messageOwner.peer_id.channel_id : 0; + SparseArray> sparseArray = replyMessageOwners.get(dialogId); + ArrayList ids = dialogReplyMessagesIds.get(channelId); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + replyMessageOwners.put(dialogId, sparseArray); + } + if (ids == null) { + ids = new ArrayList<>(); + dialogReplyMessagesIds.put(channelId, ids); + } + ArrayList arrayList = sparseArray.get(messageObject.messageOwner.reply_to.reply_to_msg_id); + if (arrayList == null) { + arrayList = new ArrayList<>(); + sparseArray.put(messageObject.messageOwner.reply_to.reply_to_msg_id, arrayList); + if (!ids.contains(messageObject.messageOwner.reply_to.reply_to_msg_id)) { + ids.add(messageObject.messageOwner.reply_to.reply_to_msg_id); } - } else if (messageObject.messageOwner.peer_id.channel_id != 0) { - messageId |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; - channelId = messageObject.messageOwner.peer_id.channel_id; - } - if (stringBuilder.length() > 0) { - stringBuilder.append(','); - } - stringBuilder.append(messageId); - ArrayList messageObjects = replyMessageOwners.get(messageId); - if (messageObjects == null) { - messageObjects = new ArrayList<>(); - replyMessageOwners.put(messageId, messageObjects); - } - messageObjects.add(messageObject); - ArrayList mids = replyMessages.get(channelId); - if (mids == null) { - mids = new ArrayList<>(); - replyMessages.put(channelId, mids); - } - if (!mids.contains(id)) { - mids.add(id); } + arrayList.add(messageObject); } } - if (replyMessages.isEmpty()) { + if (replyMessageOwners.isEmpty()) { if (callback != null) { callback.run(); } @@ -4106,35 +4033,44 @@ public class MediaDataController extends BaseController { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { - final ArrayList result = new ArrayList<>(); - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList result = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", stringBuilder.toString())); - while (cursor.next()) { - NativeByteBuffer data = cursor.byteBufferValue(0); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - message.id = cursor.intValue(1); - message.date = cursor.intValue(2); - message.dialog_id = dialogId; - MessagesStorage.addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - result.add(message); - Integer channelId = message.peer_id != null ? message.peer_id.channel_id : 0; - ArrayList mids = replyMessages.get(channelId); - if (mids != null) { - mids.remove((Integer) message.id); - if (mids.isEmpty()) { - replyMessages.remove(channelId); + for (int b = 0, N2 = replyMessageOwners.size(); b < N2; b++) { + long did = replyMessageOwners.keyAt(b); + SparseArray> owners = replyMessageOwners.valueAt(b); + ArrayList ids = dialogReplyMessagesIds.get(did); + if (ids == null) { + continue; + } + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages_v2 WHERE mid IN(%s) AND uid = %d", TextUtils.join(",", ids), dialogId)); + while (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(0); + if (data != null) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + message.readAttachPath(data, getUserConfig().clientUserId); + data.reuse(); + message.id = cursor.intValue(1); + message.date = cursor.intValue(2); + message.dialog_id = dialogId; + MessagesStorage.addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); + result.add(message); + + long channelId = message.peer_id != null ? message.peer_id.channel_id : 0; + ArrayList mids = dialogReplyMessagesIds.get(channelId); + if (mids != null) { + mids.remove((Integer) message.id); + if (mids.isEmpty()) { + dialogReplyMessagesIds.remove(channelId); + } } } } + cursor.dispose(); } - cursor.dispose(); if (!usersToLoad.isEmpty()) { getMessagesStorage().getUsersInternal(TextUtils.join(",", usersToLoad), users); @@ -4144,13 +4080,13 @@ public class MediaDataController extends BaseController { } broadcastReplyMessages(result, replyMessageOwners, users, chats, dialogId, true); - if (!replyMessages.isEmpty()) { - for (HashMap.Entry> entry : replyMessages.entrySet()) { - int channelId = entry.getKey(); + if (!dialogReplyMessagesIds.isEmpty()) { + for (int a = 0, N = dialogReplyMessagesIds.size(); a < N; a++) { + long channelId = dialogReplyMessagesIds.keyAt(a); if (channelId != 0) { - final TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); + TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); req.channel = getMessagesController().getInputChannel(channelId); - req.id = entry.getValue(); + req.id = dialogReplyMessagesIds.valueAt(a); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response; @@ -4166,10 +4102,16 @@ public class MediaDataController extends BaseController { }); } else { TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages(); - req.id = entry.getValue(); + req.id = dialogReplyMessagesIds.valueAt(a); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response; + for (int i = 0; i < messagesRes.messages.size(); i++) { + TLRPC.Message message = messagesRes.messages.get(i); + if (message.dialog_id == 0) { + message.dialog_id = dialogId; + } + } ImageLoader.saveMessagesThumbs(messagesRes.messages); broadcastReplyMessages(messagesRes.messages, replyMessageOwners, messagesRes.users, messagesRes.chats, dialogId, false); getMessagesStorage().putUsersAndChats(messagesRes.users, messagesRes.chats, true, true); @@ -4193,31 +4135,33 @@ public class MediaDataController extends BaseController { } } - private void saveReplyMessages(final LongSparseArray> replyMessageOwners, final ArrayList result, boolean scheduled) { + private void saveReplyMessages(LongSparseArray>> replyMessageOwners, ArrayList result, boolean scheduled) { getMessagesStorage().getStorageQueue().postRunnable(() -> { try { getMessagesStorage().getDatabase().beginTransaction(); SQLitePreparedStatement state; if (scheduled) { - state = getMessagesStorage().getDatabase().executeFast("UPDATE scheduled_messages SET replydata = ? WHERE mid = ?"); + state = getMessagesStorage().getDatabase().executeFast("UPDATE scheduled_messages_v2 SET replydata = ? WHERE mid = ? AND uid = ?"); } else { - state = getMessagesStorage().getDatabase().executeFast("UPDATE messages SET replydata = ? WHERE mid = ?"); + state = getMessagesStorage().getDatabase().executeFast("UPDATE messages_v2 SET replydata = ? WHERE mid = ? AND uid = ?"); } for (int a = 0; a < result.size(); a++) { TLRPC.Message message = result.get(a); - ArrayList messageObjects = replyMessageOwners.get(MessageObject.getIdWithChannel(message)); + long dialogId = MessageObject.getDialogId(message); + SparseArray> sparseArray = replyMessageOwners.get(dialogId); + if (sparseArray == null) { + continue; + } + ArrayList messageObjects = sparseArray.get(message.id); if (messageObjects != null) { NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); for (int b = 0; b < messageObjects.size(); b++) { MessageObject messageObject = messageObjects.get(b); state.requery(); - long messageId = messageObject.getId(); - if (messageObject.messageOwner.peer_id.channel_id != 0) { - messageId |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; - } state.bindByteBuffer(1, data); - state.bindLong(2, messageId); + state.bindInteger(2, messageObject.getId()); + state.bindLong(3, messageObject.getDialogId()); state.step(); } data.reuse(); @@ -4231,18 +4175,18 @@ public class MediaDataController extends BaseController { }); } - private void broadcastReplyMessages(ArrayList result, LongSparseArray> replyMessageOwners, ArrayList users, ArrayList chats, long dialog_id, boolean isCache) { - final SparseArray usersDict = new SparseArray<>(); + private void broadcastReplyMessages(ArrayList result, LongSparseArray>> replyMessageOwners, ArrayList users, ArrayList chats, long dialog_id, boolean isCache) { + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0; a < users.size(); a++) { TLRPC.User user = users.get(a); usersDict.put(user.id, user); } - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < chats.size(); a++) { TLRPC.Chat chat = chats.get(a); chatsDict.put(chat.id, chat); } - final ArrayList messageObjects = new ArrayList<>(); + ArrayList messageObjects = new ArrayList<>(); for (int a = 0, N = result.size(); a < N; a++) { messageObjects.add(new MessageObject(currentAccount, result.get(a), usersDict, chatsDict, false, false)); } @@ -4252,7 +4196,12 @@ public class MediaDataController extends BaseController { boolean changed = false; for (int a = 0, N = messageObjects.size(); a < N; a++) { MessageObject messageObject = messageObjects.get(a); - ArrayList arrayList = replyMessageOwners.get(messageObject.getIdWithChannel()); + long dialogId = messageObject.getDialogId(); + SparseArray> sparseArray = replyMessageOwners.get(dialogId); + if (sparseArray == null) { + continue; + } + ArrayList arrayList = sparseArray.get(messageObject.getId()); if (arrayList != null) { for (int b = 0; b < arrayList.size(); b++) { MessageObject m = arrayList.get(b); @@ -4478,7 +4427,7 @@ public class MediaDataController extends BaseController { b++; N2++; runs.add(b, r); - } else if (newRun.end >= run.end) { + } else { TextStyleSpan.TextStyleRun r = new TextStyleSpan.TextStyleRun(newRun); r.merge(run); r.end = run.end; @@ -4669,7 +4618,7 @@ public class MediaDataController extends BaseController { } for (int b = 0; b < spansMentions.length; b++) { TLRPC.TL_inputMessageEntityMentionName entity = new TLRPC.TL_inputMessageEntityMentionName(); - entity.user_id = getMessagesController().getInputUser(Utilities.parseInt(spansMentions[b].getURL())); + entity.user_id = getMessagesController().getInputUser(Utilities.parseLong(spansMentions[b].getURL())); if (entity.user_id != null) { entity.offset = spannable.getSpanStart(spansMentions[b]); entity.length = Math.min(spannable.getSpanEnd(spansMentions[b]), message[0].length()) - entity.offset; @@ -4794,7 +4743,7 @@ public class MediaDataController extends BaseController { getMessagesController().processUpdates((TLRPC.Updates) response, false); AndroidUtilities.runOnUIThread(() -> { loadingDrafts = false; - final UserConfig userConfig = getUserConfig(); + UserConfig userConfig = getUserConfig(); userConfig.draftsLoaded = true; userConfig.saveConfig(false); }); @@ -4802,12 +4751,12 @@ public class MediaDataController extends BaseController { }); } - public int getDraftFolderId(long did) { - return draftsFolderIds.get(did, 0); + public int getDraftFolderId(long dialogId) { + return draftsFolderIds.get(dialogId, 0); } - public void setDraftFolderId(long did, int folderId) { - draftsFolderIds.put(did, folderId); + public void setDraftFolderId(long dialogId, int folderId) { + draftsFolderIds.put(dialogId, folderId); } public void clearDraftsFolderIds() { @@ -4818,27 +4767,27 @@ public class MediaDataController extends BaseController { return drafts; } - public TLRPC.DraftMessage getDraft(long did, int threadId) { - SparseArray threads = drafts.get(did); + public TLRPC.DraftMessage getDraft(long dialogId, int threadId) { + SparseArray threads = drafts.get(dialogId); if (threads == null) { return null; } return threads.get(threadId); } - public TLRPC.Message getDraftMessage(long did, int threadId) { - SparseArray threads = draftMessages.get(did); + public TLRPC.Message getDraftMessage(long dialogId, int threadId) { + SparseArray threads = draftMessages.get(dialogId); if (threads == null) { return null; } return threads.get(threadId); } - public void saveDraft(long did, int threadId, CharSequence message, ArrayList entities, TLRPC.Message replyToMessage, boolean noWebpage) { - saveDraft(did, threadId, message, entities, replyToMessage, noWebpage, false); + public void saveDraft(long dialogId, int threadId, CharSequence message, ArrayList entities, TLRPC.Message replyToMessage, boolean noWebpage) { + saveDraft(dialogId, threadId, message, entities, replyToMessage, noWebpage, false); } - public void saveDraft(long did, int threadId, CharSequence message, ArrayList entities, TLRPC.Message replyToMessage, boolean noWebpage, boolean clean) { + public void saveDraft(long dialogId, int threadId, CharSequence message, ArrayList entities, TLRPC.Message replyToMessage, boolean noWebpage, boolean clean) { TLRPC.DraftMessage draftMessage; if (!TextUtils.isEmpty(message) || replyToMessage != null) { draftMessage = new TLRPC.TL_draftMessage(); @@ -4857,7 +4806,7 @@ public class MediaDataController extends BaseController { draftMessage.flags |= 8; } - SparseArray threads = drafts.get(did); + SparseArray threads = drafts.get(dialogId); TLRPC.DraftMessage currentDraft = threads == null ? null : threads.get(threadId); if (!clean) { if (currentDraft != null && currentDraft.message.equals(draftMessage.message) && currentDraft.reply_to_msg_id == draftMessage.reply_to_msg_id && currentDraft.no_webpage == draftMessage.no_webpage || @@ -4866,12 +4815,11 @@ public class MediaDataController extends BaseController { } } - saveDraft(did, threadId, draftMessage, replyToMessage, false); + saveDraft(dialogId, threadId, draftMessage, replyToMessage, false); if (threadId == 0) { - int lower_id = (int) did; - if (lower_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { TLRPC.TL_messages_saveDraft req = new TLRPC.TL_messages_saveDraft(); - req.peer = getMessagesController().getInputPeer(lower_id); + req.peer = getMessagesController().getInputPeer(dialogId); if (req.peer == null) { return; } @@ -4889,104 +4837,96 @@ public class MediaDataController extends BaseController { } } - public void saveDraft(long did, int threadId, TLRPC.DraftMessage draft, TLRPC.Message replyToMessage, boolean fromServer) { + public void saveDraft(long dialogId, int threadId, TLRPC.DraftMessage draft, TLRPC.Message replyToMessage, boolean fromServer) { SharedPreferences.Editor editor = draftPreferences.edit(); - final MessagesController messagesController = getMessagesController(); + MessagesController messagesController = getMessagesController(); if (draft == null || draft instanceof TLRPC.TL_draftMessageEmpty) { { - SparseArray threads = drafts.get(did); + SparseArray threads = drafts.get(dialogId); if (threads != null) { threads.remove(threadId); if (threads.size() == 0) { - drafts.remove(did); + drafts.remove(dialogId); } } } { - SparseArray threads = draftMessages.get(did); + SparseArray threads = draftMessages.get(dialogId); if (threads != null) { threads.remove(threadId); if (threads.size() == 0) { - draftMessages.remove(did); + draftMessages.remove(dialogId); } } } if (threadId == 0) { - draftPreferences.edit().remove("" + did).remove("r_" + did).commit(); + draftPreferences.edit().remove("" + dialogId).remove("r_" + dialogId).commit(); } else { - draftPreferences.edit().remove("t_" + did + "_" + threadId).remove("rt_" + did + "_" + threadId).commit(); + draftPreferences.edit().remove("t_" + dialogId + "_" + threadId).remove("rt_" + dialogId + "_" + threadId).commit(); } - messagesController.removeDraftDialogIfNeed(did); + messagesController.removeDraftDialogIfNeed(dialogId); } else { - SparseArray threads = drafts.get(did); + SparseArray threads = drafts.get(dialogId); if (threads == null) { threads = new SparseArray<>(); - drafts.put(did, threads); + drafts.put(dialogId, threads); } threads.put(threadId, draft); if (threadId == 0) { - messagesController.putDraftDialogIfNeed(did, draft); + messagesController.putDraftDialogIfNeed(dialogId, draft); } try { SerializedData serializedData = new SerializedData(draft.getObjectSize()); draft.serializeToStream(serializedData); - editor.putString(threadId == 0 ? ("" + did) : ("t_" + did + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())); + editor.putString(threadId == 0 ? ("" + dialogId) : ("t_" + dialogId + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())); serializedData.cleanup(); } catch (Exception e) { FileLog.e(e); } } - SparseArray threads = draftMessages.get(did); + SparseArray threads = draftMessages.get(dialogId); if (replyToMessage == null) { if (threads != null) { threads.remove(threadId); if (threads.size() == 0) { - draftMessages.remove(did); + draftMessages.remove(dialogId); } } if (threadId == 0) { - editor.remove("r_" + did); + editor.remove("r_" + dialogId); } else { - editor.remove("rt_" + did + "_" + threadId); + editor.remove("rt_" + dialogId + "_" + threadId); } } else { if (threads == null) { threads = new SparseArray<>(); - draftMessages.put(did, threads); + draftMessages.put(dialogId, threads); } threads.put(threadId, replyToMessage); SerializedData serializedData = new SerializedData(replyToMessage.getObjectSize()); replyToMessage.serializeToStream(serializedData); - editor.putString(threadId == 0 ? ("r_" + did) : ("rt_" + did + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())); + editor.putString(threadId == 0 ? ("r_" + dialogId) : ("rt_" + dialogId + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())); serializedData.cleanup(); } editor.commit(); if (fromServer && threadId == 0) { - if (draft.reply_to_msg_id != 0 && replyToMessage == null) { - int lower_id = (int) did; + if (draft != null && draft.reply_to_msg_id != 0 && replyToMessage == null) { TLRPC.User user = null; TLRPC.Chat chat = null; - if (lower_id > 0) { - user = getMessagesController().getUser(lower_id); + if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); } else { - chat = getMessagesController().getChat(-lower_id); + chat = getMessagesController().getChat(-dialogId); } if (user != null || chat != null) { - long messageId = draft.reply_to_msg_id; - final int channelIdFinal; - if (ChatObject.isChannel(chat)) { - messageId |= ((long) chat.id) << 32; - channelIdFinal = chat.id; - } else { - channelIdFinal = 0; - } - final long messageIdFinal = messageId; + long channelId = ChatObject.isChannel(chat) ? chat.id : 0; + int messageId = draft.reply_to_msg_id; getMessagesStorage().getStorageQueue().postRunnable(() -> { try { TLRPC.Message message = null; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data FROM messages WHERE mid = %d", messageIdFinal)); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data FROM messages_v2 WHERE mid = %d and uid = %d", messageId, dialogId)); if (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -4997,32 +4937,32 @@ public class MediaDataController extends BaseController { } cursor.dispose(); if (message == null) { - if (channelIdFinal != 0) { - final TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); - req.channel = getMessagesController().getInputChannel(channelIdFinal); - req.id.add((int) messageIdFinal); + if (channelId != 0) { + TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); + req.channel = getMessagesController().getInputChannel(channelId); + req.id.add(messageId); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response; if (!messagesRes.messages.isEmpty()) { - saveDraftReplyMessage(did, threadId, messagesRes.messages.get(0)); + saveDraftReplyMessage(dialogId, threadId, messagesRes.messages.get(0)); } } }); } else { TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages(); - req.id.add((int) messageIdFinal); + req.id.add(messageId); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response; if (!messagesRes.messages.isEmpty()) { - saveDraftReplyMessage(did, threadId, messagesRes.messages.get(0)); + saveDraftReplyMessage(dialogId, threadId, messagesRes.messages.get(0)); } } }); } } else { - saveDraftReplyMessage(did, threadId, message); + saveDraftReplyMessage(dialogId, threadId, message); } } catch (Exception e) { FileLog.e(e); @@ -5030,28 +4970,28 @@ public class MediaDataController extends BaseController { }); } } - getNotificationCenter().postNotificationName(NotificationCenter.newDraftReceived, did); + getNotificationCenter().postNotificationName(NotificationCenter.newDraftReceived, dialogId); } } - private void saveDraftReplyMessage(final long did, int threadId, final TLRPC.Message message) { + private void saveDraftReplyMessage(long dialogId, int threadId, TLRPC.Message message) { if (message == null) { return; } AndroidUtilities.runOnUIThread(() -> { - SparseArray threads = drafts.get(did); + SparseArray threads = drafts.get(dialogId); TLRPC.DraftMessage draftMessage = threads != null ? threads.get(threadId) : null; if (draftMessage != null && draftMessage.reply_to_msg_id == message.id) { - SparseArray threads2 = draftMessages.get(did); + SparseArray threads2 = draftMessages.get(dialogId); if (threads2 == null) { threads2 = new SparseArray<>(); - draftMessages.put(did, threads2); + draftMessages.put(dialogId, threads2); } threads2.put(threadId, message); SerializedData serializedData = new SerializedData(message.getObjectSize()); message.serializeToStream(serializedData); - draftPreferences.edit().putString(threadId == 0 ? ("r_" + did) : ("rt_" + did + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())).commit(); - getNotificationCenter().postNotificationName(NotificationCenter.newDraftReceived, did); + draftPreferences.edit().putString(threadId == 0 ? ("r_" + dialogId) : ("rt_" + dialogId + "_" + threadId), Utilities.bytesToHex(serializedData.toByteArray())).commit(); + getNotificationCenter().postNotificationName(NotificationCenter.newDraftReceived, dialogId); serializedData.cleanup(); } }); @@ -5068,42 +5008,42 @@ public class MediaDataController extends BaseController { } } - public void cleanDraft(long did, int threadId, boolean replyOnly) { - SparseArray threads2 = drafts.get(did); + public void cleanDraft(long dialogId, int threadId, boolean replyOnly) { + SparseArray threads2 = drafts.get(dialogId); TLRPC.DraftMessage draftMessage = threads2 != null ? threads2.get(threadId) : null; if (draftMessage == null) { return; } if (!replyOnly) { { - SparseArray threads = drafts.get(did); + SparseArray threads = drafts.get(dialogId); if (threads != null) { threads.remove(threadId); if (threads.size() == 0) { - drafts.remove(did); + drafts.remove(dialogId); } } } { - SparseArray threads = draftMessages.get(did); + SparseArray threads = draftMessages.get(dialogId); if (threads != null) { threads.remove(threadId); if (threads.size() == 0) { - draftMessages.remove(did); + draftMessages.remove(dialogId); } } } if (threadId == 0) { - draftPreferences.edit().remove("" + did).remove("r_" + did).commit(); + draftPreferences.edit().remove("" + dialogId).remove("r_" + dialogId).commit(); getMessagesController().sortDialogs(null); getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); } else { - draftPreferences.edit().remove("t_" + did + "_" + threadId).remove("rt_" + did + "_" + threadId).commit(); + draftPreferences.edit().remove("t_" + dialogId + "_" + threadId).remove("rt_" + dialogId + "_" + threadId).commit(); } } else if (draftMessage.reply_to_msg_id != 0) { draftMessage.reply_to_msg_id = 0; draftMessage.flags &= ~1; - saveDraft(did, threadId, draftMessage.message, draftMessage.entities, null, draftMessage.no_webpage, true); + saveDraft(dialogId, threadId, draftMessage.message, draftMessage.entities, null, draftMessage.no_webpage, true); } } @@ -5121,7 +5061,7 @@ public class MediaDataController extends BaseController { private LongSparseArray botKeyboards = new LongSparseArray<>(); private SparseLongArray botKeyboardsByMids = new SparseLongArray(); - public void clearBotKeyboard(final long did, final ArrayList messages) { + public void clearBotKeyboard(long dialogId, ArrayList messages) { AndroidUtilities.runOnUIThread(() -> { if (messages != null) { for (int a = 0; a < messages.size(); a++) { @@ -5133,22 +5073,22 @@ public class MediaDataController extends BaseController { } } } else { - botKeyboards.remove(did); - getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, null, did); + botKeyboards.remove(dialogId); + getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, null, dialogId); } }); } - public void loadBotKeyboard(final long did) { - TLRPC.Message keyboard = botKeyboards.get(did); + public void loadBotKeyboard(long dialogId) { + TLRPC.Message keyboard = botKeyboards.get(dialogId); if (keyboard != null) { - getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, keyboard, did); + getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, keyboard, dialogId); return; } getMessagesStorage().getStorageQueue().postRunnable(() -> { try { TLRPC.Message botKeyboard = null; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT info FROM bot_keyboard WHERE uid = %d", did)); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT info FROM bot_keyboard WHERE uid = %d", dialogId)); if (cursor.next()) { NativeByteBuffer data; @@ -5163,8 +5103,8 @@ public class MediaDataController extends BaseController { cursor.dispose(); if (botKeyboard != null) { - final TLRPC.Message botKeyboardFinal = botKeyboard; - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, botKeyboardFinal, did)); + TLRPC.Message botKeyboardFinal = botKeyboard; + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, botKeyboardFinal, dialogId)); } } catch (Exception e) { FileLog.e(e); @@ -5172,7 +5112,7 @@ public class MediaDataController extends BaseController { }); } - private TLRPC.BotInfo loadBotInfoInternal(final int uid, final long dialogId) throws SQLiteException { + private TLRPC.BotInfo loadBotInfoInternal(long uid, long dialogId) throws SQLiteException { TLRPC.BotInfo botInfo = null; SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT info FROM bot_info_v2 WHERE uid = %d AND dialogId = %d", uid, dialogId)); if (cursor.next()) { @@ -5190,7 +5130,7 @@ public class MediaDataController extends BaseController { return botInfo; } - public void loadBotInfo(final int uid, final long dialogId, boolean cache, final int classGuid) { + public void loadBotInfo(long uid, long dialogId, boolean cache, int classGuid) { if (cache) { TLRPC.BotInfo botInfo = botInfos.get(uid + "_" + dialogId); if (botInfo != null) { @@ -5202,8 +5142,7 @@ public class MediaDataController extends BaseController { try { TLRPC.BotInfo botInfo = loadBotInfoInternal(uid, dialogId); if (botInfo != null) { - final TLRPC.BotInfo botInfoFinal = botInfo; - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.botInfoDidLoad, botInfoFinal, classGuid)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.botInfoDidLoad, botInfo, classGuid)); } } catch (Exception e) { FileLog.e(e); @@ -5211,13 +5150,13 @@ public class MediaDataController extends BaseController { }); } - public void putBotKeyboard(final long did, final TLRPC.Message message) { + public void putBotKeyboard(long dialogId, TLRPC.Message message) { if (message == null) { return; } try { int mid = 0; - SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT mid FROM bot_keyboard WHERE uid = %d", did)); + SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT mid FROM bot_keyboard WHERE uid = %d", dialogId)); if (cursor.next()) { mid = cursor.intValue(0); } @@ -5230,7 +5169,7 @@ public class MediaDataController extends BaseController { state.requery(); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - state.bindLong(1, did); + state.bindLong(1, dialogId); state.bindInteger(2, message.id); state.bindByteBuffer(3, data); state.step(); @@ -5238,13 +5177,16 @@ public class MediaDataController extends BaseController { state.dispose(); AndroidUtilities.runOnUIThread(() -> { - TLRPC.Message old = botKeyboards.get(did); - botKeyboards.put(did, message); - if (old != null) { - botKeyboardsByMids.delete(old.id); + TLRPC.Message old = botKeyboards.get(dialogId); + botKeyboards.put(dialogId, message); + long channelId = MessageObject.getChannelId(message); + if (channelId == 0) { + if (old != null) { + botKeyboardsByMids.delete(old.id); + } + botKeyboardsByMids.put(message.id, dialogId); } - botKeyboardsByMids.put(message.id, did); - getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, message, did); + getNotificationCenter().postNotificationName(NotificationCenter.botKeyboardDidLoad, message, dialogId); }); } catch (Exception e) { FileLog.e(e); @@ -5262,7 +5204,7 @@ public class MediaDataController extends BaseController { state.requery(); NativeByteBuffer data = new NativeByteBuffer(botInfo.getObjectSize()); botInfo.serializeToStream(data); - state.bindInteger(1, botInfo.user_id); + state.bindLong(1, botInfo.user_id); state.bindLong(2, dialogId); state.bindByteBuffer(3, data); state.step(); @@ -5290,7 +5232,7 @@ public class MediaDataController extends BaseController { state.requery(); NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize()); info.serializeToStream(data); - state.bindInteger(1, info.user_id); + state.bindLong(1, info.user_id); state.bindLong(2, dialogId); state.bindByteBuffer(3, data); state.step(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java index 862b2579a..e21fe0b39 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java @@ -24,7 +24,6 @@ import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.text.util.Linkify; import android.util.Base64; -import android.util.SparseArray; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.browser.Browser; @@ -58,6 +57,8 @@ import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.collection.LongSparseArray; + public class MessageObject { public static final int MESSAGE_SEND_STATE_SENT = 0; @@ -875,11 +876,11 @@ public class MessageObject { localEdit = edit; } - public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, boolean generateLayout, boolean checkMediaExists) { + public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, boolean generateLayout, boolean checkMediaExists) { this(accountNum, message, users, null, generateLayout, checkMediaExists); } - public MessageObject(int accountNum, TLRPC.Message message, SparseArray users, boolean generateLayout, boolean checkMediaExists) { + public MessageObject(int accountNum, TLRPC.Message message, LongSparseArray users, boolean generateLayout, boolean checkMediaExists) { this(accountNum, message, users, null, generateLayout, checkMediaExists); } @@ -891,19 +892,19 @@ public class MessageObject { this(accountNum, message, replyToMessage, null, null, null, null, generateLayout, checkMediaExists, 0); } - public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, AbstractMap chats, boolean generateLayout, boolean checkMediaExists) { + public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, AbstractMap chats, boolean generateLayout, boolean checkMediaExists) { this(accountNum, message, users, chats, generateLayout, checkMediaExists, 0); } - public MessageObject(int accountNum, TLRPC.Message message, SparseArray users, SparseArray chats, boolean generateLayout, boolean checkMediaExists) { + public MessageObject(int accountNum, TLRPC.Message message, LongSparseArray users, LongSparseArray chats, boolean generateLayout, boolean checkMediaExists) { this(accountNum, message, null, null, null, users, chats, generateLayout, checkMediaExists, 0); } - public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, AbstractMap chats, boolean generateLayout, boolean checkMediaExists, long eid) { + public MessageObject(int accountNum, TLRPC.Message message, AbstractMap users, AbstractMap chats, boolean generateLayout, boolean checkMediaExists, long eid) { this(accountNum, message, null, users, chats, null, null, generateLayout, checkMediaExists, eid); } - public MessageObject(int accountNum, TLRPC.Message message, MessageObject replyToMessage, AbstractMap users, AbstractMap chats, SparseArray sUsers, SparseArray sChats, boolean generateLayout, boolean checkMediaExists, long eid) { + public MessageObject(int accountNum, TLRPC.Message message, MessageObject replyToMessage, AbstractMap users, AbstractMap chats, LongSparseArray sUsers, LongSparseArray sChats, boolean generateLayout, boolean checkMediaExists, long eid) { Theme.createCommonMessageResources(); currentAccount = accountNum; @@ -1149,7 +1150,7 @@ public class MessageObject { TLRPC.TL_channelAdminLogEventActionParticipantInvite action = (TLRPC.TL_channelAdminLogEventActionParticipantInvite) event.action; messageOwner = new TLRPC.TL_messageService(); messageOwner.action = new TLRPC.TL_messageActionChatAddUser(); - int peerId = getPeerId(action.participant.peer); + long peerId = getPeerId(action.participant.peer); TLObject whoUser; if (peerId > 0) { whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); @@ -1180,7 +1181,7 @@ public class MessageObject { new_participant = action.new_participant; } messageOwner = new TLRPC.TL_message(); - int peerId = MessageObject.getPeerId(prev_participant.peer); + long peerId = MessageObject.getPeerId(prev_participant.peer); TLObject whoUser; if (peerId > 0) { whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); @@ -1347,7 +1348,7 @@ public class MessageObject { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) { TLRPC.TL_channelAdminLogEventActionParticipantToggleBan action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) event.action; messageOwner = new TLRPC.TL_message(); - int peerId = getPeerId(action.prev_participant.peer); + long peerId = getPeerId(action.prev_participant.peer); TLObject whoUser; if (peerId > 0) { whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); @@ -1534,8 +1535,8 @@ public class MessageObject { message = ((TLRPC.TL_channelAdminLogEventActionDeleteMessage) event.action).message; messageText = replaceWithLink(LocaleController.getString("EventLogDeletedMessages", R.string.EventLogDeletedMessages), "un1", fromUser); } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) { - int newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value; - int oldChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).prev_value; + long newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value; + long oldChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).prev_value; if (chat.megagroup) { if (newChatId == 0) { TLRPC.Chat oldChat = MessagesController.getInstance(currentAccount).getChat(oldChatId); @@ -1749,7 +1750,7 @@ public class MessageObject { } } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantMute) { TLRPC.TL_channelAdminLogEventActionParticipantMute action = (TLRPC.TL_channelAdminLogEventActionParticipantMute) event.action; - int id = getPeerId(action.participant.peer); + long id = getPeerId(action.participant.peer); TLObject object; if (id > 0) { object = MessagesController.getInstance(currentAccount).getUser(id); @@ -1760,7 +1761,7 @@ public class MessageObject { messageText = replaceWithLink(messageText, "un2", object); } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantUnmute) { TLRPC.TL_channelAdminLogEventActionParticipantUnmute action = (TLRPC.TL_channelAdminLogEventActionParticipantUnmute) event.action; - int id = getPeerId(action.participant.peer); + long id = getPeerId(action.participant.peer); TLObject object; if (id > 0) { object = MessagesController.getInstance(currentAccount).getUser(id); @@ -1798,7 +1799,7 @@ public class MessageObject { messageText = replaceWithLink(messageText, "un3", action.new_invite); } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantVolume) { TLRPC.TL_channelAdminLogEventActionParticipantVolume action = (TLRPC.TL_channelAdminLogEventActionParticipantVolume) event.action; - int id = getPeerId(action.participant.peer); + long id = getPeerId(action.participant.peer); TLObject object; if (id > 0) { object = MessagesController.getInstance(currentAccount).getUser(id); @@ -1919,7 +1920,7 @@ public class MessageObject { private String getUserName(TLObject object, ArrayList entities, int offset) { String name; String username; - int id; + long id; if (object == null) { name = ""; username = null; @@ -2021,7 +2022,7 @@ public class MessageObject { public void generatePaymentSentMessageText(TLRPC.User fromUser) { if (fromUser == null) { - fromUser = MessagesController.getInstance(currentAccount).getUser((int) getDialogId()); + fromUser = MessagesController.getInstance(currentAccount).getUser(getDialogId()); } String name; if (fromUser != null) { @@ -2062,7 +2063,7 @@ public class MessageObject { messageText = replaceWithLink(LocaleController.getString("ActionPinnedVoice", R.string.ActionPinnedVoice), "un1", fromUser != null ? fromUser : chat); } else if (replyMessageObject.isRoundVideo()) { messageText = replaceWithLink(LocaleController.getString("ActionPinnedRound", R.string.ActionPinnedRound), "un1", fromUser != null ? fromUser : chat); - } else if (replyMessageObject.isSticker() || replyMessageObject.isAnimatedSticker()) { + } else if ((replyMessageObject.isSticker() || replyMessageObject.isAnimatedSticker()) && !replyMessageObject.isAnimatedEmoji()) { messageText = replaceWithLink(LocaleController.getString("ActionPinnedSticker", R.string.ActionPinnedSticker), "un1", fromUser != null ? fromUser : chat); } else if (replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { messageText = replaceWithLink(LocaleController.getString("ActionPinnedFile", R.string.ActionPinnedFile), "un1", fromUser != null ? fromUser : chat); @@ -2464,33 +2465,33 @@ public class MessageObject { return localType != 0; } - private TLRPC.User getUser(AbstractMap users, SparseArray sUsers, int uid) { + private TLRPC.User getUser(AbstractMap users, LongSparseArray sUsers, long userId) { TLRPC.User user = null; if (users != null) { - user = users.get(uid); + user = users.get(userId); } else if (sUsers != null) { - user = sUsers.get(uid); + user = sUsers.get(userId); } if (user == null) { - user = MessagesController.getInstance(currentAccount).getUser(uid); + user = MessagesController.getInstance(currentAccount).getUser(userId); } return user; } - private TLRPC.Chat getChat(AbstractMap chats, SparseArray sChats, int cid) { + private TLRPC.Chat getChat(AbstractMap chats, LongSparseArray sChats, long chatId) { TLRPC.Chat chat = null; if (chats != null) { - chat = chats.get(cid); + chat = chats.get(chatId); } else if (sChats != null) { - chat = sChats.get(cid); + chat = sChats.get(chatId); } if (chat == null) { - chat = MessagesController.getInstance(currentAccount).getChat(cid); + chat = MessagesController.getInstance(currentAccount).getChat(chatId); } return chat; } - private void updateMessageText(AbstractMap users, AbstractMap chats, SparseArray sUsers, SparseArray sChats) { + private void updateMessageText(AbstractMap users, AbstractMap chats, LongSparseArray sUsers, LongSparseArray sChats) { TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; if (messageOwner.from_id instanceof TLRPC.TL_peerUser) { @@ -2550,7 +2551,7 @@ public class MessageObject { } } } else if (messageOwner.action instanceof TLRPC.TL_messageActionInviteToGroupCall) { - int singleUserId = messageOwner.action.user_id; + long singleUserId = messageOwner.action.user_id; if (singleUserId == 0 && messageOwner.action.users.size() == 1) { singleUserId = messageOwner.action.users.get(0); } @@ -2575,15 +2576,15 @@ public class MessageObject { } } else if (messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { TLRPC.TL_messageActionGeoProximityReached action = (TLRPC.TL_messageActionGeoProximityReached) messageOwner.action; - int fromId = getPeerId(action.from_id); + long fromId = getPeerId(action.from_id); TLObject from; if (fromId > 0) { from = getUser(users, sUsers, fromId); } else { from = getChat(chats, sChats, -fromId); } - int toId = getPeerId(action.to_id); - int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long toId = getPeerId(action.to_id); + long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); if (toId == selfUserId) { messageText = replaceWithLink(LocaleController.formatString("ActionUserWithinRadius", R.string.ActionUserWithinRadius, LocaleController.formatDistance(action.distance, 2)), "un1", from); } else { @@ -2627,7 +2628,7 @@ public class MessageObject { } } } else if (messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { - int singleUserId = messageOwner.action.user_id; + long singleUserId = messageOwner.action.user_id; if (singleUserId == 0 && messageOwner.action.users.size() == 1) { singleUserId = messageOwner.action.users.get(0); } @@ -2895,7 +2896,7 @@ public class MessageObject { } } } else if (messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent) { - TLRPC.User user = getUser(users, sUsers, (int) getDialogId()); + TLRPC.User user = getUser(users, sUsers, getDialogId()); generatePaymentSentMessageText(user); } else if (messageOwner.action instanceof TLRPC.TL_messageActionBotAllowed) { String domain = ((TLRPC.TL_messageActionBotAllowed) messageOwner.action).domain; @@ -2947,6 +2948,19 @@ public class MessageObject { user = getUser(users, sUsers, messageOwner.peer_id.user_id); } messageText = LocaleController.formatString("ActionBotDocuments", R.string.ActionBotDocuments, UserObject.getFirstName(user), str.toString()); + } else if (messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + String emoticon = ((TLRPC.TL_messageActionSetChatTheme) messageOwner.action).emoticon; + String userName = UserObject.getFirstName(fromUser); + boolean isUserSelf = UserObject.isUserSelf(fromUser); + if (TextUtils.isEmpty(emoticon)) { + messageText = isUserSelf + ? LocaleController.formatString("ChatThemeDisabledYou", R.string.ChatThemeDisabledYou) + : LocaleController.formatString("ChatThemeDisabled", R.string.ChatThemeDisabled, userName, emoticon); + } else { + messageText = isUserSelf + ? LocaleController.formatString("ChangedChatThemeYou", R.string.ChatThemeChangedYou, emoticon) + : LocaleController.formatString("ChangedChatThemeTo", R.string.ChatThemeChangedTo, userName, emoticon); + } } } } else { @@ -3466,7 +3480,7 @@ public class MessageObject { } } - public CharSequence replaceWithLink(CharSequence source, String param, ArrayList uids, AbstractMap usersDict, SparseArray sUsersDict) { + public CharSequence replaceWithLink(CharSequence source, String param, ArrayList uids, AbstractMap usersDict, LongSparseArray sUsersDict) { int start = TextUtils.indexOf(source, param); if (start >= 0) { SpannableStringBuilder names = new SpannableStringBuilder(""); @@ -4518,7 +4532,7 @@ public class MessageObject { if (messageOwner.fwd_from == null) { return true; } - int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); if (getDialogId() == selfUserId) { return messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerUser && messageOwner.fwd_from.from_id.user_id == selfUserId && (messageOwner.fwd_from.saved_from_peer == null || messageOwner.fwd_from.saved_from_peer.user_id == selfUserId) || messageOwner.fwd_from.saved_from_peer != null && messageOwner.fwd_from.saved_from_peer.user_id == selfUserId && (messageOwner.fwd_from.from_id == null || messageOwner.fwd_from.from_id.user_id == selfUserId); @@ -4548,11 +4562,11 @@ public class MessageObject { return false; } - public static int getFromChatId(TLRPC.Message message) { + public static long getFromChatId(TLRPC.Message message) { return getPeerId(message.from_id); } - public static int getPeerId(TLRPC.Peer peer) { + public static long getPeerId(TLRPC.Peer peer) { if (peer == null) { return 0; } @@ -4565,11 +4579,11 @@ public class MessageObject { } } - public int getFromChatId() { + public long getFromChatId() { return getFromChatId(messageOwner); } - public int getChatId() { + public long getChatId() { if (messageOwner.peer_id instanceof TLRPC.TL_peerChat) { return messageOwner.peer_id.chat_id; } else if (messageOwner.peer_id instanceof TLRPC.TL_peerChannel) { @@ -4649,11 +4663,7 @@ public class MessageObject { return getMessageSize(messageOwner); } - public long getIdWithChannel() { - return getIdWithChannel(messageOwner); - } - - public static void fixMessagePeer(ArrayList messages, int channelId) { + public static void fixMessagePeer(ArrayList messages, long channelId) { if (messages == null || messages.isEmpty() || channelId == 0) { return; } @@ -4666,17 +4676,13 @@ public class MessageObject { } } - public static long getIdWithChannel(TLRPC.Message message) { - long id = message.id; - if (message.peer_id != null && message.peer_id.channel_id != 0) { - id |= ((long) message.peer_id.channel_id) << 32; - } - return id; + public long getChannelId() { + return getChannelId(messageOwner); } - public int getChannelId() { - if (messageOwner.peer_id != null) { - return messageOwner.peer_id.channel_id; + public static long getChannelId(TLRPC.Message message) { + if (message.peer_id != null) { + return message.peer_id.channel_id; } return 0; } @@ -5009,7 +5015,7 @@ public class MessageObject { } public static boolean isAnimatedStickerMessage(TLRPC.Message message) { - boolean isSecretChat = DialogObject.isSecretDialogId(message.dialog_id); + boolean isSecretChat = DialogObject.isEncryptedDialog(message.dialog_id); if (isSecretChat && message.stickerVerified != 1) { return false; } @@ -5201,7 +5207,7 @@ public class MessageObject { } if (photoHeight > maxHeight) { photoWidth *= maxHeight / photoHeight; - photoHeight = (int)maxHeight; + photoHeight = (int) maxHeight; } if (photoWidth > maxWidth) { photoHeight *= maxWidth / photoWidth; @@ -5308,7 +5314,7 @@ public class MessageObject { if (type != 1000) { return type == TYPE_ANIMATED_STICKER; } - boolean isSecretChat = DialogObject.isSecretDialogId(getDialogId()); + boolean isSecretChat = DialogObject.isEncryptedDialog(getDialogId()); if (isSecretChat && messageOwner.stickerVerified != 1) { return false; } @@ -5638,7 +5644,7 @@ public class MessageObject { return messageOwner.replies != null && messageOwner.replies.comments; } - public boolean isLinkedToChat(int chatId) { + public boolean isLinkedToChat(long chatId) { return messageOwner.replies != null && (chatId == 0 || messageOwner.replies.channel_id == chatId); } @@ -5820,6 +5826,16 @@ public class MessageObject { return messageOwner.reply_to != null ? messageOwner.reply_to.reply_to_top_id : 0; } + public static long getReplyToDialogId(TLRPC.Message message) { + if (message.reply_to == null) { + return 0; + } + if (message.reply_to.reply_to_peer_id != null) { + return getPeerId(message.reply_to.reply_to_peer_id); + } + return MessageObject.getDialogId(message); + } + public int getReplyAnyMsgId() { if (messageOwner.reply_to != null) { if (messageOwner.reply_to.reply_to_top_id != 0) { @@ -5839,7 +5855,7 @@ public class MessageObject { return messageOwner.fwd_from != null && messageOwner.fwd_from.imported; } - public int getSenderId() { + public long getSenderId() { if (messageOwner.fwd_from != null && messageOwner.fwd_from.saved_from_peer != null) { if (messageOwner.fwd_from.saved_from_peer.user_id != 0) { if (messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerUser) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java index 33f96003a..d23f05417 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java @@ -21,15 +21,17 @@ import android.os.SystemClock; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Base64; -import android.util.LongSparseArray; +import android.util.Log; import android.util.SparseArray; import android.util.SparseBooleanArray; import android.util.SparseIntArray; +import androidx.collection.LongSparseArray; import androidx.core.app.NotificationManagerCompat; import org.telegram.SQLite.SQLiteCursor; -import org.telegram.messenger.support.SparseLongArray; +import org.telegram.messenger.support.LongSparseIntArray; +import org.telegram.messenger.support.LongSparseLongArray; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.NativeByteBuffer; @@ -49,7 +51,7 @@ import org.telegram.ui.DialogsActivity; import org.telegram.ui.EditWidgetActivity; import org.telegram.ui.LaunchActivity; import org.telegram.ui.ProfileActivity; -import org.telegram.ui.SwipeGestureSettingsView; +import org.telegram.ui.Components.SwipeGestureSettingsView; import java.io.File; import java.util.ArrayList; @@ -66,16 +68,16 @@ import java.util.concurrent.CountDownLatch; public class MessagesController extends BaseController implements NotificationCenter.NotificationCenterDelegate { - private ConcurrentHashMap chats = new ConcurrentHashMap<>(100, 1.0f, 2); + private ConcurrentHashMap chats = new ConcurrentHashMap<>(100, 1.0f, 2); private ConcurrentHashMap encryptedChats = new ConcurrentHashMap<>(10, 1.0f, 2); - private ConcurrentHashMap users = new ConcurrentHashMap<>(100, 1.0f, 2); + private ConcurrentHashMap users = new ConcurrentHashMap<>(100, 1.0f, 2); private ConcurrentHashMap objectsByUsernames = new ConcurrentHashMap<>(100, 1.0f, 2); - private HashMap activeVoiceChatsMap = new HashMap<>(); + private HashMap activeVoiceChatsMap = new HashMap<>(); - private ArrayList joiningToChannels = new ArrayList<>(); + private ArrayList joiningToChannels = new ArrayList<>(); - private SparseArray exportedChats = new SparseArray<>(); + private LongSparseArray exportedChats = new LongSparseArray<>(); public ArrayList hintDialogs = new ArrayList<>(); public SparseArray> dialogsByFolder = new SparseArray<>(); @@ -95,13 +97,13 @@ public class MessagesController extends BaseController implements NotificationCe public LongSparseArray dialogs_dict = new LongSparseArray<>(); public LongSparseArray dialogMessage = new LongSparseArray<>(); public LongSparseArray dialogMessagesByRandomIds = new LongSparseArray<>(); - public LongSparseArray deletedHistory = new LongSparseArray<>(); + public LongSparseIntArray deletedHistory = new LongSparseIntArray(); public SparseArray dialogMessagesByIds = new SparseArray<>(); public ConcurrentHashMap>> printingUsers = new ConcurrentHashMap<>(20, 1.0f, 2); public LongSparseArray> printingStrings = new LongSparseArray<>(); public LongSparseArray> printingStringsTypes = new LongSparseArray<>(); - public LongSparseArray>[] sendingTypings = new LongSparseArray[11]; - public ConcurrentHashMap onlinePrivacy = new ConcurrentHashMap<>(20, 1.0f, 2); + public LongSparseArray>[] sendingTypings = new LongSparseArray[12]; + public ConcurrentHashMap onlinePrivacy = new ConcurrentHashMap<>(20, 1.0f, 2); private int lastPrintingStringCount; private boolean dialogsInTransaction; @@ -114,20 +116,20 @@ public class MessagesController extends BaseController implements NotificationCe private ArrayList visibleDialogMainThreadIds = new ArrayList<>(); private ArrayList visibleScheduledDialogMainThreadIds = new ArrayList<>(); - private SparseIntArray shortPollChannels = new SparseIntArray(); - private SparseArray> needShortPollChannels = new SparseArray<>(); - private SparseIntArray shortPollOnlines = new SparseIntArray(); - private SparseArray> needShortPollOnlines = new SparseArray<>(); + private LongSparseIntArray shortPollChannels = new LongSparseIntArray(); + private LongSparseArray> needShortPollChannels = new LongSparseArray<>(); + private LongSparseIntArray shortPollOnlines = new LongSparseIntArray(); + private LongSparseArray> needShortPollOnlines = new LongSparseArray<>(); private LongSparseArray deletingDialogs = new LongSparseArray<>(); private LongSparseArray clearingHistoryDialogs = new LongSparseArray<>(); public boolean loadingBlockedPeers = false; - public SparseIntArray blockePeers = new SparseIntArray(); + public LongSparseIntArray blockePeers = new LongSparseIntArray(); public int totalBlockedCount = -1; public boolean blockedEndReached; - private SparseArray> channelViewsToSend = new SparseArray<>(); + private LongSparseArray> channelViewsToSend = new LongSparseArray<>(); private LongSparseArray> pollsToCheck = new LongSparseArray<>(); private int pollsToCheckSize; private long lastViewsCheckTime; @@ -139,15 +141,15 @@ public class MessagesController extends BaseController implements NotificationCe public boolean dialogFiltersLoaded; public ArrayList suggestedFilters = new ArrayList<>(); - private SparseArray> updatesQueueChannels = new SparseArray<>(); - private SparseLongArray updatesStartWaitTimeChannels = new SparseLongArray(); - private SparseIntArray channelsPts = new SparseIntArray(); - private SparseBooleanArray gettingDifferenceChannels = new SparseBooleanArray(); - private SparseBooleanArray gettingChatInviters = new SparseBooleanArray(); + private LongSparseArray> updatesQueueChannels = new LongSparseArray<>(); + private LongSparseLongArray updatesStartWaitTimeChannels = new LongSparseLongArray(); + private LongSparseIntArray channelsPts = new LongSparseIntArray(); + private LongSparseArray gettingDifferenceChannels = new LongSparseArray<>(); + private LongSparseArray gettingChatInviters = new LongSparseArray<>(); - private SparseBooleanArray gettingUnknownChannels = new SparseBooleanArray(); + private LongSparseArray gettingUnknownChannels = new LongSparseArray<>(); private LongSparseArray gettingUnknownDialogs = new LongSparseArray<>(); - private SparseBooleanArray checkingLastMessagesDialogs = new SparseBooleanArray(); + private LongSparseArray checkingLastMessagesDialogs = new LongSparseArray<>(); private ArrayList updatesQueueSeq = new ArrayList<>(); private ArrayList updatesQueuePts = new ArrayList<>(); @@ -155,19 +157,19 @@ public class MessagesController extends BaseController implements NotificationCe private long updatesStartWaitTimeSeq; private long updatesStartWaitTimePts; private long updatesStartWaitTimeQts; - private SparseArray fullUsers = new SparseArray<>(); - private SparseArray fullChats = new SparseArray<>(); + private LongSparseArray fullUsers = new LongSparseArray<>(); + private LongSparseArray fullChats = new LongSparseArray<>(); private LongSparseArray groupCalls = new LongSparseArray<>(); - private SparseArray groupCallsByChatId = new SparseArray<>(); - private ArrayList loadingFullUsers = new ArrayList<>(); - private ArrayList loadedFullUsers = new ArrayList<>(); - private ArrayList loadingFullChats = new ArrayList<>(); - private ArrayList loadingGroupCalls = new ArrayList<>(); - private ArrayList loadingFullParticipants = new ArrayList<>(); - private ArrayList loadedFullParticipants = new ArrayList<>(); - private ArrayList loadedFullChats = new ArrayList<>(); - private SparseArray> channelAdmins = new SparseArray<>(); - private SparseIntArray loadingChannelAdmins = new SparseIntArray(); + private LongSparseArray groupCallsByChatId = new LongSparseArray<>(); + private ArrayList loadingFullUsers = new ArrayList<>(); + private ArrayList loadedFullUsers = new ArrayList<>(); + private ArrayList loadingFullChats = new ArrayList<>(); + private ArrayList loadingGroupCalls = new ArrayList<>(); + private ArrayList loadingFullParticipants = new ArrayList<>(); + private ArrayList loadedFullParticipants = new ArrayList<>(); + private ArrayList loadedFullChats = new ArrayList<>(); + private LongSparseArray> channelAdmins = new LongSparseArray<>(); + private LongSparseIntArray loadingChannelAdmins = new LongSparseIntArray(); private SparseIntArray migratedChats = new SparseIntArray(); @@ -186,13 +188,12 @@ public class MessagesController extends BaseController implements NotificationCe private ArrayList readTasks = new ArrayList<>(); private LongSparseArray readTasksMap = new LongSparseArray<>(); private ArrayList repliesReadTasks = new ArrayList<>(); - private LongSparseArray threadsReadTasksMap = new LongSparseArray<>(); + private HashMap threadsReadTasksMap = new HashMap<>(); private boolean gettingNewDeleteTask; private int currentDeletingTaskTime; - private ArrayList currentDeletingTaskMids; - private boolean currentDeletingTaskMedia; - private int currentDeletingTaskChannelId; + private LongSparseArray> currentDeletingTaskMids; + private LongSparseArray> currentDeletingTaskMediaMids; private Runnable currentDeleteTaskRunnable; public boolean dialogsLoaded; @@ -317,6 +318,7 @@ public class MessagesController extends BaseController implements NotificationCe public String autologinToken; public HashMap diceSuccess = new HashMap<>(); public HashMap emojiSounds = new HashMap<>(); + public HashMap> emojiInteractions = new HashMap<>(); private SharedPreferences notificationsPreferences; private SharedPreferences mainPreferences; @@ -428,29 +430,30 @@ public class MessagesController extends BaseController implements NotificationCe } - public static final int UPDATE_MASK_NAME = 1; - public static final int UPDATE_MASK_AVATAR = 2; - public static final int UPDATE_MASK_STATUS = 4; - public static final int UPDATE_MASK_CHAT_AVATAR = 8; - public static final int UPDATE_MASK_CHAT_NAME = 16; - public static final int UPDATE_MASK_CHAT_MEMBERS = 32; - public static final int UPDATE_MASK_USER_PRINT = 64; - public static final int UPDATE_MASK_USER_PHONE = 128; - public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256; - public static final int UPDATE_MASK_SELECT_DIALOG = 512; - public static final int UPDATE_MASK_PHONE = 1024; - public static final int UPDATE_MASK_NEW_MESSAGE = 2048; - public static final int UPDATE_MASK_SEND_STATE = 4096; - public static final int UPDATE_MASK_CHAT = 8192; - //public static final int UPDATE_MASK_CHAT_ADMINS = 16384; - public static final int UPDATE_MASK_MESSAGE_TEXT = 32768; - public static final int UPDATE_MASK_CHECK = 65536; - public static final int UPDATE_MASK_REORDER = 131072; - public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE; + public static int UPDATE_MASK_NAME = 1; + public static int UPDATE_MASK_AVATAR = 2; + public static int UPDATE_MASK_STATUS = 4; + public static int UPDATE_MASK_CHAT_AVATAR = 8; + public static int UPDATE_MASK_CHAT_NAME = 16; + public static int UPDATE_MASK_CHAT_MEMBERS = 32; + public static int UPDATE_MASK_USER_PRINT = 64; + public static int UPDATE_MASK_USER_PHONE = 128; + public static int UPDATE_MASK_READ_DIALOG_MESSAGE = 256; + public static int UPDATE_MASK_SELECT_DIALOG = 512; + public static int UPDATE_MASK_PHONE = 1024; + public static int UPDATE_MASK_NEW_MESSAGE = 2048; + public static int UPDATE_MASK_SEND_STATE = 4096; + public static int UPDATE_MASK_CHAT = 8192; + //public static int UPDATE_MASK_CHAT_ADMINS = 16384; + public static int UPDATE_MASK_MESSAGE_TEXT = 32768; + public static int UPDATE_MASK_CHECK = 65536; + public static int UPDATE_MASK_REORDER = 131072; + public static int UPDATE_MASK_EMOJI_INTERACTIONS = 262144; + public static int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE; - public static final int PROMO_TYPE_PROXY = 0; - public static final int PROMO_TYPE_PSA = 1; - public static final int PROMO_TYPE_OTHER = 2; + public static int PROMO_TYPE_PROXY = 0; + public static int PROMO_TYPE_PSA = 1; + public static int PROMO_TYPE_OTHER = 2; private static class ReadTask { public long dialogId; @@ -462,7 +465,7 @@ public class MessagesController extends BaseController implements NotificationCe public static class PrintingUser { public long lastTime; - public int userId; + public long userId; public TLRPC.SendMessageAction action; } @@ -484,28 +487,28 @@ public class MessagesController extends BaseController implements NotificationCe public volatile int pendingUnreadCount; public int order; public int flags; - public ArrayList alwaysShow = new ArrayList<>(); - public ArrayList neverShow = new ArrayList<>(); - public LongSparseArray pinnedDialogs = new LongSparseArray<>(); + public ArrayList alwaysShow = new ArrayList<>(); + public ArrayList neverShow = new ArrayList<>(); + public LongSparseIntArray pinnedDialogs = new LongSparseIntArray(); public ArrayList dialogs = new ArrayList<>(); private static int dialogFilterPointer = 10; public int localId = dialogFilterPointer++; - public boolean includesDialog(AccountInstance accountInstance, int lowerId) { + public boolean includesDialog(AccountInstance accountInstance, long dialogId) { MessagesController messagesController = accountInstance.getMessagesController(); - TLRPC.Dialog dialog = messagesController.dialogs_dict.get(lowerId); + TLRPC.Dialog dialog = messagesController.dialogs_dict.get(dialogId); if (dialog == null) { return false; } - return includesDialog(accountInstance, lowerId, dialog); + return includesDialog(accountInstance, dialogId, dialog); } - public boolean includesDialog(AccountInstance accountInstance, int lowerId, TLRPC.Dialog d) { - if (neverShow.contains(lowerId)) { + public boolean includesDialog(AccountInstance accountInstance, long dialogId, TLRPC.Dialog d) { + if (neverShow.contains(dialogId)) { return false; } - if (alwaysShow.contains(lowerId)) { + if (alwaysShow.contains(dialogId)) { return true; } if (d.folder_id != 0 && (flags & DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0) { @@ -518,11 +521,11 @@ public class MessagesController extends BaseController implements NotificationCe (flags & DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0 && d.unread_count == 0 && !d.unread_mark && d.unread_mentions_count == 0) { return false; } - if (lowerId > 0) { - TLRPC.User user = messagesController.getUser(lowerId); + if (dialogId > 0) { + TLRPC.User user = messagesController.getUser(dialogId); if (user != null) { if (!user.bot) { - if (user.self || user.contact || contactsController.isContact(lowerId)) { + if (user.self || user.contact || contactsController.isContact(dialogId)) { if ((flags & DIALOG_FILTER_FLAG_CONTACTS) != 0) { return true; } @@ -537,8 +540,8 @@ public class MessagesController extends BaseController implements NotificationCe } } } - } else if (lowerId < 0) { - TLRPC.Chat chat = messagesController.getChat(-lowerId); + } else if (dialogId < 0) { + TLRPC.Chat chat = messagesController.getChat(-dialogId); if (chat != null) { if (ChatObject.isChannel(chat) && !chat.megagroup) { if ((flags & DIALOG_FILTER_FLAG_CHANNELS) != 0) { @@ -559,22 +562,21 @@ public class MessagesController extends BaseController implements NotificationCe return false; } - int lower_id = (int) dialog.id; - int high_id = (int) (dialog.id >> 32); + long dialogId = dialog.id; - if (lower_id == 0) { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialog.id)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (encryptedChat != null) { - lower_id = encryptedChat.user_id; + dialogId = encryptedChat.user_id; } } - return alwaysShow.contains(lower_id); + return alwaysShow.contains(dialogId); } } private DialogFilter sortingDialogFilter; - private final Comparator dialogDateComparator = (dialog1, dialog2) -> { + private Comparator dialogDateComparator = (dialog1, dialog2) -> { int pinnedNum1 = sortingDialogFilter.pinnedDialogs.get(dialog1.id, Integer.MIN_VALUE); int pinnedNum2 = sortingDialogFilter.pinnedDialogs.get(dialog2.id, Integer.MIN_VALUE); if (dialog1 instanceof TLRPC.TL_dialogFolder && !(dialog2 instanceof TLRPC.TL_dialogFolder)) { @@ -594,9 +596,9 @@ public class MessagesController extends BaseController implements NotificationCe return 0; } } - final MediaDataController mediaDataController = getMediaDataController(); - final long date1 = DialogObject.getLastMessageOrDraftDate(dialog1, mediaDataController.getDraft(dialog1.id, 0)); - final long date2 = DialogObject.getLastMessageOrDraftDate(dialog2, mediaDataController.getDraft(dialog2.id, 0)); + MediaDataController mediaDataController = getMediaDataController(); + long date1 = DialogObject.getLastMessageOrDraftDate(dialog1, mediaDataController.getDraft(dialog1.id, 0)); + long date2 = DialogObject.getLastMessageOrDraftDate(dialog2, mediaDataController.getDraft(dialog2.id, 0)); if (date1 < date2) { return 1; } else if (date1 > date2) { @@ -605,7 +607,7 @@ public class MessagesController extends BaseController implements NotificationCe return 0; }; - private final Comparator dialogComparator = (dialog1, dialog2) -> { + private Comparator dialogComparator = (dialog1, dialog2) -> { if (dialog1 instanceof TLRPC.TL_dialogFolder && !(dialog2 instanceof TLRPC.TL_dialogFolder)) { return -1; } else if (!(dialog1 instanceof TLRPC.TL_dialogFolder) && dialog2 instanceof TLRPC.TL_dialogFolder) { @@ -623,9 +625,9 @@ public class MessagesController extends BaseController implements NotificationCe return 0; } } - final MediaDataController mediaDataController = getMediaDataController(); - final long date1 = DialogObject.getLastMessageOrDraftDate(dialog1, mediaDataController.getDraft(dialog1.id, 0)); - final long date2 = DialogObject.getLastMessageOrDraftDate(dialog2, mediaDataController.getDraft(dialog2.id, 0)); + MediaDataController mediaDataController = getMediaDataController(); + long date1 = DialogObject.getLastMessageOrDraftDate(dialog1, mediaDataController.getDraft(dialog1.id, 0)); + long date2 = DialogObject.getLastMessageOrDraftDate(dialog2, mediaDataController.getDraft(dialog2.id, 0)); if (date1 < date2) { return 1; } else if (date1 > date2) { @@ -634,7 +636,7 @@ public class MessagesController extends BaseController implements NotificationCe return 0; }; - private final Comparator updatesComparator = (lhs, rhs) -> { + private Comparator updatesComparator = (lhs, rhs) -> { int ltype = getUpdateType(lhs); int rtype = getUpdateType(rhs); if (ltype != rtype) { @@ -644,8 +646,8 @@ public class MessagesController extends BaseController implements NotificationCe } else if (ltype == 1) { return AndroidUtilities.compare(getUpdateQts(lhs), getUpdateQts(rhs)); } else if (ltype == 2) { - int lChannel = getUpdateChannelId(lhs); - int rChannel = getUpdateChannelId(rhs); + long lChannel = getUpdateChannelId(lhs); + long rChannel = getUpdateChannelId(rhs); if (lChannel == rChannel) { return AndroidUtilities.compare(getUpdatePts(lhs), getUpdatePts(rhs)); } else { @@ -897,7 +899,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - private void sendLoadPeersRequest(TLObject req, ArrayList requests, TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { + private void sendLoadPeersRequest(TLObject req, ArrayList requests, TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_messages_chats) { TLRPC.TL_messages_chats res = (TLRPC.TL_messages_chats) response; @@ -924,11 +926,11 @@ public class MessagesController extends BaseController implements NotificationCe }); } - protected void loadFilterPeers(HashMap dialogsToLoadMap, HashMap usersToLoadMap, HashMap chatsToLoadMap, TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { + protected void loadFilterPeers(HashMap dialogsToLoadMap, HashMap usersToLoadMap, HashMap chatsToLoadMap, TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { Utilities.stageQueue.postRunnable(() -> { ArrayList requests = new ArrayList<>(); TLRPC.TL_users_getUsers req = null; - for (HashMap.Entry entry : usersToLoadMap.entrySet()) { + for (HashMap.Entry entry : usersToLoadMap.entrySet()) { if (req == null) { req = new TLRPC.TL_users_getUsers(); requests.add(req); @@ -944,7 +946,7 @@ public class MessagesController extends BaseController implements NotificationCe } TLRPC.TL_messages_getChats req2 = null; TLRPC.TL_channels_getChannels req3 = null; - for (HashMap.Entry entry : chatsToLoadMap.entrySet()) { + for (HashMap.Entry entry : chatsToLoadMap.entrySet()) { TLRPC.InputPeer inputPeer = entry.getValue(); if (inputPeer.chat_id != 0) { if (req2 == null) { @@ -976,7 +978,7 @@ public class MessagesController extends BaseController implements NotificationCe } TLRPC.TL_messages_getPeerDialogs req4 = null; - for (HashMap.Entry entry : dialogsToLoadMap.entrySet()) { + for (HashMap.Entry entry : dialogsToLoadMap.entrySet()) { if (req4 == null) { req4 = new TLRPC.TL_messages_getPeerDialogs(); requests.add(req4); @@ -998,11 +1000,11 @@ public class MessagesController extends BaseController implements NotificationCe protected void processLoadedDialogFilters(ArrayList filters, TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList encryptedChats, int remote) { Utilities.stageQueue.postRunnable(() -> { - final LongSparseArray new_dialogs_dict = new LongSparseArray<>(); - final SparseArray enc_chats_dict; - final LongSparseArray new_dialogMessage = new LongSparseArray<>(); - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray new_dialogs_dict = new LongSparseArray<>(); + SparseArray enc_chats_dict; + LongSparseArray new_dialogMessage = new LongSparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < pinnedDialogs.users.size(); a++) { TLRPC.User u = pinnedDialogs.users.get(a); @@ -1045,10 +1047,8 @@ public class MessagesController extends BaseController implements NotificationCe if (d.id == 0) { continue; } - int lower_id = (int) d.id; - int high_id = (int) (d.id >> 32); - if (lower_id == 0 && enc_chats_dict != null) { - if (enc_chats_dict.get(high_id) == null) { + if (DialogObject.isEncryptedDialog(d.id) && enc_chats_dict != null) { + if (enc_chats_dict.get(DialogObject.getEncryptedChatId(d.id)) == null) { continue; } } @@ -1062,15 +1062,15 @@ public class MessagesController extends BaseController implements NotificationCe } } if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null) { if (chat.left && (promoDialogId == 0 || promoDialogId != d.id)) { continue; } } - channelsPts.put(-(int) d.id, d.pts); - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + channelsPts.put(-d.id, d.pts); + } else if (d.id < 0) { + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.migrated_to != null) { continue; } @@ -1850,7 +1850,7 @@ public class MessagesController extends BaseController implements NotificationCe if (did == 0) { req.peer = new TLRPC.TL_inputPeerEmpty(); } else { - req.peer = getInputPeer((int) did); + req.peer = getInputPeer(did); } getConnectionsManager().sendRequest(req, (response, error) -> { @@ -2041,9 +2041,8 @@ public class MessagesController extends BaseController implements NotificationCe return inputUser; } - public TLRPC.InputUser getInputUser(int user_id) { - TLRPC.User user = getInstance(UserConfig.selectedAccount).getUser(user_id); - return getInputUser(user); + public TLRPC.InputUser getInputUser(long userId) { + return getInputUser(getUser(userId)); } public static TLRPC.InputChannel getInputChannel(TLRPC.Chat chat) { @@ -2064,7 +2063,7 @@ public class MessagesController extends BaseController implements NotificationCe return inputChat; } - public TLRPC.InputChannel getInputChannel(int chatId) { + public TLRPC.InputChannel getInputChannel(long chatId) { return getInputChannel(getChat(chatId)); } @@ -2091,7 +2090,7 @@ public class MessagesController extends BaseController implements NotificationCe return inputPeer; } - public TLRPC.InputPeer getInputPeer(int id) { + public TLRPC.InputPeer getInputPeer(long id) { TLRPC.InputPeer inputPeer; if (id < 0) { TLRPC.Chat chat = getChat(-id); @@ -2134,7 +2133,7 @@ public class MessagesController extends BaseController implements NotificationCe return inputPeer; } - public TLRPC.Peer getPeer(int id) { + public TLRPC.Peer getPeer(long id) { TLRPC.Peer inputPeer; if (id < 0) { TLRPC.Chat chat = getChat(-id); @@ -2156,8 +2155,8 @@ public class MessagesController extends BaseController implements NotificationCe @Override public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.fileUploaded) { - final String location = (String) args[0]; - final TLRPC.InputFile file = (TLRPC.InputFile) args[1]; + String location = (String) args[0]; + TLRPC.InputFile file = (TLRPC.InputFile) args[1]; if (uploadingAvatar != null && uploadingAvatar.equals(location)) { TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto(); @@ -2203,7 +2202,7 @@ public class MessagesController extends BaseController implements NotificationCe req.file = file; req.mime_type = "image/jpeg"; Theme.OverrideWallpaperInfo overrideWallpaperInfo = uploadingWallpaperInfo; - final TLRPC.TL_wallPaperSettings settings = new TLRPC.TL_wallPaperSettings(); + TLRPC.TL_wallPaperSettings settings = new TLRPC.TL_wallPaperSettings(); settings.blur = overrideWallpaperInfo.isBlurred; settings.motion = overrideWallpaperInfo.isMotion; req.settings = settings; @@ -2294,6 +2293,10 @@ public class MessagesController extends BaseController implements NotificationCe settings = new TLRPC.TL_inputThemeSettings(); settings.base_theme = Theme.getBaseThemeByKey(themeInfo.name); settings.accent_color = accent.accentColor; + if (accent.accentColor2 != 0) { + settings.flags |= 8; + settings.outbox_accent_color = accent.accentColor2; + } if (accent.myMessagesAccentColor != 0) { settings.message_colors.add(accent.myMessagesAccentColor); settings.flags |= 1; @@ -2412,7 +2415,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } else if (id == NotificationCenter.fileUploadFailed) { - final String location = (String) args[0]; + String location = (String) args[0]; if (uploadingAvatar != null && uploadingAvatar.equals(location)) { uploadingAvatar = null; } else if (uploadingWallpaper != null && uploadingWallpaper.equals(location)) { @@ -2454,10 +2457,9 @@ public class MessagesController extends BaseController implements NotificationCe dialogMessagesByIds.remove(msgId); dialogMessagesByIds.put(newMsgId, obj); } - int lowerId = (int) (long) did; - if (lowerId < 0) { - TLRPC.ChatFull chatFull = fullChats.get(-lowerId); - TLRPC.Chat chat = getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.ChatFull chatFull = fullChats.get(-did); + TLRPC.Chat chat = getChat(-did); if (chat != null && !ChatObject.hasAdminRights(chat) && chatFull != null && chatFull.slowmode_seconds != 0) { chatFull.slowmode_next_send_date = getConnectionsManager().getCurrentTime() + chatFull.slowmode_seconds; chatFull.flags |= 262144; @@ -2657,8 +2659,7 @@ public class MessagesController extends BaseController implements NotificationCe currentDeletingTaskTime = 0; currentDeletingTaskMids = null; - currentDeletingTaskMedia = false; - currentDeletingTaskChannelId = 0; + currentDeletingTaskMediaMids = null; gettingNewDeleteTask = false; loadingBlockedPeers = false; totalBlockedCount = -1; @@ -2701,7 +2702,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); } - public TLRPC.User getUser(Integer id) { + public TLRPC.User getUser(Long id) { return users.get(id); } @@ -2712,15 +2713,15 @@ public class MessagesController extends BaseController implements NotificationCe return objectsByUsernames.get(username.toLowerCase()); } - public ConcurrentHashMap getUsers() { + public ConcurrentHashMap getUsers() { return users; } - public ConcurrentHashMap getChats() { + public ConcurrentHashMap getChats() { return chats; } - public TLRPC.Chat getChat(Integer id) { + public TLRPC.Chat getChat(Long id) { return chats.get(id); } @@ -2728,12 +2729,12 @@ public class MessagesController extends BaseController implements NotificationCe return encryptedChats.get(id); } - public TLRPC.EncryptedChat getEncryptedChatDB(int chat_id, boolean created) { - TLRPC.EncryptedChat chat = encryptedChats.get(chat_id); + public TLRPC.EncryptedChat getEncryptedChatDB(int chatId, boolean created) { + TLRPC.EncryptedChat chat = encryptedChats.get(chatId); if (chat == null || created && (chat instanceof TLRPC.TL_encryptedChatWaiting || chat instanceof TLRPC.TL_encryptedChatRequested)) { CountDownLatch countDownLatch = new CountDownLatch(1); ArrayList result = new ArrayList<>(); - getMessagesStorage().getEncryptedChat(chat_id, countDownLatch, result); + getMessagesStorage().getEncryptedChat(chatId, countDownLatch, result); try { countDownLatch.await(); } catch (Exception e) { @@ -2749,23 +2750,23 @@ public class MessagesController extends BaseController implements NotificationCe return chat; } - public boolean isDialogVisible(long dialog_id, boolean scheduled) { - return scheduled ? visibleScheduledDialogMainThreadIds.contains(dialog_id) : visibleDialogMainThreadIds.contains(dialog_id); + public boolean isDialogVisible(long dialogId, boolean scheduled) { + return scheduled ? visibleScheduledDialogMainThreadIds.contains(dialogId) : visibleDialogMainThreadIds.contains(dialogId); } - public void setLastVisibleDialogId(final long dialog_id, boolean scheduled, final boolean set) { + public void setLastVisibleDialogId(final long dialogId, boolean scheduled, boolean set) { ArrayList arrayList = scheduled ? visibleScheduledDialogMainThreadIds : visibleDialogMainThreadIds; if (set) { - if (arrayList.contains(dialog_id)) { + if (arrayList.contains(dialogId)) { return; } - arrayList.add(dialog_id); + arrayList.add(dialogId); } else { - arrayList.remove(dialog_id); + arrayList.remove(dialogId); } } - public void setLastCreatedDialogId(final long dialogId, boolean scheduled, final boolean set) { + public void setLastCreatedDialogId(final long dialogId, boolean scheduled, boolean set) { if (!scheduled) { ArrayList arrayList = createdDialogMainThreadIds; if (set) { @@ -2798,8 +2799,8 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public TLRPC.TL_chatInviteExported getExportedInvite(int chat_id) { - return exportedChats.get(chat_id); + public TLRPC.TL_chatInviteExported getExportedInvite(long chatId) { + return exportedChats.get(chatId); } public boolean putUser(TLRPC.User user, boolean fromCache) { @@ -2952,7 +2953,7 @@ public class MessagesController extends BaseController implements NotificationCe if (!fromCache) { if (oldChat != null) { if (chat.version != oldChat.version) { - loadedFullChats.remove((Integer) chat.id); + loadedFullChats.remove(chat.id); } if (oldChat.participants_count != 0 && chat.participants_count == 0) { chat.participants_count = oldChat.participants_count; @@ -3060,7 +3061,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public ArrayList getActiveGroupCalls() { + public ArrayList getActiveGroupCalls() { return new ArrayList<>(activeVoiceChatsMap.keySet()); } @@ -3094,15 +3095,15 @@ public class MessagesController extends BaseController implements NotificationCe } } - public TLRPC.UserFull getUserFull(int uid) { + public TLRPC.UserFull getUserFull(long uid) { return fullUsers.get(uid); } - public TLRPC.ChatFull getChatFull(int chatId) { + public TLRPC.ChatFull getChatFull(long chatId) { return fullChats.get(chatId); } - public void putGroupCall(int chatId, ChatObject.Call call) { + public void putGroupCall(long chatId, ChatObject.Call call) { groupCalls.put(call.call.id, call); groupCallsByChatId.put(chatId, call); TLRPC.ChatFull chatFull = getChatFull(chatId); @@ -3113,11 +3114,11 @@ public class MessagesController extends BaseController implements NotificationCe loadFullChat(chatId, 0, true); } - public ChatObject.Call getGroupCall(int chatId, boolean load) { + public ChatObject.Call getGroupCall(long chatId, boolean load) { return getGroupCall(chatId, load, null); } - public ChatObject.Call getGroupCall(int chatId, boolean load, Runnable onLoad) { + public ChatObject.Call getGroupCall(long chatId, boolean load, Runnable onLoad) { TLRPC.ChatFull chatFull = getChatFull(chatId); if (chatFull == null || chatFull.call == null) { return null; @@ -3144,7 +3145,7 @@ public class MessagesController extends BaseController implements NotificationCe onLoad.run(); } } - loadingGroupCalls.remove((Integer) chatId); + loadingGroupCalls.remove(chatId); })); } } @@ -3154,12 +3155,12 @@ public class MessagesController extends BaseController implements NotificationCe return result; } - public void cancelLoadFullUser(int uid) { - loadingFullUsers.remove((Integer) uid); + public void cancelLoadFullUser(long userId) { + loadingFullUsers.remove(userId); } - public void cancelLoadFullChat(int cid) { - loadingFullChats.remove((Integer) cid); + public void cancelLoadFullChat(long chatId) { + loadingFullChats.remove(chatId); } protected void clearFullUsers() { @@ -3174,7 +3175,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs(); if (dialogs != null) { for (int a = 0; a < dialogs.size(); a++) { - TLRPC.InputPeer inputPeer = getInputPeer((int) dialogs.get(a).id); + TLRPC.InputPeer inputPeer = getInputPeer(dialogs.get(a).id); if (inputPeer instanceof TLRPC.TL_inputPeerChannel && inputPeer.access_hash == 0) { continue; } @@ -3183,7 +3184,7 @@ public class MessagesController extends BaseController implements NotificationCe req.peers.add(inputDialogPeer); } } else { - TLRPC.InputPeer inputPeer = getInputPeer((int) did); + TLRPC.InputPeer inputPeer = getInputPeer(did); if (inputPeer instanceof TLRPC.TL_inputPeerChannel && inputPeer.access_hash == 0) { return; } @@ -3247,16 +3248,16 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public TLRPC.ChannelParticipant getAdminInChannel(int uid, int chatId) { - SparseArray array = channelAdmins.get(chatId); + public TLRPC.ChannelParticipant getAdminInChannel(long uid, long chatId) { + LongSparseArray array = channelAdmins.get(chatId); if (array == null) { return null; } return array.get(uid); } - public String getAdminRank(int chatId, int uid) { - SparseArray array = channelAdmins.get(chatId); + public String getAdminRank(long chatId, long uid) { + LongSparseArray array = channelAdmins.get(chatId); if (array == null) { return null; } @@ -3264,15 +3265,14 @@ public class MessagesController extends BaseController implements NotificationCe if (participant == null) { return null; } - String rank = array.get(uid).rank; - return rank != null ? rank : ""; + return participant.rank != null ? participant.rank : ""; } - public boolean isChannelAdminsLoaded(int chatId) { + public boolean isChannelAdminsLoaded(long chatId) { return channelAdmins.get(chatId) != null; } - public void loadChannelAdmins(final int chatId, final boolean cache) { + public void loadChannelAdmins(long chatId, boolean cache) { int loadTime = loadingChannelAdmins.get(chatId); if (SystemClock.elapsedRealtime() - loadTime < 60) { return; @@ -3282,19 +3282,6 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().loadChannelAdmins(chatId); } else { TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); - /*SparseArray array = channelAdmins.get(chatId); - if (array != null) { - ArrayList values = new ArrayList<>(); - for (int a = 0; a < array.size(); a++) { - values.add(array.keyAt(a)); - } - Collections.sort(values); - long acc = 0; - for (int a = 0; a < values.size(); a++) { - acc = ((acc * 20261) + 0x80000000L + values.get(a)) % 0x80000000L; - } - req.hash = (int) acc; - }*/ req.channel = getInputChannel(chatId); req.limit = 100; req.filter = new TLRPC.TL_channelParticipantsAdmins(); @@ -3306,8 +3293,8 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void processLoadedAdminsResponse(int chatId, TLRPC.TL_channels_channelParticipants participants) { - final SparseArray array1 = new SparseArray<>(participants.participants.size()); + public void processLoadedAdminsResponse(long chatId, TLRPC.TL_channels_channelParticipants participants) { + LongSparseArray array1 = new LongSparseArray<>(participants.participants.size()); for (int a = 0; a < participants.participants.size(); a++) { TLRPC.ChannelParticipant participant = participants.participants.get(a); array1.put(MessageObject.getPeerId(participant.peer), participant); @@ -3315,7 +3302,7 @@ public class MessagesController extends BaseController implements NotificationCe processLoadedChannelAdmins(array1, chatId, false); } - public void processLoadedChannelAdmins(final SparseArray array, final int chatId, final boolean cache) { + public void processLoadedChannelAdmins(final LongSparseArray array, long chatId, boolean cache) { if (!cache) { getMessagesStorage().putChannelAdmins(chatId, array); } @@ -3329,59 +3316,59 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void loadFullChat(final int chat_id, final int classGuid, boolean force) { - boolean loaded = loadedFullChats.contains(chat_id); - if (loadingFullChats.contains(chat_id) || !force && loaded) { + public void loadFullChat(long chatId, int classGuid, boolean force) { + boolean loaded = loadedFullChats.contains(chatId); + if (loadingFullChats.contains(chatId) || !force && loaded) { return; } - loadingFullChats.add(chat_id); + loadingFullChats.add(chatId); TLObject request; - final long dialog_id = -chat_id; - final TLRPC.Chat chat = getChat(chat_id); + long dialogId = -chatId; + TLRPC.Chat chat = getChat(chatId); if (ChatObject.isChannel(chat)) { TLRPC.TL_channels_getFullChannel req = new TLRPC.TL_channels_getFullChannel(); req.channel = getInputChannel(chat); request = req; - loadChannelAdmins(chat_id, !loaded); + loadChannelAdmins(chatId, !loaded); } else { TLRPC.TL_messages_getFullChat req = new TLRPC.TL_messages_getFullChat(); - req.chat_id = chat_id; + req.chat_id = chatId; request = req; - if (dialogs_read_inbox_max.get(dialog_id) == null || dialogs_read_outbox_max.get(dialog_id) == null) { - reloadDialogsReadValue(null, dialog_id); + if (dialogs_read_inbox_max.get(dialogId) == null || dialogs_read_outbox_max.get(dialogId) == null) { + reloadDialogsReadValue(null, dialogId); } } int reqId = getConnectionsManager().sendRequest(request, (response, error) -> { if (error == null) { - final TLRPC.TL_messages_chatFull res = (TLRPC.TL_messages_chatFull) response; + TLRPC.TL_messages_chatFull res = (TLRPC.TL_messages_chatFull) response; getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); getMessagesStorage().updateChatInfo(res.full_chat, false); if (ChatObject.isChannel(chat)) { - Integer value = dialogs_read_inbox_max.get(dialog_id); + Integer value = dialogs_read_inbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(false, dialog_id); + value = getMessagesStorage().getDialogReadMax(false, dialogId); } - dialogs_read_inbox_max.put(dialog_id, Math.max(res.full_chat.read_inbox_max_id, value)); + dialogs_read_inbox_max.put(dialogId, Math.max(res.full_chat.read_inbox_max_id, value)); if (res.full_chat.read_inbox_max_id > value) { ArrayList arrayList = new ArrayList<>(); TLRPC.TL_updateReadChannelInbox update = new TLRPC.TL_updateReadChannelInbox(); - update.channel_id = chat_id; + update.channel_id = chatId; update.max_id = res.full_chat.read_inbox_max_id; arrayList.add(update); processUpdateArray(arrayList, null, null, false, 0); } - value = dialogs_read_outbox_max.get(dialog_id); + value = dialogs_read_outbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(true, dialog_id); + value = getMessagesStorage().getDialogReadMax(true, dialogId); } - dialogs_read_outbox_max.put(dialog_id, Math.max(res.full_chat.read_outbox_max_id, value)); + dialogs_read_outbox_max.put(dialogId, Math.max(res.full_chat.read_outbox_max_id, value)); if (res.full_chat.read_outbox_max_id > value) { ArrayList arrayList = new ArrayList<>(); TLRPC.TL_updateReadChannelOutbox update = new TLRPC.TL_updateReadChannelOutbox(); - update.channel_id = chat_id; + update.channel_id = chatId; update.max_id = res.full_chat.read_outbox_max_id; arrayList.add(update); processUpdateArray(arrayList, null, null, false, 0); @@ -3389,20 +3376,20 @@ public class MessagesController extends BaseController implements NotificationCe } AndroidUtilities.runOnUIThread(() -> { - TLRPC.ChatFull old = fullChats.get(chat_id); + TLRPC.ChatFull old = fullChats.get(chatId); if (old != null) { res.full_chat.inviterId = old.inviterId; } - fullChats.put(chat_id, res.full_chat); - applyDialogNotificationsSettings(-chat_id, res.full_chat.notify_settings); + fullChats.put(chatId, res.full_chat); + applyDialogNotificationsSettings(-chatId, res.full_chat.notify_settings); for (int a = 0; a < res.full_chat.bot_info.size(); a++) { TLRPC.BotInfo botInfo = res.full_chat.bot_info.get(a); - getMediaDataController().putBotInfo(-chat_id, botInfo); + getMediaDataController().putBotInfo(-chatId, botInfo); } - int index = blockePeers.indexOfKey(-chat_id); + int index = blockePeers.indexOfKey(-chatId); if (res.full_chat.blocked) { if (index < 0) { - blockePeers.put(-chat_id, 1); + blockePeers.put(-chatId, 1); getNotificationCenter().postNotificationName(NotificationCenter.blockedUsersDidLoad); } } else { @@ -3411,9 +3398,9 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.blockedUsersDidLoad); } } - exportedChats.put(chat_id, res.full_chat.exported_invite); - loadingFullChats.remove((Integer) chat_id); - loadedFullChats.add(chat_id); + exportedChats.put(chatId, res.full_chat.exported_invite); + loadingFullChats.remove(chatId); + loadedFullChats.add(chatId); putUsers(res.users, false); putChats(res.chats, false); @@ -3422,7 +3409,7 @@ public class MessagesController extends BaseController implements NotificationCe } getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, res.full_chat, classGuid, false, true); if ((res.full_chat.flags & 2048) != 0) { - TLRPC.Dialog dialog = dialogs_dict.get(-chat_id); + TLRPC.Dialog dialog = dialogs_dict.get(-chatId); if (dialog != null && dialog.folder_id != res.full_chat.folder_id) { dialog.folder_id = res.full_chat.folder_id; sortDialogs(null); @@ -3432,8 +3419,8 @@ public class MessagesController extends BaseController implements NotificationCe }); } else { AndroidUtilities.runOnUIThread(() -> { - checkChannelError(error.text, chat_id); - loadingFullChats.remove((Integer) chat_id); + checkChannelError(error.text, chatId); + loadingFullChats.remove(chatId); }); } }); @@ -3442,16 +3429,16 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void loadFullUser(final TLRPC.User user, final int classGuid, boolean force) { + public void loadFullUser(final TLRPC.User user, int classGuid, boolean force) { if (user == null || loadingFullUsers.contains(user.id) || !force && loadedFullUsers.contains(user.id)) { return; } loadingFullUsers.add(user.id); TLRPC.TL_users_getFullUser req = new TLRPC.TL_users_getFullUser(); req.id = getInputUser(user); - long dialog_id = user.id; - if (dialogs_read_inbox_max.get(dialog_id) == null || dialogs_read_outbox_max.get(dialog_id) == null) { - reloadDialogsReadValue(null, dialog_id); + long dialogId = user.id; + if (dialogs_read_inbox_max.get(dialogId) == null || dialogs_read_outbox_max.get(dialogId) == null) { + reloadDialogsReadValue(null, dialogId); } int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { @@ -3478,7 +3465,7 @@ public class MessagesController extends BaseController implements NotificationCe } } fullUsers.put(user.id, userFull); - loadingFullUsers.remove((Integer) user.id); + loadingFullUsers.remove(user.id); loadedFullUsers.add(user.id); String names = user.first_name + user.last_name + user.username; ArrayList users = new ArrayList<>(); @@ -3502,19 +3489,24 @@ public class MessagesController extends BaseController implements NotificationCe } }); } else { - AndroidUtilities.runOnUIThread(() -> loadingFullUsers.remove((Integer) user.id)); + AndroidUtilities.runOnUIThread(() -> loadingFullUsers.remove(user.id)); } }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } - private void reloadMessages(final ArrayList mids, final long dialog_id, boolean scheduled) { + private void reloadMessages(ArrayList mids, long dialogId, boolean scheduled) { if (mids.isEmpty()) { return; } TLObject request; - final ArrayList result = new ArrayList<>(); - final TLRPC.Chat chat = ChatObject.getChatByDialog(dialog_id, currentAccount); + ArrayList result = new ArrayList<>(); + TLRPC.Chat chat; + if (DialogObject.isChatDialog(dialogId)) { + chat = getChat(-dialogId); + } else { + chat = null; + } if (ChatObject.isChannel(chat)) { TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages(); req.channel = getInputChannel(chat); @@ -3525,7 +3517,7 @@ public class MessagesController extends BaseController implements NotificationCe req.id = result; request = req; } - ArrayList arrayList = reloadingMessages.get(dialog_id); + ArrayList arrayList = reloadingMessages.get(dialogId); for (int a = 0; a < mids.size(); a++) { Integer mid = mids.get(a); if (arrayList != null && arrayList.contains(mid)) { @@ -3538,40 +3530,40 @@ public class MessagesController extends BaseController implements NotificationCe } if (arrayList == null) { arrayList = new ArrayList<>(); - reloadingMessages.put(dialog_id, arrayList); + reloadingMessages.put(dialogId, arrayList); } arrayList.addAll(result); getConnectionsManager().sendRequest(request, (response, error) -> { if (error == null) { TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response; - final SparseArray usersLocal = new SparseArray<>(); + LongSparseArray usersLocal = new LongSparseArray<>(); for (int a = 0; a < messagesRes.users.size(); a++) { TLRPC.User u = messagesRes.users.get(a); usersLocal.put(u.id, u); } - final SparseArray chatsLocal = new SparseArray<>(); + LongSparseArray chatsLocal = new LongSparseArray<>(); for (int a = 0; a < messagesRes.chats.size(); a++) { TLRPC.Chat c = messagesRes.chats.get(a); chatsLocal.put(c.id, c); } - Integer inboxValue = dialogs_read_inbox_max.get(dialog_id); + Integer inboxValue = dialogs_read_inbox_max.get(dialogId); if (inboxValue == null) { - inboxValue = getMessagesStorage().getDialogReadMax(false, dialog_id); - dialogs_read_inbox_max.put(dialog_id, inboxValue); + inboxValue = getMessagesStorage().getDialogReadMax(false, dialogId); + dialogs_read_inbox_max.put(dialogId, inboxValue); } - Integer outboxValue = dialogs_read_outbox_max.get(dialog_id); + Integer outboxValue = dialogs_read_outbox_max.get(dialogId); if (outboxValue == null) { - outboxValue = getMessagesStorage().getDialogReadMax(true, dialog_id); - dialogs_read_outbox_max.put(dialog_id, outboxValue); + outboxValue = getMessagesStorage().getDialogReadMax(true, dialogId); + dialogs_read_outbox_max.put(dialogId, outboxValue); } - final ArrayList objects = new ArrayList<>(); + ArrayList objects = new ArrayList<>(); for (int a = 0; a < messagesRes.messages.size(); a++) { TLRPC.Message message = messagesRes.messages.get(a); - message.dialog_id = dialog_id; + message.dialog_id = dialogId; if (!scheduled) { message.unread = (message.out ? outboxValue : inboxValue) < message.id; } @@ -3579,22 +3571,22 @@ public class MessagesController extends BaseController implements NotificationCe } ImageLoader.saveMessagesThumbs(messagesRes.messages); - getMessagesStorage().putMessages(messagesRes, dialog_id, -1, 0, false, scheduled); + getMessagesStorage().putMessages(messagesRes, dialogId, -1, 0, false, scheduled); AndroidUtilities.runOnUIThread(() -> { - ArrayList arrayList1 = reloadingMessages.get(dialog_id); + ArrayList arrayList1 = reloadingMessages.get(dialogId); if (arrayList1 != null) { arrayList1.removeAll(result); if (arrayList1.isEmpty()) { - reloadingMessages.remove(dialog_id); + reloadingMessages.remove(dialogId); } } - MessageObject dialogObj = dialogMessage.get(dialog_id); + MessageObject dialogObj = dialogMessage.get(dialogId); if (dialogObj != null) { for (int a = 0; a < objects.size(); a++) { MessageObject obj = objects.get(a); if (dialogObj.getId() == obj.getId()) { - dialogMessage.put(dialog_id, obj); + dialogMessage.put(dialogId, obj); if (obj.messageOwner.peer_id.channel_id == 0) { MessageObject obj2 = dialogMessagesByIds.get(obj.getId()); dialogMessagesByIds.remove(obj.getId()); @@ -3607,7 +3599,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } - getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialog_id, objects); + getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, objects); }); } }); @@ -3621,7 +3613,7 @@ public class MessagesController extends BaseController implements NotificationCe editor.putInt("dialog_bar_vis3" + dialogId, 3); editor.remove("dialog_bar_invite" + dialogId); editor.commit(); - if ((int) dialogId != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { TLRPC.TL_messages_hidePeerSettingsBar req = new TLRPC.TL_messages_hidePeerSettingsBar(); if (currentUser != null) { req.peer = getInputPeer(currentUser.id); @@ -3641,7 +3633,7 @@ public class MessagesController extends BaseController implements NotificationCe SharedPreferences.Editor editor = notificationsPreferences.edit(); editor.putInt("dialog_bar_vis3" + dialogId, 3); editor.commit(); - if ((int) dialogId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { if (currentEncryptedChat == null || currentEncryptedChat.access_hash == 0) { return; } @@ -3712,7 +3704,7 @@ public class MessagesController extends BaseController implements NotificationCe if (currentUser == null && currentChat == null) { return; } - final long dialogId; + long dialogId; if (currentUser != null) { dialogId = currentUser.id; } else { @@ -3746,7 +3738,7 @@ public class MessagesController extends BaseController implements NotificationCe })); } - protected void processNewChannelDifferenceParams(int pts, int pts_count, int channelId) { + protected void processNewChannelDifferenceParams(int pts, int pts_count, long channelId) { if (BuildVars.LOGS_ENABLED) { FileLog.d("processNewChannelDifferenceParams pts = " + pts + " pts_count = " + pts_count + " channeldId = " + channelId); } @@ -3766,7 +3758,7 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().saveChannelPts(channelId, pts); } else if (channelPts != pts) { long updatesStartWaitTime = updatesStartWaitTimeChannels.get(channelId); - boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId); + boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId, false); if (gettingDifferenceChannel || updatesStartWaitTime == 0 || Math.abs(System.currentTimeMillis() - updatesStartWaitTime) <= 1500) { if (BuildVars.LOGS_ENABLED) { FileLog.d("ADD CHANNEL UPDATE TO QUEUE pts = " + pts + " pts_count = " + pts_count); @@ -3846,46 +3838,52 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void didAddedNewTask(final int minDate, final SparseArray> mids) { + public void didAddedNewTask(int minDate, long dialogId, SparseArray> mids) { Utilities.stageQueue.postRunnable(() -> { - if (currentDeletingTaskMids == null && !gettingNewDeleteTask || currentDeletingTaskTime != 0 && minDate < currentDeletingTaskTime) { - getNewDeleteTask(null, 0, false); + if (currentDeletingTaskMids == null && currentDeletingTaskMediaMids == null && !gettingNewDeleteTask || currentDeletingTaskTime != 0 && minDate < currentDeletingTaskTime) { + getNewDeleteTask(null, null); } }); if (mids != null) { - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.didCreatedNewDeleteTask, mids)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.didCreatedNewDeleteTask, dialogId, mids)); } } - public void getNewDeleteTask(final ArrayList oldTask, final int channelId, boolean oldMedia) { + public void getNewDeleteTask(LongSparseArray> oldTask, LongSparseArray> oldTaskMedia) { Utilities.stageQueue.postRunnable(() -> { gettingNewDeleteTask = true; - getMessagesStorage().getNewTask(oldTask, channelId, oldMedia); + getMessagesStorage().getNewTask(oldTask, oldTaskMedia); }); } private boolean checkDeletingTask(boolean runnable) { int currentServerTime = getConnectionsManager().getCurrentTime(); - if (currentDeletingTaskMids != null && (runnable || currentDeletingTaskTime != 0 && currentDeletingTaskTime <= currentServerTime)) { + if ((currentDeletingTaskMids != null || currentDeletingTaskMediaMids != null) && (runnable || currentDeletingTaskTime != 0 && currentDeletingTaskTime <= currentServerTime)) { currentDeletingTaskTime = 0; if (currentDeleteTaskRunnable != null && !runnable) { Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable); } currentDeleteTaskRunnable = null; - final ArrayList mids = new ArrayList<>(currentDeletingTaskMids); + LongSparseArray> task = currentDeletingTaskMids != null ? currentDeletingTaskMids.clone() : null; + LongSparseArray> taskMedia = currentDeletingTaskMediaMids != null ? currentDeletingTaskMediaMids.clone() : null; AndroidUtilities.runOnUIThread(() -> { - if (currentDeletingTaskMedia) { - getMessagesStorage().emptyMessagesMedia(mids); - } else { - deleteMessages(mids, null, null, 0, 0, true, false, !mids.isEmpty() && mids.get(0) > 0); + if (task != null) { + for (int a = 0, N = task.size(); a < N; a++) { + ArrayList mids = task.valueAt(a); + deleteMessages(mids, null, null, task.keyAt(a), true, false, !mids.isEmpty() && mids.get(0) > 0); + } + } + if (taskMedia != null) { + for (int a = 0, N = taskMedia.size(); a < N; a++) { + getMessagesStorage().emptyMessagesMedia(taskMedia.keyAt(a), taskMedia.valueAt(a)); + } } Utilities.stageQueue.postRunnable(() -> { - getNewDeleteTask(mids, currentDeletingTaskChannelId, currentDeletingTaskMedia); + getNewDeleteTask(task, taskMedia); currentDeletingTaskTime = 0; currentDeletingTaskMids = null; - currentDeletingTaskMedia = false; - currentDeletingTaskChannelId = 0; + currentDeletingTaskMediaMids = null; }); }); return true; @@ -3893,14 +3891,13 @@ public class MessagesController extends BaseController implements NotificationCe return false; } - public void processLoadedDeleteTask(int taskTime, ArrayList messages, boolean media, int channelId) { + public void processLoadedDeleteTask(int taskTime, LongSparseArray> task, LongSparseArray> taskMedia) { Utilities.stageQueue.postRunnable(() -> { gettingNewDeleteTask = false; - if (messages != null) { + if (task != null || taskMedia != null) { currentDeletingTaskTime = taskTime; - currentDeletingTaskMids = messages; - currentDeletingTaskMedia = media; - currentDeletingTaskChannelId = channelId; + currentDeletingTaskMids = task; + currentDeletingTaskMediaMids = taskMedia; if (currentDeleteTaskRunnable != null) { Utilities.stageQueue.cancelRunnable(currentDeleteTaskRunnable); @@ -3915,15 +3912,14 @@ public class MessagesController extends BaseController implements NotificationCe } else { currentDeletingTaskTime = 0; currentDeletingTaskMids = null; - currentDeletingTaskMedia = false; - currentDeletingTaskChannelId = 0; + currentDeletingTaskMediaMids = null; } }); } - public void loadDialogPhotos(final int did, final int count, final long max_id, final boolean fromCache, final int classGuid) { + public void loadDialogPhotos(long did, int count, int maxId, boolean fromCache, int classGuid) { if (fromCache) { - getMessagesStorage().getDialogPhotos(did, count, max_id, classGuid); + getMessagesStorage().getDialogPhotos(did, count, maxId, classGuid); } else { if (did > 0) { TLRPC.User user = getUser(did); @@ -3933,12 +3929,12 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_photos_getUserPhotos req = new TLRPC.TL_photos_getUserPhotos(); req.limit = count; req.offset = 0; - req.max_id = (int) max_id; + req.max_id = maxId; req.user_id = getInputUser(user); int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.photos_Photos res = (TLRPC.photos_Photos) response; - processLoadedUserPhotos(res, null, did, count, max_id, false, classGuid); + processLoadedUserPhotos(res, null, did, count, maxId, false, classGuid); } }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); @@ -3946,7 +3942,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); req.filter = new TLRPC.TL_inputMessagesFilterChatPhotos(); req.limit = count; - req.offset_id = (int) max_id; + req.offset_id = maxId; req.q = ""; req.peer = getInputPeer(did); int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { @@ -3964,7 +3960,7 @@ public class MessagesController extends BaseController implements NotificationCe res.photos.add(message.action.photo); arrayList.add(message); } - processLoadedUserPhotos(res, arrayList, did, count, max_id, false, classGuid); + processLoadedUserPhotos(res, arrayList, did, count, maxId, false, classGuid); } }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); @@ -3972,7 +3968,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void blockPeer(int id) { + public void blockPeer(long id) { TLRPC.User user = null; TLRPC.Chat chat = null; if (id > 0) { @@ -4012,11 +4008,11 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void setParticipantBannedRole(final int chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.TL_chatBannedRights rights, final boolean isChannel, final BaseFragment parentFragment) { + public void setParticipantBannedRole(long chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.TL_chatBannedRights rights, boolean isChannel, BaseFragment parentFragment) { if (user == null && chat == null || rights == null) { return; } - final TLRPC.TL_channels_editBanned req = new TLRPC.TL_channels_editBanned(); + TLRPC.TL_channels_editBanned req = new TLRPC.TL_channels_editBanned(); req.channel = getInputChannel(chatId); if (user != null) { req.participant = getInputPeer(user); @@ -4034,7 +4030,7 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void setChannelSlowMode(int chatId, int seconds) { + public void setChannelSlowMode(long chatId, int seconds) { TLRPC.TL_channels_toggleSlowMode req = new TLRPC.TL_channels_toggleSlowMode(); req.seconds = seconds; req.channel = getInputChannel(chatId); @@ -4046,11 +4042,11 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void setDefaultBannedRole(final int chatId, TLRPC.TL_chatBannedRights rights, final boolean isChannel, final BaseFragment parentFragment) { + public void setDefaultBannedRole(long chatId, TLRPC.TL_chatBannedRights rights, boolean isChannel, BaseFragment parentFragment) { if (rights == null) { return; } - final TLRPC.TL_messages_editChatDefaultBannedRights req = new TLRPC.TL_messages_editChatDefaultBannedRights(); + TLRPC.TL_messages_editChatDefaultBannedRights req = new TLRPC.TL_messages_editChatDefaultBannedRights(); req.peer = getInputPeer(-chatId); req.banned_rights = rights; getConnectionsManager().sendRequest(req, (response, error) -> { @@ -4063,13 +4059,13 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void setUserAdminRole(final int chatId, TLRPC.User user, TLRPC.TL_chatAdminRights rights, String rank, final boolean isChannel, final BaseFragment parentFragment, boolean addingNew) { + public void setUserAdminRole(long chatId, TLRPC.User user, TLRPC.TL_chatAdminRights rights, String rank, boolean isChannel, BaseFragment parentFragment, boolean addingNew) { if (user == null || rights == null) { return; } TLRPC.Chat chat = getChat(chatId); if (ChatObject.isChannel(chat)) { - final TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin(); + TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin(); req.channel = getInputChannel(chat); req.user_id = getInputUser(user); req.admin_rights = rights; @@ -4102,7 +4098,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void unblockPeer(int id) { + public void unblockPeer(long id) { TLRPC.TL_contacts_unblock req = new TLRPC.TL_contacts_unblock(); TLRPC.User user = null; TLRPC.Chat chat = null; @@ -4217,12 +4213,12 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void processLoadedUserPhotos(final TLRPC.photos_Photos res, ArrayList messages, final int did, final int count, final long max_id, final boolean fromCache, final int classGuid) { + public void processLoadedUserPhotos(final TLRPC.photos_Photos res, ArrayList messages, long did, int count, int maxId, boolean fromCache, int classGuid) { if (!fromCache) { getMessagesStorage().putUsersAndChats(res.users, null, true, true); getMessagesStorage().putDialogPhotos(did, res, messages); } else if (res == null || res.photos.isEmpty()) { - loadDialogPhotos(did, count, max_id, false, classGuid); + loadDialogPhotos(did, count, maxId, false, classGuid); return; } AndroidUtilities.runOnUIThread(() -> { @@ -4397,7 +4393,7 @@ public class MessagesController extends BaseController implements NotificationCe req = request; } - final long newTaskId; + long newTaskId; if (taskId != 0) { newTaskId = taskId; } else { @@ -4471,7 +4467,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void markDialogMessageAsDeleted(ArrayList messages, long dialogId) { + public void markDialogMessageAsDeleted(long dialogId, ArrayList messages) { MessageObject obj = dialogMessage.get(dialogId); if (obj != null) { for (int a = 0; a < messages.size(); a++) { @@ -4484,20 +4480,27 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, final long dialogId, final int channelId, boolean forAll, boolean scheduled) { - deleteMessages(messages, randoms, encryptedChat, dialogId, channelId, forAll, scheduled, false, 0, null); + public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, long dialogId, boolean forAll, boolean scheduled) { + deleteMessages(messages, randoms, encryptedChat, dialogId, forAll, scheduled, false, 0, null); } - public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, final long dialogId, final int channelId, boolean forAll, boolean scheduled, boolean cacheOnly) { - deleteMessages(messages, randoms, encryptedChat, dialogId, channelId, forAll, scheduled, cacheOnly, 0, null); + public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, long dialogId, boolean forAll, boolean scheduled, boolean cacheOnly) { + deleteMessages(messages, randoms, encryptedChat, dialogId, forAll, scheduled, cacheOnly, 0, null); } - public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, final long dialogId, final int channelId, boolean forAll, boolean scheduled, boolean cacheOnly, long taskId, TLObject taskRequest) { + public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, long dialogId, boolean forAll, boolean scheduled, boolean cacheOnly, long taskId, TLObject taskRequest) { if ((messages == null || messages.isEmpty()) && taskId == 0) { return; } ArrayList toSend = null; + long channelId; if (taskId == 0) { + if (dialogId != 0 && DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getChat(-dialogId); + channelId = ChatObject.isChannel(chat) ? chat.id : 0; + } else { + channelId = 0; + } if (!cacheOnly) { toSend = new ArrayList<>(); for (int a = 0, N = messages.size(); a < N; a++) { @@ -4508,7 +4511,7 @@ public class MessagesController extends BaseController implements NotificationCe } } if (scheduled) { - getMessagesStorage().markMessagesAsDeleted(messages, true, channelId, false, true); + getMessagesStorage().markMessagesAsDeleted(dialogId, messages, true, false, true); } else { if (channelId == 0) { for (int a = 0; a < messages.size(); a++) { @@ -4519,35 +4522,40 @@ public class MessagesController extends BaseController implements NotificationCe } } } else { - markDialogMessageAsDeleted(messages, -channelId); + markDialogMessageAsDeleted(dialogId, messages); } - getMessagesStorage().markMessagesAsDeleted(messages, true, channelId, forAll, false); - getMessagesStorage().updateDialogsWithDeletedMessages(messages, null, true, channelId); + getMessagesStorage().markMessagesAsDeleted(dialogId, messages, true, forAll, false); + getMessagesStorage().updateDialogsWithDeletedMessages(dialogId, channelId, messages, null, true); } getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, messages, channelId, scheduled); + } else { + if (taskRequest instanceof TLRPC.TL_channels_deleteMessages) { + channelId = ((TLRPC.TL_channels_deleteMessages) taskRequest).channel.channel_id; + } else { + channelId = 0; + } } if (cacheOnly) { return; } - final long newTaskId; + long newTaskId; if (scheduled) { TLRPC.TL_messages_deleteScheduledMessages req; - if (taskRequest != null) { + if (taskRequest instanceof TLRPC.TL_messages_deleteScheduledMessages) { req = (TLRPC.TL_messages_deleteScheduledMessages) taskRequest; newTaskId = taskId; } else { req = new TLRPC.TL_messages_deleteScheduledMessages(); req.id = toSend; - req.peer = getInputPeer((int) dialogId); + req.peer = getInputPeer(dialogId); NativeByteBuffer data = null; try { - data = new NativeByteBuffer(16 + req.getObjectSize()); - data.writeInt32(18); + data = new NativeByteBuffer(12 + req.getObjectSize()); + data.writeInt32(24); data.writeInt64(dialogId); - data.writeInt32(channelId); req.serializeToStream(data); } catch (Exception e) { FileLog.e(e); @@ -4576,9 +4584,9 @@ public class MessagesController extends BaseController implements NotificationCe NativeByteBuffer data = null; try { - data = new NativeByteBuffer(8 + req.getObjectSize()); - data.writeInt32(7); - data.writeInt32(channelId); + data = new NativeByteBuffer(12 + req.getObjectSize()); + data.writeInt32(24); + data.writeInt64(dialogId); req.serializeToStream(data); } catch (Exception e) { FileLog.e(e); @@ -4600,7 +4608,7 @@ public class MessagesController extends BaseController implements NotificationCe getSecretChatHelper().sendMessagesDeleteMessage(encryptedChat, randoms, null); } TLRPC.TL_messages_deleteMessages req; - if (taskRequest != null) { + if (taskRequest instanceof TLRPC.TL_messages_deleteMessages) { req = (TLRPC.TL_messages_deleteMessages) taskRequest; newTaskId = taskId; } else { @@ -4610,9 +4618,9 @@ public class MessagesController extends BaseController implements NotificationCe NativeByteBuffer data = null; try { - data = new NativeByteBuffer(8 + req.getObjectSize()); - data.writeInt32(7); - data.writeInt32(channelId); + data = new NativeByteBuffer(12 + req.getObjectSize()); + data.writeInt32(24); + data.writeInt64(dialogId); req.serializeToStream(data); } catch (Exception e) { FileLog.e(e); @@ -4673,9 +4681,9 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void deleteUserChannelHistory(final TLRPC.Chat chat, final TLRPC.User user, int offset) { + public void deleteUserChannelHistory(TLRPC.Chat chat, TLRPC.User user, int offset) { if (offset == 0) { - getMessagesStorage().deleteUserChatHistory(-chat.id, chat.id, user.id); + getMessagesStorage().deleteUserChatHistory(-chat.id, user.id); } TLRPC.TL_channels_deleteUserHistory req = new TLRPC.TL_channels_deleteUserHistory(); req.channel = getInputChannel(chat); @@ -4729,7 +4737,7 @@ public class MessagesController extends BaseController implements NotificationCe } public void putAllNeededDraftDialogs() { - final LongSparseArray> drafts = getMediaDataController().getDrafts(); + LongSparseArray> drafts = getMediaDataController().getDrafts(); for (int i = 0, size = drafts.size(); i < size; i++) { SparseArray threads = drafts.valueAt(i); TLRPC.DraftMessage draftMessage = threads.get(0); @@ -4742,20 +4750,20 @@ public class MessagesController extends BaseController implements NotificationCe public void putDraftDialogIfNeed(long dialogId, TLRPC.DraftMessage draftMessage) { if (dialogs_dict.indexOfKey(dialogId) < 0) { - final MediaDataController mediaDataController = getMediaDataController(); - final int dialogsCount = allDialogs.size(); + MediaDataController mediaDataController = getMediaDataController(); + int dialogsCount = allDialogs.size(); if (dialogsCount > 0) { - final TLRPC.Dialog dialog = allDialogs.get(dialogsCount - 1); - final long minDate = DialogObject.getLastMessageOrDraftDate(dialog, mediaDataController.getDraft(dialog.id, 0)); + TLRPC.Dialog dialog = allDialogs.get(dialogsCount - 1); + long minDate = DialogObject.getLastMessageOrDraftDate(dialog, mediaDataController.getDraft(dialog.id, 0)); if (draftMessage.date < minDate) { return; } } - final TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); + TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); dialog.id = dialogId; dialog.draft = draftMessage; dialog.folder_id = mediaDataController.getDraftFolderId(dialogId); - dialog.flags = dialogId < 0 && ChatObject.isChannel(getChat((int) -dialogId)) ? 1 : 0; + dialog.flags = dialogId < 0 && ChatObject.isChannel(getChat(-dialogId)) ? 1 : 0; dialogs_dict.put(dialogId, dialog); allDialogs.add(dialog); sortDialogs(null); @@ -4763,7 +4771,7 @@ public class MessagesController extends BaseController implements NotificationCe } public void removeDraftDialogIfNeed(long dialogId) { - final TLRPC.Dialog dialog = dialogs_dict.get(dialogId); + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null && dialog.top_message == 0) { dialogs_dict.remove(dialog.id); allDialogs.remove(dialog); @@ -4777,11 +4785,11 @@ public class MessagesController extends BaseController implements NotificationCe long did = dialog.id; if (dialogsServerOnly.remove(dialog) && DialogObject.isChannel(dialog)) { Utilities.stageQueue.postRunnable(() -> { - channelsPts.delete(-(int) did); - shortPollChannels.delete(-(int) did); - needShortPollChannels.delete(-(int) did); - shortPollOnlines.delete(-(int) did); - needShortPollOnlines.delete(-(int) did); + channelsPts.delete(-did); + shortPollChannels.delete(-did); + needShortPollChannels.delete(-did); + shortPollOnlines.delete(-did); + needShortPollOnlines.delete(-did); }); } allDialogs.remove(dialog); @@ -4809,7 +4817,7 @@ public class MessagesController extends BaseController implements NotificationCe return; } TLRPC.TL_help_hidePromoData req = new TLRPC.TL_help_hidePromoData(); - req.peer = getInputPeer((int) promoDialog.id); + req.peer = getInputPeer(promoDialog.id); getConnectionsManager().sendRequest(req, (response, error) -> { }); @@ -4822,17 +4830,17 @@ public class MessagesController extends BaseController implements NotificationCe removePromoDialog(); } - public void deleteDialog(final long did, final int onlyHistory) { + public void deleteDialog(final long did, int onlyHistory) { deleteDialog(did, onlyHistory, false); } - public void deleteDialog(final long did, final int onlyHistory, boolean revoke) { + public void deleteDialog(final long did, int onlyHistory, boolean revoke) { deleteDialog(did, 1, onlyHistory, 0, revoke, null, 0); } - public void setDialogHistoryTTL(final long did, int ttl) { + public void setDialogHistoryTTL(long did, int ttl) { TLRPC.TL_messages_setHistoryTTL req = new TLRPC.TL_messages_setHistoryTTL(); - req.peer = getInputPeer((int) did); + req.peer = getInputPeer(did); req.period = ttl; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { @@ -4840,18 +4848,17 @@ public class MessagesController extends BaseController implements NotificationCe processUpdates(updates, false); } }); - int lowerId = (int) did; TLRPC.ChatFull chatFull = null; TLRPC.UserFull userFull = null; - if (lowerId > 0) { - userFull = getUserFull(lowerId); + if (did > 0) { + userFull = getUserFull(did); if (userFull == null) { return; } userFull.ttl_period = ttl; userFull.flags |= 16384; } else { - chatFull = getChatFull(-lowerId); + chatFull = getChatFull(-did); if (chatFull == null) { return; } @@ -4865,7 +4872,7 @@ public class MessagesController extends BaseController implements NotificationCe if (chatFull != null) { getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, chatFull, 0, false, false); } else { - getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, lowerId, userFull); + getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, did, userFull); } } @@ -4892,8 +4899,6 @@ public class MessagesController extends BaseController implements NotificationCe if (onlyHistory == 0 || onlyHistory == 3) { getMediaDataController().uninstallShortcut(did); } - int lower_part = (int) did; - int high_id = (int) (did >> 32); int max_id_delete = max_id; if (first != 0) { @@ -4921,7 +4926,7 @@ public class MessagesController extends BaseController implements NotificationCe if (isPromoDialog = (promoDialog != null && promoDialog.id == did)) { isLeftPromoChannel = true; if (promoDialog.id < 0) { - TLRPC.Chat chat = getChat(-(int) promoDialog.id); + TLRPC.Chat chat = getChat(-promoDialog.id); if (chat != null) { chat.left = true; } @@ -4956,7 +4961,7 @@ public class MessagesController extends BaseController implements NotificationCe if (object != null && object.messageOwner.random_id != 0) { dialogMessagesByRandomIds.remove(object.messageOwner.random_id); } - if (onlyHistory == 1 && lower_part != 0 && lastMessageId > 0) { + if (onlyHistory == 1 && !DialogObject.isEncryptedDialog(did) && lastMessageId > 0) { TLRPC.TL_messageService message = new TLRPC.TL_messageService(); message.id = dialog.top_message; message.out = getUserConfig().getClientUserId() == did; @@ -4965,23 +4970,11 @@ public class MessagesController extends BaseController implements NotificationCe message.flags |= 256; message.action = new TLRPC.TL_messageActionHistoryClear(); message.date = dialog.last_message_date; - message.dialog_id = lower_part; - if (lower_part > 0) { - message.peer_id = new TLRPC.TL_peerUser(); - message.peer_id.user_id = lower_part; - } else { - TLRPC.Chat chat = getChat(-lower_part); - if (ChatObject.isChannel(chat)) { - message.peer_id = new TLRPC.TL_peerChannel(); - message.peer_id.channel_id = -lower_part; - } else { - message.peer_id = new TLRPC.TL_peerChat(); - message.peer_id.chat_id = -lower_part; - } - } + message.dialog_id = did; + message.peer_id = getPeer(did); boolean isDialogCreated = createdDialogIds.contains(message.dialog_id); - final MessageObject obj = new MessageObject(currentAccount, message, isDialogCreated, isDialogCreated); - final ArrayList objArr = new ArrayList<>(); + MessageObject obj = new MessageObject(currentAccount, message, isDialogCreated, isDialogCreated); + ArrayList objArr = new ArrayList<>(); objArr.add(obj); ArrayList arr = new ArrayList<>(); arr.add(message); @@ -5018,15 +5011,15 @@ public class MessagesController extends BaseController implements NotificationCe return; } - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(did)) { if (peer == null) { - peer = getInputPeer(lower_part); + peer = getInputPeer(did); } if (peer == null) { return; } - final long newTaskId; + long newTaskId; if (!(peer instanceof TLRPC.TL_inputPeerChannel) || onlyHistory != 0) { if (max_id_delete > 0 && max_id_delete != Integer.MAX_VALUE) { int current = deletedHistory.get(did, 0); @@ -5078,8 +5071,8 @@ public class MessagesController extends BaseController implements NotificationCe req.max_id = max_id_delete > 0 ? max_id_delete : Integer.MAX_VALUE; req.just_clear = onlyHistory != 0; req.revoke = revoke; - final int max_id_delete_final = max_id_delete; - final TLRPC.InputPeer peerFinal = peer; + int max_id_delete_final = max_id_delete; + TLRPC.InputPeer peerFinal = peer; getConnectionsManager().sendRequest(req, (response, error) -> { if (newTaskId != 0) { getMessagesStorage().removePendingTask(newTaskId); @@ -5095,10 +5088,11 @@ public class MessagesController extends BaseController implements NotificationCe }, ConnectionsManager.RequestFlagInvokeAfter); } } else { + int encryptedId = DialogObject.getEncryptedChatId(did); if (onlyHistory == 1) { - getSecretChatHelper().sendClearHistoryMessage(getEncryptedChat(high_id), null); + getSecretChatHelper().sendClearHistoryMessage(getEncryptedChat(encryptedId), null); } else { - getSecretChatHelper().declineSecretChat(high_id, revoke); + getSecretChatHelper().declineSecretChat(encryptedId, revoke); } } } @@ -5144,14 +5138,14 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void loadChannelParticipants(final Integer chat_id) { - if (loadingFullParticipants.contains(chat_id) || loadedFullParticipants.contains(chat_id)) { + public void loadChannelParticipants(Long chatId) { + if (loadingFullParticipants.contains(chatId) || loadedFullParticipants.contains(chatId)) { return; } - loadingFullParticipants.add(chat_id); + loadingFullParticipants.add(chatId); - final TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); - req.channel = getInputChannel(chat_id); + TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); + req.channel = getInputChannel(chatId); req.filter = new TLRPC.TL_channelParticipantsRecent(); req.offset = 0; req.limit = 32; @@ -5161,10 +5155,10 @@ public class MessagesController extends BaseController implements NotificationCe putUsers(res.users, false); putChats(res.chats, false); getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); - getMessagesStorage().updateChannelUsers(chat_id, res.participants); - loadedFullParticipants.add(chat_id); + getMessagesStorage().updateChannelUsers(chatId, res.participants); + loadedFullParticipants.add(chatId); } - loadingFullParticipants.remove(chat_id); + loadingFullParticipants.remove(chatId); })); } @@ -5172,7 +5166,7 @@ public class MessagesController extends BaseController implements NotificationCe fullChats.put(chatFull.id, chatFull); } - public void processChatInfo(int chatId, final TLRPC.ChatFull info, final ArrayList usersArr, final boolean fromCache, boolean force, final boolean byChannelUsers, ArrayList pinnedMessages, HashMap pinnedMessagesMap, int totalPinnedCount, boolean pinnedEndReached) { + public void processChatInfo(long chatId, TLRPC.ChatFull info, ArrayList usersArr, boolean fromCache, boolean force, boolean byChannelUsers, ArrayList pinnedMessages, HashMap pinnedMessagesMap, int totalPinnedCount, boolean pinnedEndReached) { AndroidUtilities.runOnUIThread(() -> { if (fromCache && chatId > 0 && !byChannelUsers) { loadFullChat(chatId, 0, force); @@ -5188,7 +5182,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, info, 0, byChannelUsers, false); } if (pinnedMessages != null) { - getNotificationCenter().postNotificationName(NotificationCenter.pinnedInfoDidLoad, (long) -chatId, pinnedMessages, pinnedMessagesMap, totalPinnedCount, pinnedEndReached); + getNotificationCenter().postNotificationName(NotificationCenter.pinnedInfoDidLoad, -chatId, pinnedMessages, pinnedMessagesMap, totalPinnedCount, pinnedEndReached); } }); } @@ -5226,7 +5220,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, user.id, info); } if (pinnedMessages != null) { - getNotificationCenter().postNotificationName(NotificationCenter.pinnedInfoDidLoad, (long) user.id, pinnedMessages, pinnedMessagesMap, totalPinnedCount, pinnedEndReached); + getNotificationCenter().postNotificationName(NotificationCenter.pinnedInfoDidLoad, user.id, pinnedMessages, pinnedMessagesMap, totalPinnedCount, pinnedEndReached); } }); } @@ -5284,7 +5278,7 @@ public class MessagesController extends BaseController implements NotificationCe if (updatesQueueChannels.size() != 0) { for (int a = 0; a < updatesQueueChannels.size(); a++) { - int key = updatesQueueChannels.keyAt(a); + long key = updatesQueueChannels.keyAt(a); long updatesStartWaitTime = updatesStartWaitTimeChannels.valueAt(a); if (Math.abs(currentTime - updatesStartWaitTime) >= 1500) { if (BuildVars.LOGS_ENABLED) { @@ -5309,20 +5303,20 @@ public class MessagesController extends BaseController implements NotificationCe lastViewsCheckTime = System.currentTimeMillis(); if (channelViewsToSend.size() != 0) { for (int a = 0; a < channelViewsToSend.size(); a++) { - final int key = channelViewsToSend.keyAt(a); - final TLRPC.TL_messages_getMessagesViews req = new TLRPC.TL_messages_getMessagesViews(); + long key = channelViewsToSend.keyAt(a); + TLRPC.TL_messages_getMessagesViews req = new TLRPC.TL_messages_getMessagesViews(); req.peer = getInputPeer(key); req.id = channelViewsToSend.valueAt(a); req.increment = a == 0; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { TLRPC.TL_messages_messageViews res = (TLRPC.TL_messages_messageViews) response; - final SparseArray channelViews = new SparseArray<>(); - final SparseArray channelForwards = new SparseArray<>(); - final SparseArray> channelReplies = new SparseArray<>(); + LongSparseArray channelViews = new LongSparseArray<>(); + LongSparseArray channelForwards = new LongSparseArray<>(); + LongSparseArray> channelReplies = new LongSparseArray<>(); SparseIntArray views = channelViews.get(key); SparseIntArray forwards = channelForwards.get(key); - SparseArray replies = channelReplies.get(key); + SparseArray replies = channelReplies.get(key); for (int a1 = 0; a1 < req.id.size(); a1++) { if (a1 >= res.views.size()) { @@ -5352,7 +5346,7 @@ public class MessagesController extends BaseController implements NotificationCe } } getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); - getMessagesStorage().putChannelViews(channelViews, channelForwards, channelReplies, false, req.peer instanceof TLRPC.TL_inputPeerChannel); + getMessagesStorage().putChannelViews(channelViews, channelForwards, channelReplies, false); AndroidUtilities.runOnUIThread(() -> { putUsers(res.users, false); putChats(res.chats, false); @@ -5393,7 +5387,7 @@ public class MessagesController extends BaseController implements NotificationCe } else { messageObject.pollLastCheckTime = time; TLRPC.TL_messages_getPollResults req = new TLRPC.TL_messages_getPollResults(); - req.peer = getInputPeer((int) messageObject.getDialogId()); + req.peer = getInputPeer(messageObject.getDialogId()); req.msg_id = messageObject.getId(); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { @@ -5428,8 +5422,8 @@ public class MessagesController extends BaseController implements NotificationCe } } if (!onlinePrivacy.isEmpty()) { - ArrayList toRemove = null; - for (ConcurrentHashMap.Entry entry : onlinePrivacy.entrySet()) { + ArrayList toRemove = null; + for (ConcurrentHashMap.Entry entry : onlinePrivacy.entrySet()) { if (entry.getValue() < currentServerTime - 30) { if (toRemove == null) { toRemove = new ArrayList<>(); @@ -5438,7 +5432,7 @@ public class MessagesController extends BaseController implements NotificationCe } } if (toRemove != null) { - for (Integer uid : toRemove) { + for (Long uid : toRemove) { onlinePrivacy.remove(uid); } AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS)); @@ -5446,7 +5440,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (shortPollChannels.size() != 0) { for (int a = 0; a < shortPollChannels.size(); a++) { - int key = shortPollChannels.keyAt(a); + long key = shortPollChannels.keyAt(a); int timeout = shortPollChannels.valueAt(a); if (timeout < System.currentTimeMillis() / 1000) { shortPollChannels.delete(key); @@ -5460,7 +5454,7 @@ public class MessagesController extends BaseController implements NotificationCe if (shortPollOnlines.size() != 0) { long time = SystemClock.elapsedRealtime() / 1000; for (int a = 0; a < shortPollOnlines.size(); a++) { - int key = shortPollOnlines.keyAt(a); + long key = shortPollOnlines.keyAt(a); int timeout = shortPollOnlines.valueAt(a); if (timeout < time) { if (needShortPollChannels.indexOfKey(key) >= 0) { @@ -5556,7 +5550,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_help_termsOfServiceUpdateEmpty res = (TLRPC.TL_help_termsOfServiceUpdateEmpty) response; nextTosCheckTime = res.expires; } else if (response instanceof TLRPC.TL_help_termsOfServiceUpdate) { - final TLRPC.TL_help_termsOfServiceUpdate res = (TLRPC.TL_help_termsOfServiceUpdate) response; + TLRPC.TL_help_termsOfServiceUpdate res = (TLRPC.TL_help_termsOfServiceUpdate) response; nextTosCheckTime = res.expires; AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.needShowAlert, 4, res.terms_of_service)); } else { @@ -5604,9 +5598,9 @@ public class MessagesController extends BaseController implements NotificationCe nextPromoInfoCheckTime = res.expires; noDialog = true; } else if (response instanceof TLRPC.TL_help_promoData) { - final TLRPC.TL_help_promoData res = (TLRPC.TL_help_promoData) response; + TLRPC.TL_help_promoData res = (TLRPC.TL_help_promoData) response; - final long did; + long did; if (res.peer.user_id != 0) { did = res.peer.user_id; } else if (res.peer.chat_id != 0) { @@ -5673,8 +5667,8 @@ public class MessagesController extends BaseController implements NotificationCe sortDialogs(null); getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload, true); } else { - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User u = res.users.get(a); usersDict.put(u.id, u); @@ -5715,7 +5709,7 @@ public class MessagesController extends BaseController implements NotificationCe return; } checkingPromoInfoRequestId = 0; - final TLRPC.TL_messages_peerDialogs res2 = (TLRPC.TL_messages_peerDialogs) response1; + TLRPC.TL_messages_peerDialogs res2 = (TLRPC.TL_messages_peerDialogs) response1; if (res2 != null && !res2.dialogs.isEmpty()) { getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs(); @@ -5731,9 +5725,8 @@ public class MessagesController extends BaseController implements NotificationCe putChats(res2.chats, false); if (promoDialog != null) { - int lowerId = (int) promoDialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = getChat(-lowerId); + if (promoDialog.id < 0) { + TLRPC.Chat chat = getChat(-promoDialog.id); if (ChatObject.isNotInChat(chat) || chat.restricted) { removeDialog(promoDialog); } @@ -5746,7 +5739,7 @@ public class MessagesController extends BaseController implements NotificationCe promoDialog.id = did; promoDialog.folder_id = 0; if (DialogObject.isChannel(promoDialog)) { - channelsPts.put(-(int) promoDialog.id, promoDialog.pts); + channelsPts.put(-promoDialog.id, promoDialog.pts); } Integer value = dialogs_read_inbox_max.get(promoDialog.id); if (value == null) { @@ -5760,8 +5753,8 @@ public class MessagesController extends BaseController implements NotificationCe dialogs_read_outbox_max.put(promoDialog.id, Math.max(value, promoDialog.read_outbox_max_id)); dialogs_dict.put(did, promoDialog); if (!res2.messages.isEmpty()) { - final SparseArray usersDict1 = new SparseArray<>(); - final SparseArray chatsDict1 = new SparseArray<>(); + LongSparseArray usersDict1 = new LongSparseArray<>(); + LongSparseArray chatsDict1 = new LongSparseArray<>(); for (int a = 0; a < res2.users.size(); a++) { TLRPC.User u = res2.users.get(a); usersDict1.put(u.id, u); @@ -5782,9 +5775,8 @@ public class MessagesController extends BaseController implements NotificationCe } else { AndroidUtilities.runOnUIThread(() -> { if (promoDialog != null) { - int lowerId = (int) promoDialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = getChat(-lowerId); + if (promoDialog.id < 0) { + TLRPC.Chat chat = getChat(-promoDialog.id); if (ChatObject.isNotInChat(chat) || chat.restricted) { removeDialog(promoDialog); } @@ -5827,9 +5819,8 @@ public class MessagesController extends BaseController implements NotificationCe if (promoDialog == null) { return; } - int lowerId = (int) promoDialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = getChat(-lowerId); + if (promoDialog.id < 0) { + TLRPC.Chat chat = getChat(-promoDialog.id); if (ChatObject.isNotInChat(chat) || chat.restricted) { removeDialog(promoDialog); } @@ -5858,115 +5849,125 @@ public class MessagesController extends BaseController implements NotificationCe } private void updatePrintingStrings() { - final LongSparseArray> newStrings = new LongSparseArray<>(); - final LongSparseArray> newTypes = new LongSparseArray<>(); + LongSparseArray> newStrings = new LongSparseArray<>(); + LongSparseArray> newTypes = new LongSparseArray<>(); for (HashMap.Entry>> dialogEntry : printingUsers.entrySet()) { Long key = dialogEntry.getKey(); + boolean isEncryptedChat = DialogObject.isEncryptedDialog(key); ConcurrentHashMap> threads = dialogEntry.getValue(); - int lower_id = (int) (long) key; for (HashMap.Entry> threadEntry : threads.entrySet()) { Integer threadId = threadEntry.getKey(); ArrayList arr = threadEntry.getValue(); - final SparseArray newPrintingStrings = new SparseArray<>(); - final SparseArray newPrintingStringsTypes = new SparseArray<>(); + SparseArray newPrintingStrings = new SparseArray<>(); + SparseArray newPrintingStringsTypes = new SparseArray<>(); newStrings.put(key, newPrintingStrings); newTypes.put(key, newPrintingStringsTypes); - if (lower_id > 0 || lower_id == 0 || arr.size() == 1) { + if (key > 0 || isEncryptedChat || arr.size() == 1) { PrintingUser pu = arr.get(0); TLRPC.User user = getUser(pu.userId); if (user == null) { continue; } if (pu.action instanceof TLRPC.TL_sendMessageRecordAudioAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsRecordingAudio", R.string.IsRecordingAudio, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("RecordingAudio", R.string.RecordingAudio)); } newPrintingStringsTypes.put(threadId, 1); } else if (pu.action instanceof TLRPC.TL_sendMessageRecordRoundAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsRecordingRound", R.string.IsRecordingRound, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("RecordingRound", R.string.RecordingRound)); } newPrintingStringsTypes.put(threadId, 4); } else if (pu.action instanceof TLRPC.TL_sendMessageUploadRoundAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingVideo", R.string.IsSendingVideo, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingVideoStatus", R.string.SendingVideoStatus)); } newPrintingStringsTypes.put(threadId, 4); } else if (pu.action instanceof TLRPC.TL_sendMessageUploadAudioAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingAudio", R.string.IsSendingAudio, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingAudio", R.string.SendingAudio)); } newPrintingStringsTypes.put(threadId, 2); } else if (pu.action instanceof TLRPC.TL_sendMessageUploadVideoAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingVideo", R.string.IsSendingVideo, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingVideoStatus", R.string.SendingVideoStatus)); } newPrintingStringsTypes.put(threadId, 2); } else if (pu.action instanceof TLRPC.TL_sendMessageRecordVideoAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsRecordingVideo", R.string.IsRecordingVideo, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("RecordingVideoStatus", R.string.RecordingVideoStatus)); } newPrintingStringsTypes.put(threadId, 2); } else if (pu.action instanceof TLRPC.TL_sendMessageUploadDocumentAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingFile", R.string.IsSendingFile, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingFile", R.string.SendingFile)); } newPrintingStringsTypes.put(threadId, 2); } else if (pu.action instanceof TLRPC.TL_sendMessageUploadPhotoAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingPhoto", R.string.IsSendingPhoto, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingPhoto", R.string.SendingPhoto)); } newPrintingStringsTypes.put(threadId, 2); } else if (pu.action instanceof TLRPC.TL_sendMessageGamePlayAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSendingGame", R.string.IsSendingGame, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SendingGame", R.string.SendingGame)); } newPrintingStringsTypes.put(threadId, 3); } else if (pu.action instanceof TLRPC.TL_sendMessageGeoLocationAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSelectingLocation", R.string.IsSelectingLocation, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SelectingLocation", R.string.SelectingLocation)); } newPrintingStringsTypes.put(threadId, 0); } else if (pu.action instanceof TLRPC.TL_sendMessageChooseContactAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsSelectingContact", R.string.IsSelectingContact, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("SelectingContact", R.string.SelectingContact)); } newPrintingStringsTypes.put(threadId, 0); + } else if (pu.action instanceof TLRPC.TL_sendMessageEmojiInteractionSeen) { + String emoji = ((TLRPC.TL_sendMessageEmojiInteractionSeen) pu.action).emoticon; + String printingString; + if (key < 0 && !isEncryptedChat) { + printingString= LocaleController.formatString("IsEnjoyngAnimations", R.string.IsEnjoyngAnimations, getUserNameForTyping(user), emoji); + } else { + printingString = LocaleController.formatString("EnjoyngAnimations", R.string.EnjoyngAnimations, emoji); + } + newPrintingStrings.put(threadId, printingString); + newPrintingStringsTypes.put(threadId, 5); } else if (pu.action instanceof TLRPC.TL_sendMessageChooseStickerAction) { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsChoosingSticker", R.string.IsChoosingSticker, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("ChoosingSticker", R.string.ChoosingSticker)); } newPrintingStringsTypes.put(threadId, 5); } else { - if (lower_id < 0) { + if (key < 0 && !isEncryptedChat) { newPrintingStrings.put(threadId, LocaleController.formatString("IsTypingGroup", R.string.IsTypingGroup, getUserNameForTyping(user))); } else { newPrintingStrings.put(threadId, LocaleController.getString("Typing", R.string.Typing)); @@ -6034,16 +6035,18 @@ public class MessagesController extends BaseController implements NotificationCe } public boolean sendTyping(long dialogId, int threadMsgId, int action, int classGuid) { + return sendTyping(dialogId, threadMsgId, action, null, classGuid); + } + public boolean sendTyping(long dialogId, int threadMsgId, int action, String emojicon, int classGuid) { if (action < 0 || action >= sendingTypings.length || dialogId == 0) { return false; } - int lower_part = (int) dialogId; - if (lower_part < 0) { - if (ChatObject.shouldSendAnonymously(getChat(-lower_part))) { + if (dialogId < 0) { + if (ChatObject.shouldSendAnonymously(getChat(-dialogId))) { return false; } } else { - TLRPC.User user = getUser(lower_part); + TLRPC.User user = getUser(dialogId); if (user != null) { if (user.id == getUserConfig().getClientUserId()) { return false; @@ -6067,14 +6070,13 @@ public class MessagesController extends BaseController implements NotificationCe if (threads.get(threadMsgId) != null) { return false; } - int high_id = (int) (dialogId >> 32); - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping(); if (threadMsgId != 0) { req.top_msg_id = threadMsgId; req.flags |= 1; } - req.peer = getInputPeer(lower_part); + req.peer = getInputPeer(dialogId); if (req.peer instanceof TLRPC.TL_inputPeerChannel) { TLRPC.Chat chat = getChat(req.peer.channel_id); if (chat == null || !chat.megagroup) { @@ -6106,6 +6108,10 @@ public class MessagesController extends BaseController implements NotificationCe req.action = new TLRPC.TL_sendMessageUploadAudioAction(); } else if (action == 10) { req.action = new TLRPC.TL_sendMessageChooseStickerAction(); + } else if (action == 11) { + TLRPC.TL_sendMessageEmojiInteractionSeen interactionSeen = new TLRPC.TL_sendMessageEmojiInteractionSeen(); + interactionSeen.emoticon = emojicon; + req.action = interactionSeen; } threads.put(threadMsgId, true); int reqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> cancelTyping(action, dialogId, threadMsgId)), ConnectionsManager.RequestFlagFailOnServerErrors); @@ -6116,7 +6122,7 @@ public class MessagesController extends BaseController implements NotificationCe if (action != 0) { return false; } - TLRPC.EncryptedChat chat = getEncryptedChat(high_id); + TLRPC.EncryptedChat chat = getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping(); req.peer = new TLRPC.TL_inputEncryptedChat(); @@ -6133,8 +6139,8 @@ public class MessagesController extends BaseController implements NotificationCe return true; } - protected void removeDeletedMessagesFromArray(final long dialog_id, ArrayList messages) { - int maxDeletedId = deletedHistory.get(dialog_id, 0); + protected void removeDeletedMessagesFromArray(final long dialogId, ArrayList messages) { + int maxDeletedId = deletedHistory.get(dialogId, 0); if (maxDeletedId == 0) { return; } @@ -6148,28 +6154,27 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void loadMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int midDate, int classGuid, int load_type, int last_message_id, boolean isChannel, int mode, int threadMessageId, int replyFirstUnread, int loadIndex) { - loadMessages(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, fromCache, midDate, classGuid, load_type, last_message_id, isChannel, mode, threadMessageId, loadIndex, threadMessageId != 0 ? replyFirstUnread : 0, 0, 0, false, 0); + public void loadMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int midDate, int classGuid, int load_type, int last_message_id, int mode, int threadMessageId, int replyFirstUnread, int loadIndex) { + loadMessages(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, fromCache, midDate, classGuid, load_type, last_message_id, mode, threadMessageId, loadIndex, threadMessageId != 0 ? replyFirstUnread : 0, 0, 0, false, 0); } - public void loadMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int midDate, int classGuid, int load_type, int last_message_id, boolean isChannel, int mode, int threadMessageId, int loadIndex, int first_unread, int unread_count, int last_date, boolean queryFromServer, int mentionsCount) { - loadMessagesInternal(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, fromCache, midDate, classGuid, load_type, last_message_id, isChannel, mode, threadMessageId, loadIndex, first_unread, unread_count, last_date, queryFromServer, mentionsCount, true, true); + public void loadMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int midDate, int classGuid, int load_type, int last_message_id, int mode, int threadMessageId, int loadIndex, int first_unread, int unread_count, int last_date, boolean queryFromServer, int mentionsCount) { + loadMessagesInternal(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, fromCache, midDate, classGuid, load_type, last_message_id, mode, threadMessageId, loadIndex, first_unread, unread_count, last_date, queryFromServer, mentionsCount, true, true); } - private void loadMessagesInternal(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int minDate, int classGuid, int load_type, int last_message_id, boolean isChannel, int mode, int threadMessageId, int loadIndex, int first_unread, int unread_count, int last_date, boolean queryFromServer, int mentionsCount, boolean loadDialog, boolean processMessages) { + private void loadMessagesInternal(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, boolean fromCache, int minDate, int classGuid, int load_type, int last_message_id, int mode, int threadMessageId, int loadIndex, int first_unread, int unread_count, int last_date, boolean queryFromServer, int mentionsCount, boolean loadDialog, boolean processMessages) { if (BuildVars.LOGS_ENABLED) { FileLog.d("load messages in chat " + dialogId + " count " + count + " max_id " + max_id + " cache " + fromCache + " mindate = " + minDate + " guid " + classGuid + " load_type " + load_type + " last_message_id " + last_message_id + " mode " + mode + " index " + loadIndex + " firstUnread " + first_unread + " unread_count " + unread_count + " last_date " + last_date + " queryFromServer " + queryFromServer); } - int lower_part = (int) dialogId; - if (threadMessageId == 0 && mode != 2 && (fromCache || lower_part == 0)) { - getMessagesStorage().getMessages(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, minDate, classGuid, load_type, isChannel, mode == 1, threadMessageId, loadIndex, processMessages); + if (threadMessageId == 0 && mode != 2 && (fromCache || DialogObject.isEncryptedDialog(dialogId))) { + getMessagesStorage().getMessages(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, minDate, classGuid, load_type, mode == 1, threadMessageId, loadIndex, processMessages); } else { if (threadMessageId != 0) { if (mode != 0) { return; } TLRPC.TL_messages_getReplies req = new TLRPC.TL_messages_getReplies(); - req.peer = getInputPeer(lower_part); + req.peer = getInputPeer(dialogId); req.msg_id = threadMessageId; req.offset_date = offset_date; if (load_type == 4) { @@ -6181,8 +6186,8 @@ public class MessagesController extends BaseController implements NotificationCe } else if (load_type == 2 && max_id != 0) { req.add_offset = -count + 10; } else { - if (lower_part < 0 && max_id != 0) { - TLRPC.Chat chat = getChat(-lower_part); + if (dialogId < 0 && max_id != 0) { + TLRPC.Chat chat = getChat(-dialogId); if (ChatObject.isChannel(chat)) { req.add_offset = -1; req.limit += 1; @@ -6193,7 +6198,7 @@ public class MessagesController extends BaseController implements NotificationCe req.offset_id = max_id; int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; + TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; if (res.messages.size() > count) { res.messages.remove(0); } @@ -6219,7 +6224,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } - processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, fnid, last_message_id, unread_count, last_date, load_type, isChannel, false, 0, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); + processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, fnid, last_message_id, unread_count, last_date, load_type, false, 0, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); } else { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.loadingMessagesFailed, classGuid, req, error)); } @@ -6229,11 +6234,11 @@ public class MessagesController extends BaseController implements NotificationCe } else if (mode == 1) { TLRPC.TL_messages_getScheduledHistory req = new TLRPC.TL_messages_getScheduledHistory(); - req.peer = getInputPeer(lower_part); + req.peer = getInputPeer(dialogId); req.hash = minDate; int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; + TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; if (res instanceof TLRPC.TL_messages_messagesNotModified) { return; } @@ -6248,14 +6253,14 @@ public class MessagesController extends BaseController implements NotificationCe } } } - processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, first_unread, last_message_id, unread_count, last_date, load_type, isChannel, false, mode, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); + processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, first_unread, last_message_id, unread_count, last_date, load_type, false, mode, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); } }); getConnectionsManager().bindRequestToGuid(reqId, classGuid); } else { if (loadDialog && (load_type == 3 || load_type == 2) && last_message_id == 0) { TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs(); - TLRPC.InputPeer inputPeer = getInputPeer((int) dialogId); + TLRPC.InputPeer inputPeer = getInputPeer(dialogId); TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer(); inputDialogPeer.peer = inputPeer; req.peers.add(inputDialogPeer); @@ -6275,7 +6280,7 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().putDialogs(dialogs, 2); } - loadMessagesInternal(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, false, minDate, classGuid, load_type, dialog.top_message, isChannel, 0, threadMessageId, loadIndex, first_unread, dialog.unread_count, last_date, queryFromServer, dialog.unread_mentions_count, false, processMessages); + loadMessagesInternal(dialogId, mergeDialogId, loadInfo, count, max_id, offset_date, false, minDate, classGuid, load_type, dialog.top_message, 0, threadMessageId, loadIndex, first_unread, dialog.unread_count, last_date, queryFromServer, dialog.unread_mentions_count, false, processMessages); } } else { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.loadingMessagesFailed, classGuid, req, error)); @@ -6284,7 +6289,7 @@ public class MessagesController extends BaseController implements NotificationCe return; } TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory(); - req.peer = getInputPeer(lower_part); + req.peer = getInputPeer(dialogId); if (load_type == 4) { req.add_offset = -count + 5; } else if (load_type == 3) { @@ -6294,8 +6299,8 @@ public class MessagesController extends BaseController implements NotificationCe } else if (load_type == 2 && max_id != 0) { req.add_offset = -count + 6; } else { - if (lower_part < 0 && max_id != 0) { - TLRPC.Chat chat = getChat(-lower_part); + if (dialogId < 0 && max_id != 0) { + TLRPC.Chat chat = getChat(-dialogId); if (ChatObject.isChannel(chat)) { req.add_offset = -1; req.limit += 1; @@ -6307,7 +6312,7 @@ public class MessagesController extends BaseController implements NotificationCe req.offset_date = offset_date; int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; + TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; removeDeletedMessagesFromArray(dialogId, res.messages); if (res.messages.size() > count) { res.messages.remove(0); @@ -6323,7 +6328,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } - processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, first_unread, last_message_id, unread_count, last_date, load_type, isChannel, false, 0, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); + processLoadedMessages(res, res.messages.size(), dialogId, mergeDialogId, count, mid, offset_date, false, classGuid, first_unread, last_message_id, unread_count, last_date, load_type, false, 0, threadMessageId, loadIndex, queryFromServer, mentionsCount, processMessages); } else { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.loadingMessagesFailed, classGuid, req, error)); } @@ -6333,13 +6338,13 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void reloadWebPages(final long dialog_id, HashMap> webpagesToReload, boolean scheduled) { + public void reloadWebPages(final long dialogId, HashMap> webpagesToReload, boolean scheduled) { HashMap> map = scheduled ? reloadingScheduledWebpages : reloadingWebpages; LongSparseArray> array = scheduled ? reloadingScheduledWebpagesPending : reloadingWebpagesPending; for (HashMap.Entry> entry : webpagesToReload.entrySet()) { - final String url = entry.getKey(); - final ArrayList messages = entry.getValue(); + String url = entry.getKey(); + ArrayList messages = entry.getValue(); ArrayList arrayList = map.get(url); if (arrayList == null) { arrayList = new ArrayList<>(); @@ -6374,22 +6379,22 @@ public class MessagesController extends BaseController implements NotificationCe } } if (!messagesRes.messages.isEmpty()) { - getMessagesStorage().putMessages(messagesRes, dialog_id, -2, 0, false, scheduled); - getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialog_id, arrayList1); + getMessagesStorage().putMessages(messagesRes, dialogId, -2, 0, false, scheduled); + getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, arrayList1); } })); } } public void processLoadedMessages(TLRPC.messages_Messages messagesRes, int resCount, long dialogId, long mergeDialogId, int count, int max_id, int offset_date, boolean isCache, int classGuid, - int first_unread, int last_message_id, int unread_count, int last_date, int load_type, boolean isChannel, boolean isEnd, int mode, int threadMessageId, int loadIndex, boolean queryFromServer, int mentionsCount, boolean needProcess) { + int first_unread, int last_message_id, int unread_count, int last_date, int load_type, boolean isEnd, int mode, int threadMessageId, int loadIndex, boolean queryFromServer, int mentionsCount, boolean needProcess) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("processLoadedMessages size " + messagesRes.messages.size() + " in chat " + dialogId + " count " + count + " max_id " + max_id + " cache " + isCache + " guid " + classGuid + " load_type " + load_type + " last_message_id " + last_message_id + " isChannel " + isChannel + " index " + loadIndex + " firstUnread " + first_unread + " unread_count " + unread_count + " last_date " + last_date + " queryFromServer " + queryFromServer); + FileLog.d("processLoadedMessages size " + messagesRes.messages.size() + " in chat " + dialogId + " count " + count + " max_id " + max_id + " cache " + isCache + " guid " + classGuid + " load_type " + load_type + " last_message_id " + last_message_id + " index " + loadIndex + " firstUnread " + first_unread + " unread_count " + unread_count + " last_date " + last_date + " queryFromServer " + queryFromServer); } long startProcessTime = SystemClock.elapsedRealtime(); boolean createDialog = false; if (messagesRes instanceof TLRPC.TL_messages_channelMessages) { - int channelId = -(int) dialogId; + long channelId = -dialogId; if (mode == 0 && threadMessageId == 0) { int channelPts = channelsPts.get(channelId); if (channelPts == 0) { @@ -6406,8 +6411,6 @@ public class MessagesController extends BaseController implements NotificationCe } } } - int lower_id = (int) dialogId; - int high_id = (int) (dialogId >> 32); if (!isCache) { ImageLoader.saveMessagesThumbs(messagesRes.messages); } @@ -6418,7 +6421,7 @@ public class MessagesController extends BaseController implements NotificationCe } else { reload = resCount == 0 && (!isInitialLoading || (SystemClock.elapsedRealtime() - lastServerQueryTime.get(dialogId, 0L)) > 60 * 1000); } - if (high_id != 1 && lower_id != 0 && isCache && reload) { + if (!DialogObject.isEncryptedDialog(dialogId) && isCache && reload) { int hash; if (mode == 2) { hash = 0; @@ -6430,22 +6433,22 @@ public class MessagesController extends BaseController implements NotificationCe if (message.id < 0) { continue; } - h = ((h * 20261) + 0x80000000L + message.id) % 0x80000000L; - h = ((h * 20261) + 0x80000000L + message.edit_date) % 0x80000000L; - h = ((h * 20261) + 0x80000000L + message.date) % 0x80000000L; + h = MediaDataController.calcHash(h, message.id); + h = MediaDataController.calcHash(h, message.edit_date); + h = MediaDataController.calcHash(h, message.date); } hash = (int) h - 1; } else { lastServerQueryTime.put(dialogId, SystemClock.elapsedRealtime()); hash = 0; } - AndroidUtilities.runOnUIThread(() -> loadMessagesInternal(dialogId, mergeDialogId, false, count, load_type == 2 && queryFromServer ? first_unread : max_id, offset_date, false, hash, classGuid, load_type, last_message_id, isChannel, mode, threadMessageId, loadIndex, first_unread, unread_count, last_date, queryFromServer, mentionsCount, true, needProcess)); + AndroidUtilities.runOnUIThread(() -> loadMessagesInternal(dialogId, mergeDialogId, false, count, load_type == 2 && queryFromServer ? first_unread : max_id, offset_date, false, hash, classGuid, load_type, last_message_id, mode, threadMessageId, loadIndex, first_unread, unread_count, last_date, queryFromServer, mentionsCount, true, needProcess)); if (messagesRes.messages.isEmpty()) { return; } } - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < messagesRes.users.size(); a++) { TLRPC.User u = messagesRes.users.get(a); usersDict.put(u.id, u); @@ -6495,13 +6498,13 @@ public class MessagesController extends BaseController implements NotificationCe } } - if (!needProcess && (int) dialogId == 0) { + if (!needProcess && DialogObject.isEncryptedDialog(dialogId)) { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.messagesDidLoadWithoutProcess, classGuid, messagesRes.messages.size(), isCache, isEnd, last_message_id)); return; } - final ArrayList objects = new ArrayList<>(); - final ArrayList messagesToReload = new ArrayList<>(); - final HashMap> webpagesToReload = new HashMap<>(); + ArrayList objects = new ArrayList<>(); + ArrayList messagesToReload = new ArrayList<>(); + HashMap> webpagesToReload = new HashMap<>(); TLRPC.InputChannel inputChannel = null; long fileProcessTime = 0; for (int a = 0; a < size; a++) { @@ -6561,7 +6564,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.scheduledMessagesUpdated, dialogId, objects.size()); } - if ((int) dialogId != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { int finalFirst_unread_final = first_unread_final; getMediaDataController().loadReplyMessagesForMessages(objects, dialogId, mode == 1, () -> { if (!needProcess) { @@ -6666,7 +6669,7 @@ public class MessagesController extends BaseController implements NotificationCe } protected void onFolderEmpty(int folderId) { - int[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); + long[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); if (dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId] == Integer.MAX_VALUE) { removeFolder(folderId); } else { @@ -6691,14 +6694,14 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_folders_editPeerFolders req = new TLRPC.TL_folders_editPeerFolders(); boolean[] folderCreated = null; - final long newTaskId; + long newTaskId; if (taskId == 0) { boolean added = false; - int selfUserId = getUserConfig().getClientUserId(); + long selfUserId = getUserConfig().getClientUserId(); int size = 0; for (int a = 0, N = dialogIds.size(); a < N; a++) { long dialogId = dialogIds.get(a); - if (!DialogObject.isPeerDialogId(dialogId) && !DialogObject.isSecretDialogId(dialogId)) { + if (!DialogObject.isChatDialog(dialogId) && !DialogObject.isUserDialog(dialogId) && !DialogObject.isEncryptedDialog(dialogId)) { continue; } if (folderId == 1 && (dialogId == selfUserId || dialogId == 777000 || isPromoDialog(dialogId, false))) { @@ -6721,12 +6724,12 @@ public class MessagesController extends BaseController implements NotificationCe folderCreated = new boolean[1]; ensureFolderDialogExists(folderId, folderCreated); } - if (DialogObject.isSecretDialogId(dialogId)) { + if (DialogObject.isEncryptedDialog(dialogId)) { getMessagesStorage().setDialogsFolderId(null, null, dialogId, folderId); } else { TLRPC.TL_inputFolderPeer folderPeer = new TLRPC.TL_inputFolderPeer(); folderPeer.folder_id = folderId; - folderPeer.peer = getInputPeer((int) dialogId); + folderPeer.peer = getInputPeer(dialogId); req.folder_peers.add(folderPeer); size += folderPeer.getObjectSize(); } @@ -6772,11 +6775,11 @@ public class MessagesController extends BaseController implements NotificationCe return folderCreated == null ? 0 : (folderCreated[0] ? 2 : 1); } - public void loadDialogs(final int folderId, final int offset, final int count, boolean fromCache) { + public void loadDialogs(final int folderId, int offset, int count, boolean fromCache) { loadDialogs(folderId, offset, count, fromCache, null); } - public void loadDialogs(final int folderId, final int offset, final int count, boolean fromCache, Runnable onEmptyCallback) { + public void loadDialogs(final int folderId, int offset, int count, boolean fromCache, Runnable onEmptyCallback) { if (loadingDialogs.get(folderId) || resetingDialogs) { return; } @@ -6795,7 +6798,7 @@ public class MessagesController extends BaseController implements NotificationCe req.flags |= 2; req.folder_id = folderId; } - int[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); + long[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); if (dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId] != -1) { if (dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId] == Integer.MAX_VALUE) { dialogsEndReached.put(folderId, true); @@ -6804,8 +6807,8 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); return; } - req.offset_id = dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId]; - req.offset_date = dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetDate]; + req.offset_id = (int) dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId]; + req.offset_date = (int) dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetDate]; if (req.offset_id == 0) { req.offset_peer = new TLRPC.TL_inputPeerEmpty(); } else { @@ -6819,7 +6822,7 @@ public class MessagesController extends BaseController implements NotificationCe req.offset_peer = new TLRPC.TL_inputPeerChat(); req.offset_peer.chat_id = dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetChatId]; } - req.offset_peer.access_hash = ((long) dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetAccess_1]) | ((long) dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetAccess_1] << 32); + req.offset_peer.access_hash = dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetAccess]; } } else { boolean found = false; @@ -6829,14 +6832,12 @@ public class MessagesController extends BaseController implements NotificationCe if (dialog.pinned) { continue; } - int lower_id = (int) dialog.id; - int high_id = (int) (dialog.id >> 32); - if (lower_id != 0 && high_id != 1 && dialog.top_message > 0) { + if (!DialogObject.isEncryptedDialog(dialog.id) && dialog.top_message > 0) { MessageObject message = dialogMessage.get(dialog.id); if (message != null && message.getId() > 0) { req.offset_date = message.messageOwner.date; req.offset_id = message.messageOwner.id; - int id; + long id; if (message.messageOwner.peer_id.channel_id != 0) { id = -message.messageOwner.peer_id.channel_id; } else if (message.messageOwner.peer_id.chat_id != 0) { @@ -6856,7 +6857,7 @@ public class MessagesController extends BaseController implements NotificationCe } getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { - final TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response; + TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response; processLoadedDialogs(dialogsRes, null, folderId, 0, count, 0, false, false, false); if (onEmptyCallback != null && dialogsRes.dialogs.isEmpty()) { AndroidUtilities.runOnUIThread(onEmptyCallback); @@ -6903,7 +6904,7 @@ public class MessagesController extends BaseController implements NotificationCe } else { req.peer = new TLRPC.TL_inputNotifyBroadcasts(); } - final int type = a; + int type = a; getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response != null) { loadingNotificationSettings--; @@ -6987,7 +6988,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationsController().deleteAllNotificationChannels(); } - protected void loadUnknownDialog(final TLRPC.InputPeer peer, final long taskId) { + protected void loadUnknownDialog(final TLRPC.InputPeer peer, long taskId) { if (peer == null) { return; } @@ -7004,7 +7005,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer(); inputDialogPeer.peer = peer; req.peers.add(inputDialogPeer); - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { @@ -7094,7 +7095,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - private void resetDialogs(boolean query, final int seq, final int newPts, final int date, final int qts) { + private void resetDialogs(boolean query, int seq, int newPts, int date, int qts) { if (query) { if (resetingDialogs) { return; @@ -7131,10 +7132,10 @@ public class MessagesController extends BaseController implements NotificationCe resetDialogsAll.users.addAll(resetDialogsPinned.users); resetDialogsAll.chats.addAll(resetDialogsPinned.chats); - final LongSparseArray new_dialogs_dict = new LongSparseArray<>(); - final LongSparseArray new_dialogMessage = new LongSparseArray<>(); - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray new_dialogs_dict = new LongSparseArray<>(); + LongSparseArray new_dialogMessage = new LongSparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < resetDialogsAll.users.size(); a++) { TLRPC.User u = resetDialogsAll.users.get(a); @@ -7181,13 +7182,13 @@ public class MessagesController extends BaseController implements NotificationCe } } if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.left) { continue; } - channelsPts.put(-(int) d.id, d.pts); - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + channelsPts.put(-d.id, d.pts); + } else if (DialogObject.isChatDialog(d.id)) { + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.migrated_to != null) { continue; } @@ -7238,7 +7239,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - protected void completeDialogsReset(final TLRPC.messages_Dialogs dialogsRes, final int messagesCount, final int seq, final int newPts, final int date, final int qts, final LongSparseArray new_dialogs_dict, final LongSparseArray new_dialogMessage, final TLRPC.Message lastMessage) { + protected void completeDialogsReset(final TLRPC.messages_Dialogs dialogsRes, int messagesCount, int seq, int newPts, int date, int qts, LongSparseArray new_dialogs_dict, LongSparseArray new_dialogMessage, TLRPC.Message lastMessage) { Utilities.stageQueue.postRunnable(() -> { gettingDifference = false; getMessagesStorage().setLastPtsValue(newPts); @@ -7250,7 +7251,7 @@ public class MessagesController extends BaseController implements NotificationCe resetingDialogs = false; applyDialogsNotificationsSettings(dialogsRes.dialogs); - final MediaDataController mediaDataController = getMediaDataController(); + MediaDataController mediaDataController = getMediaDataController(); mediaDataController.clearAllDrafts(false); mediaDataController.loadDraftsIfNeed(); @@ -7259,7 +7260,7 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0; a < allDialogs.size(); a++) { TLRPC.Dialog oldDialog = allDialogs.get(a); - if (!DialogObject.isSecretDialogId(oldDialog.id)) { + if (!DialogObject.isEncryptedDialog(oldDialog.id)) { dialogs_dict.remove(oldDialog.id); MessageObject messageObject = dialogMessage.get(oldDialog.id); dialogMessage.remove(oldDialog.id); @@ -7308,7 +7309,7 @@ public class MessagesController extends BaseController implements NotificationCe serverDialogsEndReached.put(1, false); int totalDialogsLoadCount = getUserConfig().getTotalDialogsCount(0); - int[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(0); + long[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(0); if (totalDialogsLoadCount < 400 && dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId] != -1 && dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId] != Integer.MAX_VALUE) { loadDialogs(0, 0, 100, false); } @@ -7317,7 +7318,7 @@ public class MessagesController extends BaseController implements NotificationCe }); } - private void migrateDialogs(final int offset, final int offsetDate, final int offsetUser, final int offsetChat, final int offsetChannel, final long accessPeer) { + private void migrateDialogs(int offset, int offsetDate, long offsetUser, long offsetChat, long offsetChannel, long accessPeer) { if (migratingDialogs || offset == -1) { return; } @@ -7348,7 +7349,7 @@ public class MessagesController extends BaseController implements NotificationCe } getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { - final TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response; + TLRPC.messages_Dialogs dialogsRes = (TLRPC.messages_Dialogs) response; getMessagesStorage().getStorageQueue().postRunnable(() -> { try { int offsetId; @@ -7425,7 +7426,7 @@ public class MessagesController extends BaseController implements NotificationCe if (BuildVars.LOGS_ENABLED) { FileLog.d("migrate found missing dialogs " + dialogsRes.dialogs.size()); } - cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT min(date) FROM dialogs WHERE date != 0 AND did >> 32 IN (0, -1)"); + cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT min(date) FROM dialogs WHERE date != 0 AND did >> 32 NOT IN (536870912, 1073741824)"); if (cursor.next()) { int date = Math.max(1441062000, cursor.intValue(0)); for (int a = 0; a < dialogsRes.messages.size(); a++) { @@ -7526,17 +7527,17 @@ public class MessagesController extends BaseController implements NotificationCe private int DIALOGS_LOAD_TYPE_CHANNEL = 2; private int DIALOGS_LOAD_TYPE_UNKNOWN = 3; - public void processLoadedDialogs(final TLRPC.messages_Dialogs dialogsRes, final ArrayList encChats, final int folderId, final int offset, final int count, final int loadType, final boolean resetEnd, final boolean migrate, final boolean fromCache) { + public void processLoadedDialogs(final TLRPC.messages_Dialogs dialogsRes, ArrayList encChats, int folderId, int offset, int count, int loadType, boolean resetEnd, boolean migrate, boolean fromCache) { Utilities.stageQueue.postRunnable(() -> { if (!firstGettingTask) { - getNewDeleteTask(null, 0, false); + getNewDeleteTask(null, null); firstGettingTask = true; } if (BuildVars.LOGS_ENABLED) { FileLog.d("loaded folderId " + folderId + " loadType " + loadType + " count " + dialogsRes.dialogs.size()); } - int[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); + long[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(folderId); if (loadType == DIALOGS_LOAD_TYPE_CACHE && dialogsRes.dialogs.size() == 0) { AndroidUtilities.runOnUIThread(() -> { putUsers(dialogsRes.users, true); @@ -7555,11 +7556,11 @@ public class MessagesController extends BaseController implements NotificationCe return; } - final LongSparseArray new_dialogs_dict = new LongSparseArray<>(); - final SparseArray enc_chats_dict; - final LongSparseArray new_dialogMessage = new LongSparseArray<>(); - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray new_dialogs_dict = new LongSparseArray<>(); + SparseArray enc_chats_dict; + LongSparseArray new_dialogMessage = new LongSparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < dialogsRes.users.size(); a++) { TLRPC.User u = dialogsRes.users.get(a); @@ -7607,9 +7608,9 @@ public class MessagesController extends BaseController implements NotificationCe int totalDialogsLoadCount = getUserConfig().getTotalDialogsCount(folderId); int dialogsLoadOffsetId; int dialogsLoadOffsetDate = 0; - int dialogsLoadOffsetChannelId = 0; - int dialogsLoadOffsetChatId = 0; - int dialogsLoadOffsetUserId = 0; + long dialogsLoadOffsetChannelId = 0; + long dialogsLoadOffsetChatId = 0; + long dialogsLoadOffsetUserId = 0; long dialogsLoadOffsetAccess = 0; if (lastMessage != null && lastMessage.id != dialogsLoadOffset[UserConfig.i_dialogsLoadOffsetId]) { totalDialogsLoadCount += dialogsRes.dialogs.size(); @@ -7663,17 +7664,15 @@ public class MessagesController extends BaseController implements NotificationCe getUserConfig().saveConfig(false); } - final ArrayList dialogsToReload = new ArrayList<>(); + ArrayList dialogsToReload = new ArrayList<>(); for (int a = 0; a < dialogsRes.dialogs.size(); a++) { TLRPC.Dialog d = dialogsRes.dialogs.get(a); DialogObject.initDialog(d); if (d.id == 0) { continue; } - int lower_id = (int) d.id; - int high_id = (int) (d.id >> 32); - if (lower_id == 0 && enc_chats_dict != null) { - if (enc_chats_dict.get(high_id) == null) { + if (DialogObject.isEncryptedDialog(d.id) && enc_chats_dict != null) { + if (enc_chats_dict.get(DialogObject.getEncryptedChatId(d.id)) == null) { continue; } } @@ -7688,7 +7687,7 @@ public class MessagesController extends BaseController implements NotificationCe } boolean allowCheck = true; if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null) { if (!chat.megagroup) { allowCheck = false; @@ -7697,9 +7696,9 @@ public class MessagesController extends BaseController implements NotificationCe continue; } } - channelsPts.put(-(int) d.id, d.pts); - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + channelsPts.put(-d.id, d.pts); + } else if (DialogObject.isChatDialog(d.id)) { + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && (chat.migrated_to != null || ChatObject.isNotInChat(chat))) { continue; } @@ -7885,7 +7884,7 @@ public class MessagesController extends BaseController implements NotificationCe dialogsEndReached.put(folderId, (dialogsRes.dialogs.size() == 0 || dialogsRes.dialogs.size() != count) && loadType == 0); if (archivedDialogsCount > 0 && archivedDialogsCount < 20 && folderId == 0) { dialogsEndReached.put(1, true); - int[] dialogsLoadOffsetArchived = getUserConfig().getDialogLoadOffsets(folderId); + long[] dialogsLoadOffsetArchived = getUserConfig().getDialogLoadOffsets(folderId); if (dialogsLoadOffsetArchived[UserConfig.i_dialogsLoadOffsetId] == Integer.MAX_VALUE) { serverDialogsEndReached.put(1, true); } @@ -7896,7 +7895,7 @@ public class MessagesController extends BaseController implements NotificationCe } } int totalDialogsLoadCount = getUserConfig().getTotalDialogsCount(folderId); - int[] dialogsLoadOffset2 = getUserConfig().getDialogLoadOffsets(folderId); + long[] dialogsLoadOffset2 = getUserConfig().getDialogLoadOffsets(folderId); if (!fromCache && !migrate && totalDialogsLoadCount < 400 && dialogsLoadOffset2[UserConfig.i_dialogsLoadOffsetId] != -1 && dialogsLoadOffset2[UserConfig.i_dialogsLoadOffsetId] != Integer.MAX_VALUE) { loadDialogs(folderId, 0, 100, false); } @@ -7922,22 +7921,22 @@ public class MessagesController extends BaseController implements NotificationCe }); } - private void applyDialogNotificationsSettings(long dialog_id, TLRPC.PeerNotifySettings notify_settings) { + private void applyDialogNotificationsSettings(long dialogId, TLRPC.PeerNotifySettings notify_settings) { if (notify_settings == null) { return; } - int currentValue = notificationsPreferences.getInt("notify2_" + dialog_id, -1); - int currentValue2 = notificationsPreferences.getInt("notifyuntil_" + dialog_id, 0); + int currentValue = notificationsPreferences.getInt("notify2_" + dialogId, -1); + int currentValue2 = notificationsPreferences.getInt("notifyuntil_" + dialogId, 0); SharedPreferences.Editor editor = notificationsPreferences.edit(); boolean updated = false; - TLRPC.Dialog dialog = dialogs_dict.get(dialog_id); + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null) { dialog.notify_settings = notify_settings; } if ((notify_settings.flags & 2) != 0) { - editor.putBoolean("silent_" + dialog_id, notify_settings.silent); + editor.putBoolean("silent_" + dialogId, notify_settings.silent); } else { - editor.remove("silent_" + dialog_id); + editor.remove("silent_" + dialogId); } if ((notify_settings.flags & 4) != 0) { if (notify_settings.mute_until > getConnectionsManager().getCurrentTime()) { @@ -7945,7 +7944,7 @@ public class MessagesController extends BaseController implements NotificationCe if (notify_settings.mute_until > getConnectionsManager().getCurrentTime() + 60 * 60 * 24 * 365) { if (currentValue != 2) { updated = true; - editor.putInt("notify2_" + dialog_id, 2); + editor.putInt("notify2_" + dialogId, 2); if (dialog != null) { dialog.notify_settings.mute_until = Integer.MAX_VALUE; } @@ -7953,25 +7952,25 @@ public class MessagesController extends BaseController implements NotificationCe } else { if (currentValue != 3 || currentValue2 != notify_settings.mute_until) { updated = true; - editor.putInt("notify2_" + dialog_id, 3); - editor.putInt("notifyuntil_" + dialog_id, notify_settings.mute_until); + editor.putInt("notify2_" + dialogId, 3); + editor.putInt("notifyuntil_" + dialogId, notify_settings.mute_until); if (dialog != null) { dialog.notify_settings.mute_until = until; } } until = notify_settings.mute_until; } - getMessagesStorage().setDialogFlags(dialog_id, ((long) until << 32) | 1); - getNotificationsController().removeNotificationsForDialog(dialog_id); + getMessagesStorage().setDialogFlags(dialogId, ((long) until << 32) | 1); + getNotificationsController().removeNotificationsForDialog(dialogId); } else { if (currentValue != 0 && currentValue != 1) { updated = true; if (dialog != null) { dialog.notify_settings.mute_until = 0; } - editor.putInt("notify2_" + dialog_id, 0); + editor.putInt("notify2_" + dialogId, 0); } - getMessagesStorage().setDialogFlags(dialog_id, 0); + getMessagesStorage().setDialogFlags(dialogId, 0); } } else { if (currentValue != -1) { @@ -7979,9 +7978,9 @@ public class MessagesController extends BaseController implements NotificationCe if (dialog != null) { dialog.notify_settings.mute_until = 0; } - editor.remove("notify2_" + dialog_id); + editor.remove("notify2_" + dialogId); } - getMessagesStorage().setDialogFlags(dialog_id, 0); + getMessagesStorage().setDialogFlags(dialogId, 0); } editor.commit(); if (updated) { @@ -7997,33 +7996,26 @@ public class MessagesController extends BaseController implements NotificationCe if (editor == null) { editor = notificationsPreferences.edit(); } - int dialog_id; - if (dialog.peer.user_id != 0) { - dialog_id = dialog.peer.user_id; - } else if (dialog.peer.chat_id != 0) { - dialog_id = -dialog.peer.chat_id; - } else { - dialog_id = -dialog.peer.channel_id; - } + long dialogId = MessageObject.getPeerId(dialog.peer); if ((dialog.notify_settings.flags & 2) != 0) { - editor.putBoolean("silent_" + dialog_id, dialog.notify_settings.silent); + editor.putBoolean("silent_" + dialogId, dialog.notify_settings.silent); } else { - editor.remove("silent_" + dialog_id); + editor.remove("silent_" + dialogId); } if ((dialog.notify_settings.flags & 4) != 0) { if (dialog.notify_settings.mute_until > getConnectionsManager().getCurrentTime()) { if (dialog.notify_settings.mute_until > getConnectionsManager().getCurrentTime() + 60 * 60 * 24 * 365) { - editor.putInt("notify2_" + dialog_id, 2); + editor.putInt("notify2_" + dialogId, 2); dialog.notify_settings.mute_until = Integer.MAX_VALUE; } else { - editor.putInt("notify2_" + dialog_id, 3); - editor.putInt("notifyuntil_" + dialog_id, dialog.notify_settings.mute_until); + editor.putInt("notify2_" + dialogId, 3); + editor.putInt("notifyuntil_" + dialogId, dialog.notify_settings.mute_until); } } else { - editor.putInt("notify2_" + dialog_id, 0); + editor.putInt("notify2_" + dialogId, 0); } } else { - editor.remove("notify2_" + dialog_id); + editor.remove("notify2_" + dialogId); } } } @@ -8032,8 +8024,8 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void reloadMentionsCountForChannel(TLRPC.InputPeer peer, final long taskId) { - final long newTaskId; + public void reloadMentionsCountForChannel(TLRPC.InputPeer peer, long taskId) { + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { @@ -8067,16 +8059,16 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void reloadMentionsCountForChannels(final ArrayList arrayList) { + public void reloadMentionsCountForChannels(final ArrayList arrayList) { AndroidUtilities.runOnUIThread(() -> { for (int a = 0; a < arrayList.size(); a++) { - final long dialog_id = -arrayList.get(a); - reloadMentionsCountForChannel(getInputPeer((int) dialog_id), 0); + long dialogId = -arrayList.get(a); + reloadMentionsCountForChannel(getInputPeer(dialogId), 0); } }); } - public void processDialogsUpdateRead(final LongSparseArray dialogsToUpdate, final LongSparseArray dialogsMentionsToUpdate) { + public void processDialogsUpdateRead(final LongSparseIntArray dialogsToUpdate, LongSparseIntArray dialogsMentionsToUpdate) { AndroidUtilities.runOnUIThread(() -> { boolean filterDialogsChanged = false; if (dialogsToUpdate != null) { @@ -8145,23 +8137,22 @@ public class MessagesController extends BaseController implements NotificationCe }); } - protected void checkLastDialogMessage(final TLRPC.Dialog dialog, final TLRPC.InputPeer peer, long taskId) { - final int lower_id = (int) dialog.id; - if (lower_id == 0 || checkingLastMessagesDialogs.indexOfKey(lower_id) >= 0) { + protected void checkLastDialogMessage(TLRPC.Dialog dialog, TLRPC.InputPeer peer, long taskId) { + if (DialogObject.isEncryptedDialog(dialog.id) || checkingLastMessagesDialogs.indexOfKey(dialog.id) >= 0) { return; } TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory(); - req.peer = peer == null ? getInputPeer(lower_id) : peer; + req.peer = peer == null ? getInputPeer(dialog.id) : peer; if (req.peer == null) { return; } req.limit = 1; - checkingLastMessagesDialogs.put(lower_id, true); + checkingLastMessagesDialogs.put(dialog.id, true); if (BuildVars.LOGS_ENABLED) { - FileLog.d("checkLastDialogMessage for " + lower_id); + FileLog.d("checkLastDialogMessage for " + dialog.id); } - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { @@ -8192,10 +8183,10 @@ public class MessagesController extends BaseController implements NotificationCe getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; - removeDeletedMessagesFromArray(lower_id, res.messages); + removeDeletedMessagesFromArray(dialog.id, res.messages); if (!res.messages.isEmpty()) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("checkLastDialogMessage for " + lower_id + " has message"); + FileLog.d("checkLastDialogMessage for " + dialog.id + " has message"); } TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs(); TLRPC.Message newMessage = res.messages.get(0); @@ -8224,18 +8215,18 @@ public class MessagesController extends BaseController implements NotificationCe } else { AndroidUtilities.runOnUIThread(() -> { if (BuildVars.LOGS_ENABLED) { - FileLog.d("checkLastDialogMessage for " + lower_id + " has not message"); + FileLog.d("checkLastDialogMessage for " + dialog.id + " has not message"); } if (getMediaDataController().getDraft(dialog.id, 0) == null) { TLRPC.Dialog currentDialog = dialogs_dict.get(dialog.id); if (currentDialog == null) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("checkLastDialogMessage for " + lower_id + " current dialog not found"); + FileLog.d("checkLastDialogMessage for " + dialog.id + " current dialog not found"); } getMessagesStorage().isDialogHasTopMessage(dialog.id, () -> deleteDialog(dialog.id, 3)); } else { if (BuildVars.LOGS_ENABLED) { - FileLog.d("checkLastDialogMessage for " + lower_id + " current dialog top message " + currentDialog.top_message); + FileLog.d("checkLastDialogMessage for " + dialog.id + " current dialog top message " + currentDialog.top_message); } if (currentDialog.top_message == 0) { deleteDialog(dialog.id, 3); @@ -8248,17 +8239,17 @@ public class MessagesController extends BaseController implements NotificationCe if (newTaskId != 0) { getMessagesStorage().removePendingTask(newTaskId); } - AndroidUtilities.runOnUIThread(() -> checkingLastMessagesDialogs.delete(lower_id)); + AndroidUtilities.runOnUIThread(() -> checkingLastMessagesDialogs.delete(dialog.id)); }); } public void processDialogsUpdate(final TLRPC.messages_Dialogs dialogsRes, ArrayList encChats, boolean fromCache) { Utilities.stageQueue.postRunnable(() -> { - final LongSparseArray new_dialogs_dict = new LongSparseArray<>(); - final LongSparseArray new_dialogMessage = new LongSparseArray<>(); - final SparseArray usersDict = new SparseArray<>(dialogsRes.users.size()); - final SparseArray chatsDict = new SparseArray<>(dialogsRes.chats.size()); - final LongSparseArray dialogsToUpdate = new LongSparseArray<>(); + LongSparseArray new_dialogs_dict = new LongSparseArray<>(); + LongSparseArray new_dialogMessage = new LongSparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(dialogsRes.users.size()); + LongSparseArray chatsDict = new LongSparseArray<>(dialogsRes.chats.size()); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(); for (int a = 0; a < dialogsRes.users.size(); a++) { TLRPC.User u = dialogsRes.users.get(a); @@ -8292,12 +8283,12 @@ public class MessagesController extends BaseController implements NotificationCe DialogObject.initDialog(d); if (promoDialogId == 0 || promoDialogId != d.id) { if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && ChatObject.isNotInChat(chat)) { continue; } - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + } else if (DialogObject.isChatDialog(d.id)) { + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && (chat.migrated_to != null || ChatObject.isNotInChat(chat))) { continue; } @@ -8451,7 +8442,7 @@ public class MessagesController extends BaseController implements NotificationCe public void addToViewsQueue(MessageObject messageObject) { Utilities.stageQueue.postRunnable(() -> { - int peer = (int) messageObject.getDialogId(); + long peer = messageObject.getDialogId(); int id = messageObject.getId(); ArrayList ids = channelViewsToSend.get(peer); if (ids == null) { @@ -8506,21 +8497,18 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void markMessageContentAsRead(final MessageObject messageObject) { + public void markMessageContentAsRead(MessageObject messageObject) { if (messageObject.scheduled) { return; } - ArrayList arrayList = new ArrayList<>(); - long messageId = messageObject.getId(); - if (messageObject.messageOwner.peer_id.channel_id != 0) { - messageId |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; - } + ArrayList arrayList = new ArrayList<>(); if (messageObject.messageOwner.mentioned) { - getMessagesStorage().markMentionMessageAsRead(messageObject.getId(), messageObject.messageOwner.peer_id.channel_id, messageObject.getDialogId()); + getMessagesStorage().markMentionMessageAsRead(-messageObject.messageOwner.peer_id.channel_id, messageObject.getId(), messageObject.getDialogId()); } - arrayList.add(messageId); - getMessagesStorage().markMessagesContentAsRead(arrayList, 0); - getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, arrayList); + arrayList.add(messageObject.getId()); + long dialogId = messageObject.getDialogId(); + getMessagesStorage().markMessagesContentAsRead(dialogId, arrayList, 0); + getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, dialogId, arrayList); if (messageObject.getId() < 0) { markMessageAsRead(messageObject.getDialogId(), messageObject.messageOwner.random_id, Integer.MIN_VALUE); } else { @@ -8547,8 +8535,8 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void markMentionMessageAsRead(final int mid, final int channelId, final long did) { - getMessagesStorage().markMentionMessageAsRead(mid, channelId, did); + public void markMentionMessageAsRead(int mid, long channelId, long did) { + getMessagesStorage().markMentionMessageAsRead(-channelId, mid, did); if (channelId != 0) { TLRPC.TL_channels_readMessageContents req = new TLRPC.TL_channels_readMessageContents(); req.channel = getInputChannel(channelId); @@ -8571,26 +8559,26 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void markMessageAsRead(final int mid, final int channelId, TLRPC.InputChannel inputChannel, int ttl, long taskId) { + public void markMessageAsRead2(long dialogId, int mid, TLRPC.InputChannel inputChannel, int ttl, long taskId) { if (mid == 0 || ttl <= 0) { return; } - if (channelId != 0 && inputChannel == null) { - inputChannel = getInputChannel(channelId); + if (DialogObject.isChatDialog(dialogId) && inputChannel == null) { + inputChannel = getInputChannel(dialogId); if (inputChannel == null) { return; } } - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { - data = new NativeByteBuffer(16 + (inputChannel != null ? inputChannel.getObjectSize() : 0)); - data.writeInt32(11); + data = new NativeByteBuffer(20 + (inputChannel != null ? inputChannel.getObjectSize() : 0)); + data.writeInt32(23); + data.writeInt64(dialogId); data.writeInt32(mid); - data.writeInt32(channelId); data.writeInt32(ttl); - if (channelId != 0) { + if (inputChannel != null) { inputChannel.serializeToStream(data); } } catch (Exception e) { @@ -8601,8 +8589,8 @@ public class MessagesController extends BaseController implements NotificationCe newTaskId = taskId; } int time = getConnectionsManager().getCurrentTime(); - getMessagesStorage().createTaskForMid(mid, channelId, time, time, ttl, false); - if (channelId != 0) { + getMessagesStorage().createTaskForMid(dialogId, mid, time, time, ttl, false); + if (inputChannel != null) { TLRPC.TL_channels_readMessageContents req = new TLRPC.TL_channels_readMessageContents(); req.channel = inputChannel; req.id.add(mid); @@ -8626,46 +8614,41 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void markMessageAsRead(final long dialog_id, final long random_id, int ttl) { - if (random_id == 0 || dialog_id == 0 || ttl <= 0 && ttl != Integer.MIN_VALUE) { + public void markMessageAsRead(long dialogId, long randomId, int ttl) { + if (randomId == 0 || dialogId == 0 || ttl <= 0 && ttl != Integer.MIN_VALUE) { return; } - int lower_part = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { return; } - TLRPC.EncryptedChat chat = getEncryptedChat(high_id); + TLRPC.EncryptedChat chat = getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (chat == null) { return; } - ArrayList random_ids = new ArrayList<>(); - random_ids.add(random_id); - getSecretChatHelper().sendMessagesReadMessage(chat, random_ids, null); + ArrayList randomIds = new ArrayList<>(); + randomIds.add(randomId); + getSecretChatHelper().sendMessagesReadMessage(chat, randomIds, null); if (ttl > 0) { int time = getConnectionsManager().getCurrentTime(); - getMessagesStorage().createTaskForSecretChat(chat.id, time, time, 0, random_ids); + getMessagesStorage().createTaskForSecretChat(chat.id, time, time, 0, randomIds); } } private void completeReadTask(ReadTask task) { - int lower_part = (int) task.dialogId; - int high_id = (int) (task.dialogId >> 32); - if (task.replyId != 0) { TLRPC.TL_messages_readDiscussion req = new TLRPC.TL_messages_readDiscussion(); req.msg_id = (int) task.replyId; - req.peer = getInputPeer(lower_part); + req.peer = getInputPeer(task.dialogId); req.read_max_id = task.maxId; getConnectionsManager().sendRequest(req, (response, error) -> { }); - } else if (lower_part != 0) { - TLRPC.InputPeer inputPeer = getInputPeer(lower_part); + } else if (!DialogObject.isEncryptedDialog(task.dialogId)) { + TLRPC.InputPeer inputPeer = getInputPeer(task.dialogId); TLObject req; if (inputPeer instanceof TLRPC.TL_inputPeerChannel) { TLRPC.TL_channels_readHistory request = new TLRPC.TL_channels_readHistory(); - request.channel = getInputChannel(-lower_part); + request.channel = getInputChannel(-task.dialogId); request.max_id = task.maxId; req = request; } else { @@ -8683,7 +8666,7 @@ public class MessagesController extends BaseController implements NotificationCe } }); } else { - TLRPC.EncryptedChat chat = getEncryptedChat(high_id); + TLRPC.EncryptedChat chat = getEncryptedChat(DialogObject.getEncryptedChatId(task.dialogId)); if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { TLRPC.TL_messages_readEncryptedHistory req = new TLRPC.TL_messages_readEncryptedHistory(); req.peer = new TLRPC.TL_inputEncryptedChat(); @@ -8717,22 +8700,23 @@ public class MessagesController extends BaseController implements NotificationCe } completeReadTask(task); repliesReadTasks.remove(a); - threadsReadTasksMap.remove(task.replyId); + threadsReadTasksMap.remove(task.dialogId + "_" + task.replyId); a--; size--; } } - public void markDialogAsReadNow(final long dialogId, long replyId) { + public void markDialogAsReadNow(long dialogId, int replyId) { Utilities.stageQueue.postRunnable(() -> { if (replyId != 0) { - ReadTask currentReadTask = threadsReadTasksMap.get(replyId); + String key = dialogId + "_" + replyId; + ReadTask currentReadTask = threadsReadTasksMap.get(key); if (currentReadTask == null) { return; } completeReadTask(currentReadTask); repliesReadTasks.remove(currentReadTask); - threadsReadTasksMap.remove(replyId); + threadsReadTasksMap.remove(key); } else { ReadTask currentReadTask = readTasksMap.get(dialogId); if (currentReadTask == null) { @@ -8746,48 +8730,35 @@ public class MessagesController extends BaseController implements NotificationCe } public void markMentionsAsRead(long dialogId) { - if ((int) dialogId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { return; } getMessagesStorage().resetMentionsCount(dialogId, 0); TLRPC.TL_messages_readMentions req = new TLRPC.TL_messages_readMentions(); - req.peer = getInputPeer((int) dialogId); + req.peer = getInputPeer(dialogId); getConnectionsManager().sendRequest(req, (response, error) -> { }); } - public void markDialogAsRead(long dialogId, int maxPositiveId, int maxNegativeId, int maxDate, boolean popup, long threadId, int countDiff, boolean readNow, int scheduledCount) { - int lower_part = (int) dialogId; - int high_id = (int) (dialogId >> 32); + public void markDialogAsRead(long dialogId, int maxPositiveId, int maxNegativeId, int maxDate, boolean popup, int threadId, int countDiff, boolean readNow, int scheduledCount) { boolean createReadTask; if (threadId != 0) { createReadTask = maxPositiveId != Integer.MAX_VALUE; } else { boolean countMessages = getNotificationsController().showBadgeMessages; - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if (maxPositiveId == 0) { return; } - long maxMessageId = maxPositiveId; - long minMessageId = maxNegativeId; - boolean isChannel = false; - if (lower_part < 0) { - TLRPC.Chat chat = getChat(-lower_part); - if (ChatObject.isChannel(chat)) { - maxMessageId |= ((long) -lower_part) << 32; - minMessageId |= ((long) -lower_part) << 32; - isChannel = true; - } - } Integer value = dialogs_read_inbox_max.get(dialogId); if (value == null) { value = 0; } dialogs_read_inbox_max.put(dialogId, Math.max(value, maxPositiveId)); - getMessagesStorage().processPendingRead(dialogId, maxMessageId, minMessageId, isChannel, scheduledCount); + getMessagesStorage().processPendingRead(dialogId, maxPositiveId, maxNegativeId, scheduledCount); getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null) { @@ -8822,12 +8793,12 @@ public class MessagesController extends BaseController implements NotificationCe } if (!popup) { getNotificationsController().processReadMessages(null, dialogId, 0, maxPositiveId, false); - LongSparseArray dialogsToUpdate = new LongSparseArray<>(1); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1); dialogsToUpdate.put(dialogId, 0); getNotificationsController().processDialogsUpdateRead(dialogsToUpdate); } else { getNotificationsController().processReadMessages(null, dialogId, 0, maxPositiveId, true); - LongSparseArray dialogsToUpdate = new LongSparseArray<>(1); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1); dialogsToUpdate.put(dialogId, -1); getNotificationsController().processDialogsUpdateRead(dialogsToUpdate); } @@ -8840,8 +8811,8 @@ public class MessagesController extends BaseController implements NotificationCe } createReadTask = true; - TLRPC.EncryptedChat chat = getEncryptedChat(high_id); - getMessagesStorage().processPendingRead(dialogId, maxPositiveId, maxNegativeId, false, scheduledCount); + TLRPC.EncryptedChat chat = getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); + getMessagesStorage().processPendingRead(dialogId, maxPositiveId, maxNegativeId, scheduledCount); getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { getNotificationsController().processReadMessages(null, dialogId, maxDate, 0, popup); TLRPC.Dialog dialog = dialogs_dict.get(dialogId); @@ -8874,7 +8845,7 @@ public class MessagesController extends BaseController implements NotificationCe } getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE); } - LongSparseArray dialogsToUpdate = new LongSparseArray<>(1); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1); dialogsToUpdate.put(dialogId, 0); getNotificationsController().processDialogsUpdateRead(dialogsToUpdate); })); @@ -8890,7 +8861,7 @@ public class MessagesController extends BaseController implements NotificationCe Utilities.stageQueue.postRunnable(() -> { ReadTask currentReadTask; if (threadId != 0) { - currentReadTask = threadsReadTasksMap.get(threadId); + currentReadTask = threadsReadTasksMap.get(dialogId + "_" + threadId); } else { currentReadTask = readTasksMap.get(dialogId); } @@ -8901,7 +8872,7 @@ public class MessagesController extends BaseController implements NotificationCe currentReadTask.sendRequestTime = SystemClock.elapsedRealtime() + 5000; if (!readNow) { if (threadId != 0) { - threadsReadTasksMap.put(threadId, currentReadTask); + threadsReadTasksMap.put(dialogId + "_" + threadId, currentReadTask); repliesReadTasks.add(currentReadTask); } else { readTasksMap.put(dialogId, currentReadTask); @@ -8918,9 +8889,9 @@ public class MessagesController extends BaseController implements NotificationCe } } - public int createChat(String title, ArrayList selectedContacts, final String about, int type, boolean forImport, Location location, String locationAddress, final BaseFragment fragment) { + public int createChat(String title, ArrayList selectedContacts, String about, int type, boolean forImport, Location location, String locationAddress, BaseFragment fragment) { if (type == ChatObject.CHAT_TYPE_CHAT && !forImport) { - final TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat(); + TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat(); req.title = title; for (int a = 0; a < selectedContacts.size(); a++) { TLRPC.User user = getUser(selectedContacts.get(a)); @@ -8937,7 +8908,7 @@ public class MessagesController extends BaseController implements NotificationCe }); return; } - final TLRPC.Updates updates = (TLRPC.Updates) response; + TLRPC.Updates updates = (TLRPC.Updates) response; processUpdates(updates, false); AndroidUtilities.runOnUIThread(() -> { putUsers(updates.users, false); @@ -8950,7 +8921,7 @@ public class MessagesController extends BaseController implements NotificationCe }); }, ConnectionsManager.RequestFlagFailOnServerErrors); } else if (forImport || type == ChatObject.CHAT_TYPE_CHANNEL || type == ChatObject.CHAT_TYPE_MEGAGROUP) { - final TLRPC.TL_channels_createChannel req = new TLRPC.TL_channels_createChannel(); + TLRPC.TL_channels_createChannel req = new TLRPC.TL_channels_createChannel(); req.title = title; req.about = about != null ? about : ""; req.for_import = forImport; @@ -8974,7 +8945,7 @@ public class MessagesController extends BaseController implements NotificationCe }); return; } - final TLRPC.Updates updates = (TLRPC.Updates) response; + TLRPC.Updates updates = (TLRPC.Updates) response; processUpdates(updates, false); AndroidUtilities.runOnUIThread(() -> { putUsers(updates.users, false); @@ -8990,11 +8961,11 @@ public class MessagesController extends BaseController implements NotificationCe return 0; } - public void convertToMegaGroup(final Context context, int chat_id, BaseFragment fragment, MessagesStorage.IntCallback convertRunnable) { + public void convertToMegaGroup(Context context, long chatId, BaseFragment fragment, MessagesStorage.LongCallback convertRunnable) { TLRPC.TL_messages_migrateChat req = new TLRPC.TL_messages_migrateChat(); - req.chat_id = chat_id; - final AlertDialog progressDialog = context != null ? new AlertDialog(context, 3) : null; - final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { + req.chat_id = chatId; + AlertDialog progressDialog = context != null ? new AlertDialog(context, 3) : null; + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { if (context != null) { AndroidUtilities.runOnUIThread(() -> { @@ -9051,8 +9022,8 @@ public class MessagesController extends BaseController implements NotificationCe public void convertToGigaGroup(final Context context, TLRPC.Chat chat, BaseFragment fragment, MessagesStorage.BooleanCallback convertRunnable) { TLRPC.TL_channels_convertToGigagroup req = new TLRPC.TL_channels_convertToGigagroup(); req.channel = getInputChannel(chat); - final AlertDialog progressDialog = context != null ? new AlertDialog(context, 3) : null; - final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { + AlertDialog progressDialog = context != null ? new AlertDialog(context, 3) : null; + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { if (context != null) { AndroidUtilities.runOnUIThread(() -> { @@ -9100,12 +9071,12 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void addUsersToChannel(int chat_id, ArrayList users, final BaseFragment fragment) { + public void addUsersToChannel(long chatId, ArrayList users, BaseFragment fragment) { if (users == null || users.isEmpty()) { return; } - final TLRPC.TL_channels_inviteToChannel req = new TLRPC.TL_channels_inviteToChannel(); - req.channel = getInputChannel(chat_id); + TLRPC.TL_channels_inviteToChannel req = new TLRPC.TL_channels_inviteToChannel(); + req.channel = getInputChannel(chatId); req.users = users; getConnectionsManager().sendRequest(req, (response, error) -> { if (error != null) { @@ -9116,9 +9087,9 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void toogleChannelSignatures(int chat_id, boolean enabled) { + public void toogleChannelSignatures(long chatId, boolean enabled) { TLRPC.TL_channels_toggleSignatures req = new TLRPC.TL_channels_toggleSignatures(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); req.enabled = enabled; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { @@ -9128,9 +9099,9 @@ public class MessagesController extends BaseController implements NotificationCe }, ConnectionsManager.RequestFlagInvokeAfter); } - public void toogleChannelInvitesHistory(int chat_id, boolean enabled) { + public void toogleChannelInvitesHistory(long chatId, boolean enabled) { TLRPC.TL_channels_togglePreHistoryHidden req = new TLRPC.TL_channels_togglePreHistoryHidden(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); req.enabled = enabled; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { @@ -9140,9 +9111,9 @@ public class MessagesController extends BaseController implements NotificationCe }, ConnectionsManager.RequestFlagInvokeAfter); } - public void updateChatAbout(int chat_id, final String about, final TLRPC.ChatFull info) { + public void updateChatAbout(long chatId, String about, TLRPC.ChatFull info) { TLRPC.TL_messages_editChatAbout req = new TLRPC.TL_messages_editChatAbout(); - req.peer = getInputPeer(-chat_id); + req.peer = getInputPeer(-chatId); req.about = about; getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_boolTrue && info != null) { @@ -9155,14 +9126,14 @@ public class MessagesController extends BaseController implements NotificationCe }, ConnectionsManager.RequestFlagInvokeAfter); } - public void updateChannelUserName(final int chat_id, final String userName) { + public void updateChannelUserName(long chatId, String userName) { TLRPC.TL_channels_updateUsername req = new TLRPC.TL_channels_updateUsername(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); req.username = userName; getConnectionsManager().sendRequest(req, (response, error) -> { if (response instanceof TLRPC.TL_boolTrue) { AndroidUtilities.runOnUIThread(() -> { - TLRPC.Chat chat = getChat(chat_id); + TLRPC.Chat chat = getChat(chatId); if (userName.length() != 0) { chat.flags |= TLRPC.CHAT_FLAG_IS_PUBLIC; } else { @@ -9195,40 +9166,40 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public boolean isJoiningChannel(final int chat_id) { - return joiningToChannels.contains(chat_id); + public boolean isJoiningChannel(long chatId) { + return joiningToChannels.contains(chatId); } - public void addUserToChat(final int chat_id, final TLRPC.User user, int count_fwd, String botHash, final BaseFragment fragment, final Runnable onFinishRunnable) { + public void addUserToChat(long chatId, TLRPC.User user, int forwardCount, String botHash, BaseFragment fragment, Runnable onFinishRunnable) { if (user == null) { return; } - final TLObject request; + TLObject request; - final boolean isChannel = ChatObject.isChannel(chat_id, currentAccount); - final boolean isMegagroup = isChannel && getChat(chat_id).megagroup; - final TLRPC.InputUser inputUser = getInputUser(user); + boolean isChannel = ChatObject.isChannel(chatId, currentAccount); + boolean isMegagroup = isChannel && getChat(chatId).megagroup; + TLRPC.InputUser inputUser = getInputUser(user); if (botHash == null || isChannel && !isMegagroup) { if (isChannel) { if (inputUser instanceof TLRPC.TL_inputUserSelf) { - if (joiningToChannels.contains(chat_id)) { + if (joiningToChannels.contains(chatId)) { return; } TLRPC.TL_channels_joinChannel req = new TLRPC.TL_channels_joinChannel(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); request = req; - joiningToChannels.add(chat_id); + joiningToChannels.add(chatId); } else { TLRPC.TL_channels_inviteToChannel req = new TLRPC.TL_channels_inviteToChannel(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); req.users.add(inputUser); request = req; } } else { TLRPC.TL_messages_addChatUser req = new TLRPC.TL_messages_addChatUser(); - req.chat_id = chat_id; - req.fwd_limit = count_fwd; + req.chat_id = chatId; + req.fwd_limit = forwardCount; req.user_id = inputUser; request = req; } @@ -9236,10 +9207,10 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_messages_startBot req = new TLRPC.TL_messages_startBot(); req.bot = inputUser; if (isChannel) { - req.peer = getInputPeer(-chat_id); + req.peer = getInputPeer(-chatId); } else { req.peer = new TLRPC.TL_inputPeerChat(); - req.peer.chat_id = chat_id; + req.peer.chat_id = chatId; } req.start_param = botHash; req.random_id = Utilities.random.nextLong(); @@ -9248,7 +9219,7 @@ public class MessagesController extends BaseController implements NotificationCe getConnectionsManager().sendRequest(request, (response, error) -> { if (isChannel && inputUser instanceof TLRPC.TL_inputUserSelf) { - AndroidUtilities.runOnUIThread(() -> joiningToChannels.remove((Integer) chat_id)); + AndroidUtilities.runOnUIThread(() -> joiningToChannels.remove(chatId)); } if (error != null) { AndroidUtilities.runOnUIThread(() -> { @@ -9273,12 +9244,12 @@ public class MessagesController extends BaseController implements NotificationCe processUpdates(updates, false); if (isChannel) { if (!hasJoinMessage && inputUser instanceof TLRPC.TL_inputUserSelf) { - generateJoinMessage(chat_id, true); + generateJoinMessage(chatId, true); } - AndroidUtilities.runOnUIThread(() -> loadFullChat(chat_id, 0, true), 1000); + AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000); } if (isChannel && inputUser instanceof TLRPC.TL_inputUserSelf) { - getMessagesStorage().updateDialogsWithDeletedMessages(new ArrayList<>(), null, true, chat_id); + getMessagesStorage().updateDialogsWithDeletedMessages(-chatId, chatId, new ArrayList<>(), null, true); } if (onFinishRunnable != null) { AndroidUtilities.runOnUIThread(onFinishRunnable); @@ -9286,11 +9257,11 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void deleteParticipantFromChat(int chat_id, TLRPC.User user, TLRPC.ChatFull info) { - deleteParticipantFromChat(chat_id, user, null, info, false, false); + public void deleteParticipantFromChat(long chatId, TLRPC.User user, TLRPC.ChatFull info) { + deleteParticipantFromChat(chatId, user, null, info, false, false); } - public void deleteParticipantFromChat(int chat_id, TLRPC.User user, TLRPC.Chat chat, TLRPC.ChatFull info, boolean forceDelete, boolean revoke) { + public void deleteParticipantFromChat(long chatId, TLRPC.User user, TLRPC.Chat chat, TLRPC.ChatFull info, boolean forceDelete, boolean revoke) { if (user == null && chat == null) { return; } @@ -9301,8 +9272,8 @@ public class MessagesController extends BaseController implements NotificationCe inputPeer = getInputPeer(chat); } TLObject request; - TLRPC.Chat ownerChat = getChat(chat_id); - final boolean isChannel = ChatObject.isChannel(ownerChat); + TLRPC.Chat ownerChat = getChat(chatId); + boolean isChannel = ChatObject.isChannel(ownerChat); if (isChannel) { if (UserObject.isUserSelf(user)) { if (ownerChat.creator && forceDelete) { @@ -9336,65 +9307,55 @@ public class MessagesController extends BaseController implements NotificationCe } else { if (forceDelete) { TLRPC.TL_messages_deleteChat req = new TLRPC.TL_messages_deleteChat(); - req.chat_id = chat_id; + req.chat_id = chatId; getConnectionsManager().sendRequest(req, (response, error) -> { }); return; } TLRPC.TL_messages_deleteChatUser req = new TLRPC.TL_messages_deleteChatUser(); - req.chat_id = chat_id; + req.chat_id = chatId; req.user_id = getInputUser(user); req.revoke_history = true; request = req; } if (UserObject.isUserSelf(user)) { - deleteDialog(-chat_id, 0, revoke); + deleteDialog(-chatId, 0, revoke); } getConnectionsManager().sendRequest(request, (response, error) -> { if (error != null) { return; } - final TLRPC.Updates updates = (TLRPC.Updates) response; + TLRPC.Updates updates = (TLRPC.Updates) response; processUpdates(updates, false); if (isChannel && !UserObject.isUserSelf(user)) { - AndroidUtilities.runOnUIThread(() -> loadFullChat(chat_id, 0, true), 1000); + AndroidUtilities.runOnUIThread(() -> loadFullChat(chatId, 0, true), 1000); } }, ConnectionsManager.RequestFlagInvokeAfter); } - public void changeChatTitle(int chat_id, String title) { - if (chat_id > 0) { - TLObject request; - if (ChatObject.isChannel(chat_id, currentAccount)) { - TLRPC.TL_channels_editTitle req = new TLRPC.TL_channels_editTitle(); - req.channel = getInputChannel(chat_id); - req.title = title; - request = req; - } else { - TLRPC.TL_messages_editChatTitle req = new TLRPC.TL_messages_editChatTitle(); - req.chat_id = chat_id; - req.title = title; - request = req; - } - getConnectionsManager().sendRequest(request, (response, error) -> { - if (error != null) { - return; - } - processUpdates((TLRPC.Updates) response, false); - }, ConnectionsManager.RequestFlagInvokeAfter); + public void changeChatTitle(long chatId, String title) { + TLObject request; + if (ChatObject.isChannel(chatId, currentAccount)) { + TLRPC.TL_channels_editTitle req = new TLRPC.TL_channels_editTitle(); + req.channel = getInputChannel(chatId); + req.title = title; + request = req; } else { - TLRPC.Chat chat = getChat(chat_id); - chat.title = title; - ArrayList chatArrayList = new ArrayList<>(); - chatArrayList.add(chat); - getMessagesStorage().putUsersAndChats(null, chatArrayList, true, true); - getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); - getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME); + TLRPC.TL_messages_editChatTitle req = new TLRPC.TL_messages_editChatTitle(); + req.chat_id = chatId; + req.title = title; + request = req; } + getConnectionsManager().sendRequest(request, (response, error) -> { + if (error != null) { + return; + } + processUpdates((TLRPC.Updates) response, false); + }, ConnectionsManager.RequestFlagInvokeAfter); } - public void changeChatAvatar(int chat_id, TLRPC.TL_inputChatPhoto oldPhoto, TLRPC.InputFile inputPhoto, final TLRPC.InputFile inputVideo, double videoStartTimestamp, String videoPath, TLRPC.FileLocation smallSize, TLRPC.FileLocation bigSize, Runnable callback) { + public void changeChatAvatar(long chatId, TLRPC.TL_inputChatPhoto oldPhoto, TLRPC.InputFile inputPhoto, TLRPC.InputFile inputVideo, double videoStartTimestamp, String videoPath, TLRPC.FileLocation smallSize, TLRPC.FileLocation bigSize, Runnable callback) { TLObject request; TLRPC.InputChatPhoto inputChatPhoto; if (oldPhoto != null) { @@ -9415,14 +9376,14 @@ public class MessagesController extends BaseController implements NotificationCe } else { inputChatPhoto = new TLRPC.TL_inputChatPhotoEmpty(); } - if (ChatObject.isChannel(chat_id, currentAccount)) { + if (ChatObject.isChannel(chatId, currentAccount)) { TLRPC.TL_channels_editPhoto req = new TLRPC.TL_channels_editPhoto(); - req.channel = getInputChannel(chat_id); + req.channel = getInputChannel(chatId); req.photo = inputChatPhoto; request = req; } else { TLRPC.TL_messages_editChatPhoto req = new TLRPC.TL_messages_editChatPhoto(); - req.chat_id = chat_id; + req.chat_id = chatId; req.photo = inputChatPhoto; request = req; } @@ -9583,7 +9544,7 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { UserConfig userConfig = UserConfig.getInstance(a); if (a != currentAccount && userConfig.isClientActivated()) { - int uid = userConfig.getClientUserId(); + long uid = userConfig.getClientUserId(); req.other_uids.add(uid); if (BuildVars.LOGS_ENABLED) { FileLog.d("add other uid = " + uid + " for account " + currentAccount); @@ -9688,7 +9649,7 @@ public class MessagesController extends BaseController implements NotificationCe return 0; } - private void processChannelsUpdatesQueue(int channelId, int state) { + private void processChannelsUpdatesQueue(long channelId, int state) { ArrayList updatesQueue = updatesQueueChannels.get(channelId); if (updatesQueue == null) { return; @@ -9810,7 +9771,7 @@ public class MessagesController extends BaseController implements NotificationCe setUpdatesStartTime(type, 0); } - protected void loadUnknownChannel(final TLRPC.Chat channel, final long taskId) { + protected void loadUnknownChannel(final TLRPC.Chat channel, long taskId) { if (!(channel instanceof TLRPC.TL_channel) || gettingUnknownChannels.indexOfKey(channel.id) >= 0) { return; } @@ -9830,7 +9791,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer(); inputDialogPeer.peer = inputPeer; req.peers.add(inputDialogPeer); - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { @@ -9864,7 +9825,7 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void startShortPoll(TLRPC.Chat chat, int guid, final boolean stop) { + public void startShortPoll(TLRPC.Chat chat, int guid, boolean stop) { if (chat == null) { return; } @@ -9913,7 +9874,7 @@ public class MessagesController extends BaseController implements NotificationCe }); } - private void getChannelDifference(final int channelId) { + private void getChannelDifference(long channelId) { getChannelDifference(channelId, 0, 0, null); } @@ -9931,8 +9892,8 @@ public class MessagesController extends BaseController implements NotificationCe user.id == 4298000); } - protected void getChannelDifference(final int channelId, final int newDialogType, final long taskId, TLRPC.InputChannel inputChannel) { - boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId); + protected void getChannelDifference(long channelId, int newDialogType, long taskId, TLRPC.InputChannel inputChannel) { + boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId, false); if (gettingDifferenceChannel) { return; } @@ -9977,13 +9938,13 @@ public class MessagesController extends BaseController implements NotificationCe } return; } - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { - data = new NativeByteBuffer(12 + inputChannel.getObjectSize()); - data.writeInt32(6); - data.writeInt32(channelId); + data = new NativeByteBuffer(16 + inputChannel.getObjectSize()); + data.writeInt32(25); + data.writeInt64(channelId); data.writeInt32(newDialogType); inputChannel.serializeToStream(data); } catch (Exception e) { @@ -10006,9 +9967,9 @@ public class MessagesController extends BaseController implements NotificationCe } getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.updates_ChannelDifference res = (TLRPC.updates_ChannelDifference) response; + TLRPC.updates_ChannelDifference res = (TLRPC.updates_ChannelDifference) response; - final SparseArray usersDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User user = res.users.get(a); usersDict.put(user.id, user); @@ -10021,9 +9982,9 @@ public class MessagesController extends BaseController implements NotificationCe break; } } - final TLRPC.Chat channelFinal = channel; + TLRPC.Chat channelFinal = channel; - final ArrayList msgUpdates = new ArrayList<>(); + ArrayList msgUpdates = new ArrayList<>(); if (!res.other_updates.isEmpty()) { for (int a = 0; a < res.other_updates.size(); a++) { TLRPC.Update upd = res.other_updates.get(a); @@ -10043,9 +10004,9 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().getStorageQueue().postRunnable(() -> { if (!msgUpdates.isEmpty()) { - final SparseArray corrected = new SparseArray<>(); + SparseArray corrected = new SparseArray<>(); for (TLRPC.TL_updateMessageID update : msgUpdates) { - long[] ids = getMessagesStorage().updateMessageStateAndId(update.random_id, null, update.id, 0, false, channelId, -1); + long[] ids = getMessagesStorage().updateMessageStateAndId(update.random_id, -channelId, null, update.id, 0, false, -1); if (ids != null) { corrected.put(update.id, ids); } @@ -10056,9 +10017,8 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0; a < corrected.size(); a++) { int newId = corrected.keyAt(a); long[] ids = corrected.valueAt(a); - int oldId = (int) ids[1]; - getSendMessagesHelper().processSentMessage(oldId); - getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null, ids[0], 0L, -1, false); + getSendMessagesHelper().processSentMessage((int) ids[1]); + getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false); } }); } @@ -10067,21 +10027,21 @@ public class MessagesController extends BaseController implements NotificationCe Utilities.stageQueue.postRunnable(() -> { if (res instanceof TLRPC.TL_updates_channelDifference || res instanceof TLRPC.TL_updates_channelDifferenceEmpty) { if (!res.new_messages.isEmpty()) { - final LongSparseArray> messages = new LongSparseArray<>(); + LongSparseArray> messages = new LongSparseArray<>(); ImageLoader.saveMessagesThumbs(res.new_messages); - final ArrayList pushMessages = new ArrayList<>(); - long dialog_id = -channelId; - Integer inboxValue = dialogs_read_inbox_max.get(dialog_id); + ArrayList pushMessages = new ArrayList<>(); + long dialogId = -channelId; + Integer inboxValue = dialogs_read_inbox_max.get(dialogId); if (inboxValue == null) { - inboxValue = getMessagesStorage().getDialogReadMax(false, dialog_id); - dialogs_read_inbox_max.put(dialog_id, inboxValue); + inboxValue = getMessagesStorage().getDialogReadMax(false, dialogId); + dialogs_read_inbox_max.put(dialogId, inboxValue); } - Integer outboxValue = dialogs_read_outbox_max.get(dialog_id); + Integer outboxValue = dialogs_read_outbox_max.get(dialogId); if (outboxValue == null) { - outboxValue = getMessagesStorage().getDialogReadMax(true, dialog_id); - dialogs_read_outbox_max.put(dialog_id, outboxValue); + outboxValue = getMessagesStorage().getDialogReadMax(true, dialogId); + dialogs_read_outbox_max.put(dialogId, outboxValue); } for (int a = 0; a < res.new_messages.size(); a++) { @@ -10091,7 +10051,7 @@ public class MessagesController extends BaseController implements NotificationCe } message.unread = !(channelFinal != null && channelFinal.left || (message.out ? outboxValue : inboxValue) >= message.id || message.action instanceof TLRPC.TL_messageActionChannelCreate); - boolean isDialogCreated = createdDialogIds.contains(dialog_id); + boolean isDialogCreated = createdDialogIds.contains(dialogId); MessageObject obj = new MessageObject(currentAccount, message, usersDict, isDialogCreated, isDialogCreated); if ((!obj.isOut() || obj.messageOwner.from_scheduled) && obj.isUnread()) { pushMessages.add(obj); @@ -10128,18 +10088,18 @@ public class MessagesController extends BaseController implements NotificationCe processChannelsUpdatesQueue(channelId, 1); getMessagesStorage().saveChannelPts(channelId, res.pts); } else if (res instanceof TLRPC.TL_updates_channelDifferenceTooLong) { - long dialog_id = -channelId; + long dialogId = -channelId; - Integer inboxValue = dialogs_read_inbox_max.get(dialog_id); + Integer inboxValue = dialogs_read_inbox_max.get(dialogId); if (inboxValue == null) { - inboxValue = getMessagesStorage().getDialogReadMax(false, dialog_id); - dialogs_read_inbox_max.put(dialog_id, inboxValue); + inboxValue = getMessagesStorage().getDialogReadMax(false, dialogId); + dialogs_read_inbox_max.put(dialogId, inboxValue); } - Integer outboxValue = dialogs_read_outbox_max.get(dialog_id); + Integer outboxValue = dialogs_read_outbox_max.get(dialogId); if (outboxValue == null) { - outboxValue = getMessagesStorage().getDialogReadMax(true, dialog_id); - dialogs_read_outbox_max.put(dialog_id, outboxValue); + outboxValue = getMessagesStorage().getDialogReadMax(true, dialogId); + dialogs_read_outbox_max.put(dialogId, outboxValue); } for (int a = 0; a < res.messages.size(); a++) { @@ -10178,7 +10138,7 @@ public class MessagesController extends BaseController implements NotificationCe }); } - private void checkChannelError(String text, int channelId) { + private void checkChannelError(String text, long channelId) { switch (text) { case "CHANNEL_PRIVATE": getNotificationCenter().postNotificationName(NotificationCenter.chatInfoCantLoad, channelId, 0); @@ -10196,7 +10156,7 @@ public class MessagesController extends BaseController implements NotificationCe getDifference(getMessagesStorage().getLastPtsValue(), getMessagesStorage().getLastDateValue(), getMessagesStorage().getLastQtsValue(), false); } - public void getDifference(int pts, final int date, final int qts, boolean slice) { + public void getDifference(int pts, int date, int qts, boolean slice) { registerForPush(SharedConfig.pushString); if (getMessagesStorage().getLastPtsValue() == 0) { loadCurrentState(); @@ -10228,7 +10188,7 @@ public class MessagesController extends BaseController implements NotificationCe getConnectionsManager().setIsUpdating(true); getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { - final TLRPC.updates_Difference res = (TLRPC.updates_Difference) response; + TLRPC.updates_Difference res = (TLRPC.updates_Difference) response; if (res instanceof TLRPC.TL_updates_differenceTooLong) { AndroidUtilities.runOnUIThread(() -> { loadedFullUsers.clear(); @@ -10240,8 +10200,8 @@ public class MessagesController extends BaseController implements NotificationCe getDifference(res.intermediate_state.pts, res.intermediate_state.date, res.intermediate_state.qts, true); } - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User user = res.users.get(a); usersDict.put(user.id, user); @@ -10251,7 +10211,7 @@ public class MessagesController extends BaseController implements NotificationCe chatsDict.put(chat.id, chat); } - final ArrayList msgUpdates = new ArrayList<>(); + ArrayList msgUpdates = new ArrayList<>(); if (!res.other_updates.isEmpty()) { for (int a = 0; a < res.other_updates.size(); a++) { TLRPC.Update upd = res.other_updates.get(a); @@ -10260,7 +10220,7 @@ public class MessagesController extends BaseController implements NotificationCe res.other_updates.remove(a); a--; } else if (getUpdateType(upd) == 2) { - int channelId = getUpdateChannelId(upd); + long channelId = getUpdateChannelId(upd); int channelPts = channelsPts.get(channelId); if (channelPts == 0) { channelPts = getMessagesStorage().getChannelPtsSync(channelId); @@ -10286,10 +10246,10 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().getStorageQueue().postRunnable(() -> { getMessagesStorage().putUsersAndChats(res.users, res.chats, true, false); if (!msgUpdates.isEmpty()) { - final SparseArray corrected = new SparseArray<>(); + SparseArray corrected = new SparseArray<>(); for (int a = 0; a < msgUpdates.size(); a++) { TLRPC.TL_updateMessageID update = msgUpdates.get(a); - long[] ids = getMessagesStorage().updateMessageStateAndId(update.random_id, null, update.id, 0, false, 0, -1); + long[] ids = getMessagesStorage().updateMessageStateAndId(update.random_id, 0, null, update.id, 0, false, -1); if (ids != null) { corrected.put(update.id, ids); } @@ -10300,9 +10260,8 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0; a < corrected.size(); a++) { int newId = corrected.keyAt(a); long[] ids = corrected.valueAt(a); - int oldId = (int) ids[1]; - getSendMessagesHelper().processSentMessage(oldId); - getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null, ids[0], 0L, -1, false); + getSendMessagesHelper().processSentMessage((int) ids[1]); + getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, (int) ids[1], newId, null, ids[0], 0L, -1, false); } }); } @@ -10310,7 +10269,7 @@ public class MessagesController extends BaseController implements NotificationCe Utilities.stageQueue.postRunnable(() -> { if (!res.new_messages.isEmpty() || !res.new_encrypted_messages.isEmpty()) { - final LongSparseArray> messages = new LongSparseArray<>(); + LongSparseArray> messages = new LongSparseArray<>(); for (int b = 0; b < res.new_encrypted_messages.size(); b++) { TLRPC.EncryptedMessage encryptedMessage = res.new_encrypted_messages.get(b); ArrayList decryptedMessages = getSecretChatHelper().decryptMessage(encryptedMessage); @@ -10321,8 +10280,8 @@ public class MessagesController extends BaseController implements NotificationCe ImageLoader.saveMessagesThumbs(res.new_messages); - final ArrayList pushMessages = new ArrayList<>(); - int clientUserId = getUserConfig().getClientUserId(); + ArrayList pushMessages = new ArrayList<>(); + long clientUserId = getUserConfig().getClientUserId(); for (int a = 0; a < res.new_messages.size(); a++) { TLRPC.Message message = res.new_messages.get(a); if (message instanceof TLRPC.TL_messageEmpty) { @@ -10330,7 +10289,7 @@ public class MessagesController extends BaseController implements NotificationCe } MessageObject.getDialogId(message); - if ((int) message.dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(message.dialog_id)) { if (message.action instanceof TLRPC.TL_messageActionChatDeleteUser) { TLRPC.User user = usersDict.get(message.action.user_id); if (user != null && user.bot) { @@ -10431,15 +10390,15 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void markDialogAsUnread(long did, TLRPC.InputPeer peer, long taskId) { - TLRPC.Dialog dialog = dialogs_dict.get(did); + public void markDialogAsUnread(long dialogId, TLRPC.InputPeer peer, long taskId) { + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null) { dialog.unread_mark = true; - if (dialog.unread_count == 0 && !isDialogMuted(did)) { + if (dialog.unread_count == 0 && !isDialogMuted(dialogId)) { unreadUnmutedDialogs++; } getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_READ_DIALOG_MESSAGE); - getMessagesStorage().setDialogUnread(did, true); + getMessagesStorage().setDialogUnread(dialogId, true); for (int b = 0; b < selectedDialogFilter.length; b++) { if (selectedDialogFilter[b] != null && (selectedDialogFilter[b].flags & DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0) { sortDialogs(null); @@ -10448,12 +10407,11 @@ public class MessagesController extends BaseController implements NotificationCe } } } - int lower_id = (int) did; - if (lower_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { TLRPC.TL_messages_markDialogUnread req = new TLRPC.TL_messages_markDialogUnread(); req.unread = true; if (peer == null) { - peer = getInputPeer(lower_id); + peer = getInputPeer(dialogId); } if (peer instanceof TLRPC.TL_inputPeerEmpty) { return; @@ -10462,13 +10420,13 @@ public class MessagesController extends BaseController implements NotificationCe inputDialogPeer.peer = peer; req.peer = inputDialogPeer; - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { data = new NativeByteBuffer(12 + peer.getObjectSize()); data.writeInt32(9); - data.writeInt64(did); + data.writeInt64(dialogId); peer.serializeToStream(data); } catch (Exception e) { FileLog.e(e); @@ -10494,7 +10452,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_messages_getDialogUnreadMarks req = new TLRPC.TL_messages_getDialogUnreadMarks(); getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response != null) { - final TLRPC.Vector vector = (TLRPC.Vector) response; + TLRPC.Vector vector = (TLRPC.Vector) response; for (int a = 0, size = vector.objects.size(); a < size; a++) { TLRPC.DialogPeer peer = (TLRPC.DialogPeer) vector.objects.get(a); if (peer instanceof TLRPC.TL_dialogPeer) { @@ -10530,7 +10488,7 @@ public class MessagesController extends BaseController implements NotificationCe req.folder_id = folderId; req.force = true; - final long newTaskId; + long newTaskId; if (taskId == 0) { ArrayList dialogs = getDialogs(folderId); if (dialogs.isEmpty()) { @@ -10553,8 +10511,8 @@ public class MessagesController extends BaseController implements NotificationCe } dids.add(dialog.id); pinned.add(dialog.pinnedNum); - if ((int) dialog.id != 0) { - TLRPC.InputPeer inputPeer = getInputPeer((int) dialogs.get(a).id); + if (!DialogObject.isEncryptedDialog(dialog.id)) { + TLRPC.InputPeer inputPeer = getInputPeer(dialog.id); TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer(); inputDialogPeer.peer = inputPeer; req.order.add(inputDialogPeer); @@ -10588,9 +10546,8 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public boolean pinDialog(long did, boolean pin, TLRPC.InputPeer peer, long taskId) { - int lower_id = (int) did; - TLRPC.Dialog dialog = dialogs_dict.get(did); + public boolean pinDialog(long dialogId, boolean pin, TLRPC.InputPeer peer, long taskId) { + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog == null || dialog.pinned == pin) { return dialog != null; } @@ -10621,12 +10578,12 @@ public class MessagesController extends BaseController implements NotificationCe dialogs.remove(dialogs.size() - 1); } getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); - if (lower_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if (taskId != -1) { TLRPC.TL_messages_toggleDialogPin req = new TLRPC.TL_messages_toggleDialogPin(); req.pinned = pin; if (peer == null) { - peer = getInputPeer(lower_id); + peer = getInputPeer(dialogId); } if (peer instanceof TLRPC.TL_inputPeerEmpty) { return false; @@ -10635,13 +10592,13 @@ public class MessagesController extends BaseController implements NotificationCe inputDialogPeer.peer = peer; req.peer = inputDialogPeer; - final long newTaskId; + long newTaskId; if (taskId == 0) { NativeByteBuffer data = null; try { data = new NativeByteBuffer(16 + peer.getObjectSize()); data.writeInt32(4); - data.writeInt64(did); + data.writeInt64(dialogId); data.writeBool(pin); peer.serializeToStream(data); } catch (Exception e) { @@ -10659,11 +10616,11 @@ public class MessagesController extends BaseController implements NotificationCe }); } } - getMessagesStorage().setDialogPinned(did, dialog.pinnedNum); + getMessagesStorage().setDialogPinned(dialogId, dialog.pinnedNum); return true; } - public void loadPinnedDialogs(final int folderId, final long newDialogId, final ArrayList order) { + public void loadPinnedDialogs(final int folderId, long newDialogId, ArrayList order) { if (loadingPinnedDialogs.indexOfKey(folderId) >= 0 || getUserConfig().isPinnedDialogsLoaded(folderId)) { return; } @@ -10672,18 +10629,18 @@ public class MessagesController extends BaseController implements NotificationCe req.folder_id = folderId; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { - final TLRPC.TL_messages_peerDialogs res = (TLRPC.TL_messages_peerDialogs) response; + TLRPC.TL_messages_peerDialogs res = (TLRPC.TL_messages_peerDialogs) response; ArrayList newPinnedDialogs = new ArrayList<>(res.dialogs); fetchFolderInLoadedPinnedDialogs(res); - final TLRPC.TL_messages_dialogs toCache = new TLRPC.TL_messages_dialogs(); + TLRPC.TL_messages_dialogs toCache = new TLRPC.TL_messages_dialogs(); toCache.users.addAll(res.users); toCache.chats.addAll(res.chats); toCache.dialogs.addAll(res.dialogs); toCache.messages.addAll(res.messages); - final LongSparseArray new_dialogMessage = new LongSparseArray<>(); - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + LongSparseArray new_dialogMessage = new LongSparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User u = res.users.get(a); @@ -10716,12 +10673,12 @@ public class MessagesController extends BaseController implements NotificationCe d.pinned = true; DialogObject.initDialog(d); if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.left) { continue; } - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); + } else if (DialogObject.isChatDialog(d.id)) { + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.migrated_to != null) { continue; } @@ -10761,7 +10718,7 @@ public class MessagesController extends BaseController implements NotificationCe if (dialog instanceof TLRPC.TL_dialogFolder) { continue; } - if ((int) dialog.id == 0) { + if (DialogObject.isEncryptedDialog(dialog.id)) { if (pinnedNum < newPinnedDialogs.size()) { newPinnedDialogs.add(pinnedNum, dialog); } else { @@ -10841,9 +10798,9 @@ public class MessagesController extends BaseController implements NotificationCe }); } - public void generateJoinMessage(final int chat_id, boolean ignoreLeft) { - TLRPC.Chat chat = getChat(chat_id); - if (chat == null || !ChatObject.isChannel(chat_id, currentAccount) || (chat.left || chat.kicked) && !ignoreLeft) { + public void generateJoinMessage(long chatId, boolean ignoreLeft) { + TLRPC.Chat chat = getChat(chatId); + if (chat == null || !ChatObject.isChannel(chatId, currentAccount) || (chat.left || chat.kicked) && !ignoreLeft) { return; } @@ -10854,15 +10811,15 @@ public class MessagesController extends BaseController implements NotificationCe message.from_id = new TLRPC.TL_peerUser(); message.from_id.user_id = getUserConfig().getClientUserId(); message.peer_id = new TLRPC.TL_peerChannel(); - message.peer_id.channel_id = chat_id; - message.dialog_id = -chat_id; + message.peer_id.channel_id = chatId; + message.dialog_id = -chatId; message.post = true; message.action = new TLRPC.TL_messageActionChatAddUser(); message.action.users.add(getUserConfig().getClientUserId()); getUserConfig().saveConfig(false); - final ArrayList pushMessages = new ArrayList<>(); - final ArrayList messagesArr = new ArrayList<>(); + ArrayList pushMessages = new ArrayList<>(); + ArrayList messagesArr = new ArrayList<>(); messagesArr.add(message); MessageObject obj = new MessageObject(currentAccount, message, true, false); @@ -10872,12 +10829,12 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().putMessages(messagesArr, true, true, false, 0, false); AndroidUtilities.runOnUIThread(() -> { - updateInterfaceWithMessages(-chat_id, pushMessages, false); + updateInterfaceWithMessages(-chatId, pushMessages, false); getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); }); } - protected void deleteMessagesByPush(long dialogId, ArrayList ids, int channelId) { + protected void deleteMessagesByPush(long dialogId, ArrayList ids, long channelId) { getMessagesStorage().getStorageQueue().postRunnable(() -> { AndroidUtilities.runOnUIThread(() -> { getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, ids, channelId, false); @@ -10902,13 +10859,13 @@ public class MessagesController extends BaseController implements NotificationCe } }); getMessagesStorage().deletePushMessages(dialogId, ids); - ArrayList dialogIds = getMessagesStorage().markMessagesAsDeleted(ids, false, channelId, true, false); - getMessagesStorage().updateDialogsWithDeletedMessages(ids, dialogIds, false, channelId); + ArrayList dialogIds = getMessagesStorage().markMessagesAsDeleted(dialogId, ids, false, true, false); + getMessagesStorage().updateDialogsWithDeletedMessages(dialogId, channelId, ids, dialogIds, false); }); } - public void checkChatInviter(final int chatId, boolean createMessage) { - final TLRPC.Chat chat = getChat(chatId); + public void checkChatInviter(long chatId, boolean createMessage) { + TLRPC.Chat chat = getChat(chatId); if (!ChatObject.isChannel(chat) || chat.creator || gettingChatInviters.indexOfKey(chatId) >= 0) { return; } @@ -10917,7 +10874,7 @@ public class MessagesController extends BaseController implements NotificationCe req.channel = getInputChannel(chatId); req.participant = getInputPeer(getUserConfig().getClientUserId()); getConnectionsManager().sendRequest(req, (response, error) -> { - final TLRPC.TL_channels_channelParticipant res = (TLRPC.TL_channels_channelParticipant) response; + TLRPC.TL_channels_channelParticipant res = (TLRPC.TL_channels_channelParticipant) response; if (res != null && res.participant instanceof TLRPC.TL_channelParticipantSelf && res.participant.inviter_id != getUserConfig().getClientUserId()) { if (chat.megagroup && getMessagesStorage().isMigratedChat(chat.id)) { return; @@ -10947,9 +10904,9 @@ public class MessagesController extends BaseController implements NotificationCe getUserConfig().saveConfig(false); pushMessages = new ArrayList<>(); - final ArrayList messagesArr = new ArrayList<>(); + ArrayList messagesArr = new ArrayList<>(); - ConcurrentHashMap usersDict = new ConcurrentHashMap<>(); + ConcurrentHashMap usersDict = new ConcurrentHashMap<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User user = res.users.get(a); usersDict.put(user.id, user); @@ -11071,7 +11028,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public static int getUpdateChannelId(TLRPC.Update update) { + public static long getUpdateChannelId(TLRPC.Update update) { if (update instanceof TLRPC.TL_updateNewChannelMessage) { return ((TLRPC.TL_updateNewChannelMessage) update).message.peer_id.channel_id; } else if (update instanceof TLRPC.TL_updateEditChannelMessage) { @@ -11113,7 +11070,7 @@ public class MessagesController extends BaseController implements NotificationCe } public void processUpdates(final TLRPC.Updates updates, boolean fromQueue) { - ArrayList needGetChannelsDiff = null; + ArrayList needGetChannelsDiff = null; boolean needGetDiff = false; boolean needReceivedQueue = false; boolean updateStatus = false; @@ -11122,14 +11079,14 @@ public class MessagesController extends BaseController implements NotificationCe arr.add(updates.update); processUpdateArray(arr, null, null, false, updates.date); } else if (updates instanceof TLRPC.TL_updateShortChatMessage || updates instanceof TLRPC.TL_updateShortMessage) { - final int user_id = updates instanceof TLRPC.TL_updateShortChatMessage ? updates.from_id : updates.user_id; - TLRPC.User user = getUser(user_id); + long userId = updates instanceof TLRPC.TL_updateShortChatMessage ? updates.from_id : updates.user_id; + TLRPC.User user = getUser(userId); TLRPC.User user2 = null; TLRPC.User user3 = null; TLRPC.Chat channel = null; if (user == null || user.min) { - user = getMessagesStorage().getUserSync(user_id); + user = getMessagesStorage().getUserSync(userId); if (user != null && user.min) { user = null; } @@ -11187,7 +11144,7 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0; a < updates.entities.size(); a++) { TLRPC.MessageEntity entity = updates.entities.get(a); if (entity instanceof TLRPC.TL_messageEntityMentionName) { - int uid = ((TLRPC.TL_messageEntityMentionName) entity).user_id; + long uid = ((TLRPC.TL_messageEntityMentionName) entity).user_id; TLRPC.User entityUser = getUser(uid); if (entityUser == null || entityUser.min) { entityUser = getMessagesStorage().getUserSync(uid); @@ -11214,20 +11171,20 @@ public class MessagesController extends BaseController implements NotificationCe if (getMessagesStorage().getLastPtsValue() + updates.pts_count == updates.pts) { TLRPC.TL_message message = new TLRPC.TL_message(); message.id = updates.id; - int clientUserId = getUserConfig().getClientUserId(); + long clientUserId = getUserConfig().getClientUserId(); if (updates instanceof TLRPC.TL_updateShortMessage) { message.from_id = new TLRPC.TL_peerUser(); if (updates.out) { message.from_id.user_id = clientUserId; } else { - message.from_id.user_id = user_id; + message.from_id.user_id = userId; } message.peer_id = new TLRPC.TL_peerUser(); - message.peer_id.user_id = user_id; - message.dialog_id = user_id; + message.peer_id.user_id = userId; + message.dialog_id = userId; } else { message.from_id = new TLRPC.TL_peerUser(); - message.from_id.user_id = user_id; + message.from_id.user_id = userId; message.peer_id = new TLRPC.TL_peerChat(); message.peer_id.chat_id = updates.chat_id; message.dialog_id = -updates.chat_id; @@ -11263,13 +11220,13 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().setLastPtsValue(updates.pts); boolean isDialogCreated = createdDialogIds.contains(message.dialog_id); - final MessageObject obj = new MessageObject(currentAccount, message, isDialogCreated, isDialogCreated); - final ArrayList objArr = new ArrayList<>(); + MessageObject obj = new MessageObject(currentAccount, message, isDialogCreated, isDialogCreated); + ArrayList objArr = new ArrayList<>(); objArr.add(obj); ArrayList arr = new ArrayList<>(); arr.add(message); if (updates instanceof TLRPC.TL_updateShortMessage) { - final boolean printUpdate = !updates.out && updatePrintingUsersWithNewMessages(updates.user_id, objArr); + boolean printUpdate = !updates.out && updatePrintingUsersWithNewMessages(updates.user_id, objArr); if (printUpdate) { updatePrintingStrings(); } @@ -11277,11 +11234,11 @@ public class MessagesController extends BaseController implements NotificationCe if (printUpdate) { getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT); } - updateInterfaceWithMessages(user_id, objArr, false); + updateInterfaceWithMessages(userId, objArr, false); getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload); }); } else { - final boolean printUpdate = updatePrintingUsersWithNewMessages(-updates.chat_id, objArr); + boolean printUpdate = updatePrintingUsersWithNewMessages(-updates.chat_id, objArr); if (printUpdate) { updatePrintingStrings(); } @@ -11316,7 +11273,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } else if (updates instanceof TLRPC.TL_updatesCombined || updates instanceof TLRPC.TL_updates) { - SparseArray minChannels = null; + LongSparseArray minChannels = null; for (int a = 0; a < updates.chats.size(); a++) { TLRPC.Chat chat = updates.chats.get(a); if (chat instanceof TLRPC.TL_channel) { @@ -11329,7 +11286,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (existChat == null || existChat.min) { if (minChannels == null) { - minChannels = new SparseArray<>(); + minChannels = new LongSparseArray<>(); } minChannels.put(chat.id, chat); } @@ -11341,7 +11298,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateNewChannelMessage) { TLRPC.Message message = ((TLRPC.TL_updateNewChannelMessage) update).message; - int channelId = message.peer_id.channel_id; + long channelId = message.peer_id.channel_id; if (minChannels.indexOfKey(channelId) >= 0) { if (BuildVars.LOGS_ENABLED) { FileLog.d("need get diff because of min channel " + channelId); @@ -11448,7 +11405,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } else if (getUpdateType(update) == 2) { - int channelId = getUpdateChannelId(update); + long channelId = getUpdateChannelId(update); boolean skipUpdate = false; int channelPts = channelsPts.get(channelId); if (channelPts == 0) { @@ -11504,7 +11461,7 @@ public class MessagesController extends BaseController implements NotificationCe FileLog.d(update + " need get channel diff, pts: " + channelPts + " " + updatesNew.pts + " count = " + updatesNew.pts_count + " channelId = " + channelId); } long updatesStartWaitTime = updatesStartWaitTimeChannels.get(channelId); - boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId); + boolean gettingDifferenceChannel = gettingDifferenceChannels.get(channelId, false); if (gettingDifferenceChannel || updatesStartWaitTime == 0 || Math.abs(System.currentTimeMillis() - updatesStartWaitTime) <= 1500) { if (updatesStartWaitTime == 0) { updatesStartWaitTimeChannels.put(channelId, System.currentTimeMillis()); @@ -11592,7 +11549,7 @@ public class MessagesController extends BaseController implements NotificationCe getSecretChatHelper().processPendingEncMessages(); if (!fromQueue) { for (int a = 0; a < updatesQueueChannels.size(); a++) { - int key = updatesQueueChannels.keyAt(a); + long key = updatesQueueChannels.keyAt(a); if (needGetChannelsDiff != null && needGetChannelsDiff.contains(key)) { getChannelDifference(key); } else { @@ -11647,7 +11604,7 @@ public class MessagesController extends BaseController implements NotificationCe return updated; } - public boolean processUpdateArray(ArrayList updates, final ArrayList usersArr, final ArrayList chatsArr, boolean fromGetDifference, int date) { + public boolean processUpdateArray(ArrayList updates, ArrayList usersArr, ArrayList chatsArr, boolean fromGetDifference, int date) { if (updates.isEmpty()) { if (usersArr != null || chatsArr != null) { AndroidUtilities.runOnUIThread(() -> { @@ -11665,29 +11622,30 @@ public class MessagesController extends BaseController implements NotificationCe LongSparseArray webPages = null; ArrayList pushMessages = null; ArrayList messagesArr = null; + ArrayList emojiInteractions = null; ArrayList scheduledMessagesArr = null; LongSparseArray> editingMessages = null; - SparseArray channelViews = null; - SparseArray channelForwards = null; - SparseArray> channelReplies = null; - SparseLongArray markAsReadMessagesInbox = null; - SparseLongArray markAsReadMessagesOutbox = null; - ArrayList markAsReadMessages = null; + LongSparseArray channelViews = null; + LongSparseArray channelForwards = null; + LongSparseArray> channelReplies = null; + LongSparseIntArray markAsReadMessagesInbox = null; + LongSparseIntArray markAsReadMessagesOutbox = null; + LongSparseArray> markContentAsReadMessages = null; SparseIntArray markAsReadEncrypted = null; - SparseArray> deletedMessages = null; - SparseArray> scheduledDeletedMessages = null; - SparseArray> groupSpeakingActions = null; - LongSparseArray importingActions = null; - SparseIntArray clearHistoryMessages = null; + LongSparseArray> deletedMessages = null; + LongSparseArray> scheduledDeletedMessages = null; + LongSparseArray> groupSpeakingActions = null; + LongSparseIntArray importingActions = null; + LongSparseIntArray clearHistoryMessages = null; ArrayList chatInfoToUpdate = null; ArrayList updatesOnMainThread = null; ArrayList folderUpdates = null; ArrayList tasks = null; - ArrayList contactsIds = null; + ArrayList contactsIds = null; ArrayList messageThumbs = null; - ConcurrentHashMap usersDict; - ConcurrentHashMap chatsDict; + ConcurrentHashMap usersDict; + ConcurrentHashMap chatsDict; if (usersArr != null) { usersDict = new ConcurrentHashMap<>(); for (int a = 0, size = usersArr.size(); a < size; a++) { @@ -11715,7 +11673,7 @@ public class MessagesController extends BaseController implements NotificationCe } int interfaceUpdateMask = 0; - int clientUserId = getUserConfig().getClientUserId(); + long clientUserId = getUserConfig().getClientUserId(); for (int c = 0, size3 = updates.size(); c < size3; c++) { TLRPC.Update baseUpdate = updates.get(c); @@ -11741,30 +11699,30 @@ public class MessagesController extends BaseController implements NotificationCe continue; } TLRPC.Chat chat = null; - int chat_id = 0; - int user_id = 0; + long chatId = 0; + long userId = 0; if (message.peer_id.channel_id != 0) { - chat_id = message.peer_id.channel_id; + chatId = message.peer_id.channel_id; } else if (message.peer_id.chat_id != 0) { - chat_id = message.peer_id.chat_id; + chatId = message.peer_id.chat_id; } else if (message.peer_id.user_id != 0) { - user_id = message.peer_id.user_id; + userId = message.peer_id.user_id; } - if (chat_id != 0) { - chat = chatsDict.get(chat_id); + if (chatId != 0) { + chat = chatsDict.get(chatId); if (chat == null || chat.min) { - chat = getChat(chat_id); + chat = getChat(chatId); } if (chat == null || chat.min) { - chat = getMessagesStorage().getChatSync(chat_id); + chat = getMessagesStorage().getChatSync(chatId); putChat(chat, true); } } if (!fromGetDifference) { - if (chat_id != 0) { + if (chatId != 0) { if (chat == null) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("not found chat " + chat_id); + FileLog.d("not found chat " + chatId); } return false; } @@ -11775,24 +11733,24 @@ public class MessagesController extends BaseController implements NotificationCe boolean allowMin = false; if (a != 0) { if (a == 1) { - user_id = message.from_id instanceof TLRPC.TL_peerUser ? message.from_id.user_id : 0; + userId = message.from_id instanceof TLRPC.TL_peerUser ? message.from_id.user_id : 0; if (message.post) { allowMin = true; } } else if (a == 2) { - user_id = message.fwd_from != null && message.fwd_from.from_id instanceof TLRPC.TL_peerUser ? message.fwd_from.from_id.user_id : 0; + userId = message.fwd_from != null && message.fwd_from.from_id instanceof TLRPC.TL_peerUser ? message.fwd_from.from_id.user_id : 0; } else { TLRPC.MessageEntity entity = message.entities.get(a - 3); - user_id = entity instanceof TLRPC.TL_messageEntityMentionName ? ((TLRPC.TL_messageEntityMentionName) entity).user_id : 0; + userId = entity instanceof TLRPC.TL_messageEntityMentionName ? ((TLRPC.TL_messageEntityMentionName) entity).user_id : 0; } } - if (user_id > 0) { - TLRPC.User user = usersDict.get(user_id); + if (userId > 0) { + TLRPC.User user = usersDict.get(userId); if (user == null || !allowMin && user.min) { - user = getUser(user_id); + user = getUser(userId); } if (user == null || !allowMin && user.min) { - user = getMessagesStorage().getUserSync(user_id); + user = getMessagesStorage().getUserSync(userId); if (user != null && !allowMin && user.min) { user = null; } @@ -11800,12 +11758,12 @@ public class MessagesController extends BaseController implements NotificationCe } if (user == null) { if (BuildVars.LOGS_ENABLED) { - FileLog.d("not found user " + user_id); + FileLog.d("not found user " + userId); } return false; } if (!message.out && a == 1 && user.status != null && user.status.expires <= 0 && Math.abs(getConnectionsManager().getCurrentTime() - message.date) < 30) { - onlinePrivacy.put(user_id, message.date); + onlinePrivacy.put(userId, message.date); interfaceUpdateMask |= UPDATE_MASK_STATUS; } } @@ -11827,15 +11785,15 @@ public class MessagesController extends BaseController implements NotificationCe MessageObject.getDialogId(message); if (baseUpdate instanceof TLRPC.TL_updateNewChannelMessage && message.reply_to != null && !(message.action instanceof TLRPC.TL_messageActionPinMessage)) { if (channelReplies == null) { - channelReplies = new SparseArray<>(); + channelReplies = new LongSparseArray<>(); } - SparseArray replies = channelReplies.get((int) message.dialog_id); + SparseArray replies = channelReplies.get(message.dialog_id); if (replies == null) { replies = new SparseArray<>(); - channelReplies.put((int) message.dialog_id, replies); + channelReplies.put(message.dialog_id, replies); } int id = message.reply_to.reply_to_top_id != 0 ? message.reply_to.reply_to_top_id : message.reply_to.reply_to_msg_id; - TLRPC.TL_messageReplies messageReplies = replies.get(id); + TLRPC.MessageReplies messageReplies = replies.get(id); if (messageReplies == null) { messageReplies = new TLRPC.TL_messageReplies(); replies.put(id, messageReplies); @@ -11921,68 +11879,72 @@ public class MessagesController extends BaseController implements NotificationCe } } else if (baseUpdate instanceof TLRPC.TL_updateReadMessagesContents) { TLRPC.TL_updateReadMessagesContents update = (TLRPC.TL_updateReadMessagesContents) baseUpdate; - if (markAsReadMessages == null) { - markAsReadMessages = new ArrayList<>(); + if (markContentAsReadMessages == null) { + markContentAsReadMessages = new LongSparseArray<>(); } - for (int a = 0, size = update.messages.size(); a < size; a++) { - long id = update.messages.get(a); - markAsReadMessages.add(id); + ArrayList ids = markContentAsReadMessages.get(0); + if (ids == null) { + ids = new ArrayList<>(); + markContentAsReadMessages.put(0, ids); } + ids.addAll(update.messages); } else if (baseUpdate instanceof TLRPC.TL_updateChannelReadMessagesContents) { TLRPC.TL_updateChannelReadMessagesContents update = (TLRPC.TL_updateChannelReadMessagesContents) baseUpdate; - if (markAsReadMessages == null) { - markAsReadMessages = new ArrayList<>(); + if (markContentAsReadMessages == null) { + markContentAsReadMessages = new LongSparseArray<>(); } - for (int a = 0, size = update.messages.size(); a < size; a++) { - long id = update.messages.get(a); - id |= ((long) update.channel_id) << 32; - markAsReadMessages.add(id); + long dialogId = -update.channel_id; + ArrayList ids = markContentAsReadMessages.get(dialogId); + if (ids == null) { + ids = new ArrayList<>(); + markContentAsReadMessages.put(dialogId, ids); } + ids.addAll(update.messages); } else if (baseUpdate instanceof TLRPC.TL_updateReadHistoryInbox) { TLRPC.TL_updateReadHistoryInbox update = (TLRPC.TL_updateReadHistoryInbox) baseUpdate; - long dialog_id; + long dialogId; if (markAsReadMessagesInbox == null) { - markAsReadMessagesInbox = new SparseLongArray(); + markAsReadMessagesInbox = new LongSparseIntArray(); } if (update.peer.chat_id != 0) { markAsReadMessagesInbox.put(-update.peer.chat_id, update.max_id); - dialog_id = -update.peer.chat_id; + dialogId = -update.peer.chat_id; } else { markAsReadMessagesInbox.put(update.peer.user_id, update.max_id); - dialog_id = update.peer.user_id; + dialogId = update.peer.user_id; } - Integer value = dialogs_read_inbox_max.get(dialog_id); + Integer value = dialogs_read_inbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(false, dialog_id); + value = getMessagesStorage().getDialogReadMax(false, dialogId); } - dialogs_read_inbox_max.put(dialog_id, Math.max(value, update.max_id)); + dialogs_read_inbox_max.put(dialogId, Math.max(value, update.max_id)); } else if (baseUpdate instanceof TLRPC.TL_updateReadHistoryOutbox) { TLRPC.TL_updateReadHistoryOutbox update = (TLRPC.TL_updateReadHistoryOutbox) baseUpdate; - long dialog_id; + long dialogId; if (markAsReadMessagesOutbox == null) { - markAsReadMessagesOutbox = new SparseLongArray(); + markAsReadMessagesOutbox = new LongSparseIntArray(); } if (update.peer.chat_id != 0) { markAsReadMessagesOutbox.put(-update.peer.chat_id, update.max_id); - dialog_id = -update.peer.chat_id; + dialogId = -update.peer.chat_id; } else { markAsReadMessagesOutbox.put(update.peer.user_id, update.max_id); - dialog_id = update.peer.user_id; + dialogId = update.peer.user_id; TLRPC.User user = getUser(update.peer.user_id); if (user != null && user.status != null && user.status.expires <= 0 && Math.abs(getConnectionsManager().getCurrentTime() - date) < 30) { onlinePrivacy.put(update.peer.user_id, date); interfaceUpdateMask |= UPDATE_MASK_STATUS; } } - Integer value = dialogs_read_outbox_max.get(dialog_id); + Integer value = dialogs_read_outbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(true, dialog_id); + value = getMessagesStorage().getDialogReadMax(true, dialogId); } - dialogs_read_outbox_max.put(dialog_id, Math.max(value, update.max_id)); + dialogs_read_outbox_max.put(dialogId, Math.max(value, update.max_id)); } else if (baseUpdate instanceof TLRPC.TL_updateDeleteMessages) { TLRPC.TL_updateDeleteMessages update = (TLRPC.TL_updateDeleteMessages) baseUpdate; if (deletedMessages == null) { - deletedMessages = new SparseArray<>(); + deletedMessages = new LongSparseArray<>(); } ArrayList arrayList = deletedMessages.get(0); if (arrayList == null) { @@ -11994,23 +11956,18 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_updateDeleteScheduledMessages update = (TLRPC.TL_updateDeleteScheduledMessages) baseUpdate; if (scheduledDeletedMessages == null) { - scheduledDeletedMessages = new SparseArray<>(); - } - ArrayList arrayList; - int id; - if (update.peer instanceof TLRPC.TL_peerChannel) { - arrayList = scheduledDeletedMessages.get(id = update.peer.channel_id); - } else { - arrayList = scheduledDeletedMessages.get(id = 0); + scheduledDeletedMessages = new LongSparseArray<>(); } + long id = MessageObject.getPeerId(update.peer); + ArrayList arrayList = scheduledDeletedMessages.get(MessageObject.getPeerId(update.peer)); if (arrayList == null) { arrayList = new ArrayList<>(); scheduledDeletedMessages.put(id, arrayList); } arrayList.addAll(update.messages); } else if (baseUpdate instanceof TLRPC.TL_updateUserTyping || baseUpdate instanceof TLRPC.TL_updateChatUserTyping || baseUpdate instanceof TLRPC.TL_updateChannelUserTyping) { - int userId; - int chatId; + long userId; + long chatId; int threadId; TLRPC.SendMessageAction action; if (baseUpdate instanceof TLRPC.TL_updateChannelUserTyping) { @@ -12031,6 +11988,17 @@ public class MessagesController extends BaseController implements NotificationCe action = update.action; chatId = 0; threadId = 0; + if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) { + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.onEmojiInteractionsReceived, update.user_id, update.action)); + continue; + } + +// if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) { +// if (emojiInteractions == null) { +// emojiInteractions = new ArrayList<>(); +// } +// emojiInteractions.add(update.action); +// } } else { TLRPC.TL_updateChatUserTyping update = (TLRPC.TL_updateChatUserTyping) baseUpdate; chatId = update.chat_id; @@ -12043,6 +12011,18 @@ public class MessagesController extends BaseController implements NotificationCe } action = update.action; threadId = 0; + + if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) { + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.onEmojiInteractionsReceived, -update.chat_id, update.action)); + continue; + } + +// if (update.action instanceof TLRPC.TL_sendMessageEmojiInteraction) { +// if (emojiInteractions == null) { +// emojiInteractions = new ArrayList<>(); +// } +// emojiInteractions.add(update.action); +// } } long uid = -chatId; if (uid == 0) { @@ -12050,7 +12030,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (action instanceof TLRPC.TL_sendMessageHistoryImportAction) { if (importingActions == null) { - importingActions = new LongSparseArray<>(); + importingActions = new LongSparseIntArray(); } TLRPC.TL_sendMessageHistoryImportAction importAction = (TLRPC.TL_sendMessageHistoryImportAction) action; importingActions.put(uid, importAction.progress); @@ -12058,9 +12038,9 @@ public class MessagesController extends BaseController implements NotificationCe if (action instanceof TLRPC.TL_speakingInGroupCallAction) { if (chatId != 0) { if (groupSpeakingActions == null) { - groupSpeakingActions = new SparseArray<>(); + groupSpeakingActions = new LongSparseArray<>(); } - ArrayList uids = groupSpeakingActions.get(chatId); + ArrayList uids = groupSpeakingActions.get(chatId); if (uids == null) { uids = new ArrayList<>(); groupSpeakingActions.put(chatId, uids); @@ -12190,7 +12170,7 @@ public class MessagesController extends BaseController implements NotificationCe ArrayList decryptedMessages = getSecretChatHelper().decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) baseUpdate).message); if (decryptedMessages != null && !decryptedMessages.isEmpty()) { int cid = ((TLRPC.TL_updateNewEncryptedMessage) baseUpdate).message.chat_id; - long uid = ((long) cid) << 32; + long uid = DialogObject.makeEncryptedDialogId(cid); if (messages == null) { messages = new LongSparseArray<>(); } @@ -12219,7 +12199,7 @@ public class MessagesController extends BaseController implements NotificationCe TLRPC.TL_updateEncryptedChatTyping update = (TLRPC.TL_updateEncryptedChatTyping) baseUpdate; TLRPC.EncryptedChat encryptedChat = getEncryptedChatDB(update.chat_id, true); if (encryptedChat != null) { - long uid = ((long) update.chat_id) << 32; + long uid = DialogObject.makeEncryptedDialogId(update.chat_id); ConcurrentHashMap> threads = printingUsers.get(uid); if (threads == null) { threads = new ConcurrentHashMap<>(); @@ -12273,9 +12253,9 @@ public class MessagesController extends BaseController implements NotificationCe } else if (baseUpdate instanceof TLRPC.TL_updateEncryption) { getSecretChatHelper().processUpdateEncryption((TLRPC.TL_updateEncryption) baseUpdate, usersDict); } else if (baseUpdate instanceof TLRPC.TL_updatePeerBlocked) { - final TLRPC.TL_updatePeerBlocked finalUpdate = (TLRPC.TL_updatePeerBlocked) baseUpdate; + TLRPC.TL_updatePeerBlocked finalUpdate = (TLRPC.TL_updatePeerBlocked) baseUpdate; getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { - int id = MessageObject.getPeerId(finalUpdate.peer_id); + long id = MessageObject.getPeerId(finalUpdate.peer_id); if (finalUpdate.blocked) { if (blockePeers.indexOfKey(id) < 0) { blockePeers.put(id, 1); @@ -12291,7 +12271,7 @@ public class MessagesController extends BaseController implements NotificationCe } updatesOnMainThread.add(baseUpdate); } else if (baseUpdate instanceof TLRPC.TL_updateServiceNotification) { - final TLRPC.TL_updateServiceNotification update = (TLRPC.TL_updateServiceNotification) baseUpdate; + TLRPC.TL_updateServiceNotification update = (TLRPC.TL_updateServiceNotification) baseUpdate; if (update.popup && update.message != null && update.message.length() > 0) { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.needShowAlert, 2, update.message, update.type)); } @@ -12379,7 +12359,7 @@ public class MessagesController extends BaseController implements NotificationCe if (BuildVars.LOGS_ENABLED) { FileLog.d(baseUpdate + " channelId = " + update.channel_id); } - int channelPts = channelsPts.get(update.channel_id); + int channelPts = channelsPts.get(update.channel_id, 0); if (channelPts == 0) { channelPts = getMessagesStorage().getChannelPtsSync(update.channel_id); if (channelPts == 0) { @@ -12409,47 +12389,44 @@ public class MessagesController extends BaseController implements NotificationCe } } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelInbox) { TLRPC.TL_updateReadChannelInbox update = (TLRPC.TL_updateReadChannelInbox) baseUpdate; - long message_id = update.max_id; - message_id |= ((long) update.channel_id) << 32; - long dialog_id = -update.channel_id; if (markAsReadMessagesInbox == null) { - markAsReadMessagesInbox = new SparseLongArray(); + markAsReadMessagesInbox = new LongSparseIntArray(); } - markAsReadMessagesInbox.put(-update.channel_id, message_id); - Integer value = dialogs_read_inbox_max.get(dialog_id); + long dialogId = -update.channel_id; + markAsReadMessagesInbox.put(dialogId, update.max_id); + Integer value = dialogs_read_inbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(false, dialog_id); + value = getMessagesStorage().getDialogReadMax(false, dialogId); } - dialogs_read_inbox_max.put(dialog_id, Math.max(value, update.max_id)); + dialogs_read_inbox_max.put(dialogId, Math.max(value, update.max_id)); } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelOutbox) { TLRPC.TL_updateReadChannelOutbox update = (TLRPC.TL_updateReadChannelOutbox) baseUpdate; if (BuildVars.LOGS_ENABLED) { FileLog.d(baseUpdate + " channelId = " + update.channel_id); } - long message_id = update.max_id; - message_id |= ((long) update.channel_id) << 32; - long dialog_id = -update.channel_id; if (markAsReadMessagesOutbox == null) { - markAsReadMessagesOutbox = new SparseLongArray(); + markAsReadMessagesOutbox = new LongSparseIntArray(); } - markAsReadMessagesOutbox.put(-update.channel_id, message_id); - Integer value = dialogs_read_outbox_max.get(dialog_id); + long dialogId = -update.channel_id; + markAsReadMessagesOutbox.put(dialogId, update.max_id); + Integer value = dialogs_read_outbox_max.get(dialogId); if (value == null) { - value = getMessagesStorage().getDialogReadMax(true, dialog_id); + value = getMessagesStorage().getDialogReadMax(true, dialogId); } - dialogs_read_outbox_max.put(dialog_id, Math.max(value, update.max_id)); + dialogs_read_outbox_max.put(dialogId, Math.max(value, update.max_id)); } else if (baseUpdate instanceof TLRPC.TL_updateDeleteChannelMessages) { TLRPC.TL_updateDeleteChannelMessages update = (TLRPC.TL_updateDeleteChannelMessages) baseUpdate; if (BuildVars.LOGS_ENABLED) { FileLog.d(baseUpdate + " channelId = " + update.channel_id); } if (deletedMessages == null) { - deletedMessages = new SparseArray<>(); + deletedMessages = new LongSparseArray<>(); } - ArrayList arrayList = deletedMessages.get(update.channel_id); + long dialogId = -update.channel_id; + ArrayList arrayList = deletedMessages.get(dialogId); if (arrayList == null) { arrayList = new ArrayList<>(); - deletedMessages.put(update.channel_id, arrayList); + deletedMessages.put(dialogId, arrayList); } arrayList.addAll(update.messages); } else if (baseUpdate instanceof TLRPC.TL_updateChannel) { @@ -12472,12 +12449,13 @@ public class MessagesController extends BaseController implements NotificationCe FileLog.d(baseUpdate + " channelId = " + update.channel_id); } if (channelViews == null) { - channelViews = new SparseArray<>(); + channelViews = new LongSparseArray<>(); } - SparseIntArray array = channelViews.get(update.channel_id); + long dialogId = -update.channel_id; + SparseIntArray array = channelViews.get(dialogId); if (array == null) { array = new SparseIntArray(); - channelViews.put(update.channel_id, array); + channelViews.put(dialogId, array); } array.put(update.id, update.views); } else if (baseUpdate instanceof TLRPC.TL_updateChannelMessageForwards) { @@ -12486,12 +12464,13 @@ public class MessagesController extends BaseController implements NotificationCe FileLog.d(baseUpdate + " channelId = " + update.channel_id); } if (channelForwards == null) { - channelForwards = new SparseArray<>(); + channelForwards = new LongSparseArray<>(); } - SparseIntArray array = channelForwards.get(update.channel_id); + long dialogId = -update.channel_id; + SparseIntArray array = channelForwards.get(dialogId); if (array == null) { array = new SparseIntArray(); - channelForwards.put(update.channel_id, array); + channelForwards.put(dialogId, array); } array.put(update.id, update.forwards); } else if (baseUpdate instanceof TLRPC.TL_updateChatParticipantAdmin) { @@ -12499,7 +12478,7 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().updateChatInfo(update.chat_id, update.user_id, 2, update.is_admin ? 1 : 0, update.version); } else if (baseUpdate instanceof TLRPC.TL_updateChatDefaultBannedRights) { TLRPC.TL_updateChatDefaultBannedRights update = (TLRPC.TL_updateChatDefaultBannedRights) baseUpdate; - int chatId; + long chatId; if (update.peer.channel_id != 0) { chatId = update.peer.channel_id; } else { @@ -12562,13 +12541,13 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0, count = message.entities.size(); a < count; a++) { TLRPC.MessageEntity entity = message.entities.get(a); if (entity instanceof TLRPC.TL_messageEntityMentionName) { - int user_id = ((TLRPC.TL_messageEntityMentionName) entity).user_id; - TLRPC.User user = usersDict.get(user_id); + long userId = ((TLRPC.TL_messageEntityMentionName) entity).user_id; + TLRPC.User user = usersDict.get(userId); if (user == null || user.min) { - user = getUser(user_id); + user = getUser(userId); } if (user == null || user.min) { - user = getMessagesStorage().getUserSync(user_id); + user = getMessagesStorage().getUserSync(userId); if (user != null && user.min) { user = null; } @@ -12676,11 +12655,12 @@ public class MessagesController extends BaseController implements NotificationCe } else if (baseUpdate instanceof TLRPC.TL_updateChannelAvailableMessages) { TLRPC.TL_updateChannelAvailableMessages update = (TLRPC.TL_updateChannelAvailableMessages) baseUpdate; if (clearHistoryMessages == null) { - clearHistoryMessages = new SparseIntArray(); + clearHistoryMessages = new LongSparseIntArray(); } - int currentValue = clearHistoryMessages.get(update.channel_id); + long dialogId = -update.channel_id; + int currentValue = clearHistoryMessages.get(dialogId, 0); if (currentValue == 0 || currentValue < update.available_min_id) { - clearHistoryMessages.put(update.channel_id, update.available_min_id); + clearHistoryMessages.put(dialogId, update.available_min_id); } } else if (baseUpdate instanceof TLRPC.TL_updateDialogUnreadMark) { if (updatesOnMainThread == null) { @@ -12700,15 +12680,8 @@ public class MessagesController extends BaseController implements NotificationCe updatesOnMainThread.add(baseUpdate); } else if (baseUpdate instanceof TLRPC.TL_updateMessageReactions) { TLRPC.TL_updateMessageReactions update = (TLRPC.TL_updateMessageReactions) baseUpdate; - long dialogId; - if (update.peer.chat_id != 0) { - dialogId = -update.peer.chat_id; - } else if (update.peer.channel_id != 0) { - dialogId = -update.peer.channel_id; - } else { - dialogId = update.peer.user_id; - } - getMessagesStorage().updateMessageReactions(dialogId, update.msg_id, update.peer.channel_id, update.reactions); + long dialogId = MessageObject.getPeerId(update.peer); + getMessagesStorage().updateMessageReactions(dialogId, update.msg_id, update.reactions); if (updatesOnMainThread == null) { updatesOnMainThread = new ArrayList<>(); } @@ -12771,15 +12744,15 @@ public class MessagesController extends BaseController implements NotificationCe updatePrintingStrings(); } - final int interfaceUpdateMaskFinal = interfaceUpdateMask; - final boolean printChangedArg = printChanged; + int interfaceUpdateMaskFinal = interfaceUpdateMask; + boolean printChangedArg = printChanged; if (contactsIds != null) { getContactsController().processContactsUpdates(contactsIds, usersDict); } if (pushMessages != null) { - final ArrayList pushMessagesFinal = pushMessages; + ArrayList pushMessagesFinal = pushMessages; getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> getNotificationsController().processNewMessages(pushMessagesFinal, true, false, null))); } @@ -12800,12 +12773,12 @@ public class MessagesController extends BaseController implements NotificationCe } getMessagesStorage().putMessages(messagesRes, editingMessages.keyAt(b), -2, 0, false, false); } - final LongSparseArray> editingMessagesFinal = editingMessages; + LongSparseArray> editingMessagesFinal = editingMessages; getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> getNotificationsController().processEditedMessages(editingMessagesFinal))); } if (channelViews != null || channelForwards != null || channelReplies != null) { - getMessagesStorage().putChannelViews(channelViews, channelForwards, channelReplies, true, true); + getMessagesStorage().putChannelViews(channelViews, channelForwards, channelReplies, true); } if (folderUpdates != null) { for (int a = 0, size = folderUpdates.size(); a < size; a++) { @@ -12813,20 +12786,20 @@ public class MessagesController extends BaseController implements NotificationCe } } - final LongSparseArray> editingMessagesFinal = editingMessages; - final SparseArray channelViewsFinal = channelViews; - final SparseArray channelForwardsFinal = channelForwards; - final SparseArray> channelRepliesFinal = channelReplies; - final LongSparseArray webPagesFinal = webPages; - final LongSparseArray> messagesFinal = messages; - final LongSparseArray> scheduledMessagesFinal = scheduledMessages; - final ArrayList chatInfoToUpdateFinal = chatInfoToUpdate; - final ArrayList contactsIdsFinal = contactsIds; - final ArrayList updatesOnMainThreadFinal = updatesOnMainThread; - final ArrayList updateMessageThumbs = messageThumbs; - final ArrayList folderUpdatesFinal = folderUpdates; - final SparseArray> groupSpeakingActionsFinal = groupSpeakingActions; - final LongSparseArray importingActionsFinal = importingActions; + LongSparseArray> editingMessagesFinal = editingMessages; + LongSparseArray channelViewsFinal = channelViews; + LongSparseArray channelForwardsFinal = channelForwards; + LongSparseArray> channelRepliesFinal = channelReplies; + LongSparseArray webPagesFinal = webPages; + LongSparseArray> messagesFinal = messages; + LongSparseArray> scheduledMessagesFinal = scheduledMessages; + ArrayList chatInfoToUpdateFinal = chatInfoToUpdate; + ArrayList contactsIdsFinal = contactsIds; + ArrayList updatesOnMainThreadFinal = updatesOnMainThread; + ArrayList updateMessageThumbs = messageThumbs; + ArrayList folderUpdatesFinal = folderUpdates; + LongSparseArray> groupSpeakingActionsFinal = groupSpeakingActions; + LongSparseIntArray importingActionsFinal = importingActions; AndroidUtilities.runOnUIThread(() -> { int updateMask = interfaceUpdateMaskFinal; @@ -12838,7 +12811,7 @@ public class MessagesController extends BaseController implements NotificationCe ArrayList dbUsersStatus = new ArrayList<>(); SharedPreferences.Editor editor = null; for (int a = 0, size = updatesOnMainThreadFinal.size(); a < size; a++) { - final TLRPC.Update baseUpdate = updatesOnMainThreadFinal.get(a); + TLRPC.Update baseUpdate = updatesOnMainThreadFinal.get(a); if (baseUpdate instanceof TLRPC.TL_updatePrivacy) { TLRPC.TL_updatePrivacy update = (TLRPC.TL_updatePrivacy) baseUpdate; if (update.key instanceof TLRPC.TL_privacyKeyStatusTimestamp) { @@ -12860,7 +12833,7 @@ public class MessagesController extends BaseController implements NotificationCe } } else if (baseUpdate instanceof TLRPC.TL_updateUserStatus) { TLRPC.TL_updateUserStatus update = (TLRPC.TL_updateUserStatus) baseUpdate; - final TLRPC.User currentUser = getUser(update.user_id); + TLRPC.User currentUser = getUser(update.user_id); if (update.status instanceof TLRPC.TL_userStatusRecently) { update.status.expires = -100; @@ -12873,7 +12846,7 @@ public class MessagesController extends BaseController implements NotificationCe currentUser.id = update.user_id; currentUser.status = update.status; } - final TLRPC.User toDbUser = new TLRPC.TL_user(); + TLRPC.User toDbUser = new TLRPC.TL_user(); toDbUser.id = update.user_id; toDbUser.status = update.status; dbUsersStatus.add(toDbUser); @@ -12882,7 +12855,7 @@ public class MessagesController extends BaseController implements NotificationCe } } else if (baseUpdate instanceof TLRPC.TL_updateUserName) { TLRPC.TL_updateUserName update = (TLRPC.TL_updateUserName) baseUpdate; - final TLRPC.User currentUser = getUser(update.user_id); + TLRPC.User currentUser = getUser(update.user_id); if (currentUser != null) { if (!UserObject.isContact(currentUser)) { currentUser.first_name = update.first_name; @@ -12896,7 +12869,7 @@ public class MessagesController extends BaseController implements NotificationCe } currentUser.username = update.username; } - final TLRPC.User toDbUser = new TLRPC.TL_user(); + TLRPC.User toDbUser = new TLRPC.TL_user(); toDbUser.id = update.user_id; toDbUser.first_name = update.first_name; toDbUser.last_name = update.last_name; @@ -12947,11 +12920,11 @@ public class MessagesController extends BaseController implements NotificationCe loadPinnedDialogs(update.folder_id, 0, order); } else if (baseUpdate instanceof TLRPC.TL_updateUserPhoto) { TLRPC.TL_updateUserPhoto update = (TLRPC.TL_updateUserPhoto) baseUpdate; - final TLRPC.User currentUser = getUser(update.user_id); + TLRPC.User currentUser = getUser(update.user_id); if (currentUser != null) { currentUser.photo = update.photo; } - final TLRPC.User toDbUser = new TLRPC.TL_user(); + TLRPC.User toDbUser = new TLRPC.TL_user(); toDbUser.id = update.user_id; toDbUser.photo = update.photo; dbUsers.add(toDbUser); @@ -12960,7 +12933,7 @@ public class MessagesController extends BaseController implements NotificationCe } } else if (baseUpdate instanceof TLRPC.TL_updateUserPhone) { TLRPC.TL_updateUserPhone update = (TLRPC.TL_updateUserPhone) baseUpdate; - final TLRPC.User currentUser = getUser(update.user_id); + TLRPC.User currentUser = getUser(update.user_id); if (currentUser != null) { currentUser.phone = update.phone; Utilities.phoneBookQueue.postRunnable(() -> getContactsController().addContactToPhoneBook(currentUser, true)); @@ -12968,7 +12941,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged); } } - final TLRPC.User toDbUser = new TLRPC.TL_user(); + TLRPC.User toDbUser = new TLRPC.TL_user(); toDbUser.id = update.user_id; toDbUser.phone = update.phone; dbUsers.add(toDbUser); @@ -12982,54 +12955,54 @@ public class MessagesController extends BaseController implements NotificationCe int currentTime1 = getConnectionsManager().getCurrentTime(); if (update.peer instanceof TLRPC.TL_notifyPeer) { TLRPC.TL_notifyPeer notifyPeer = (TLRPC.TL_notifyPeer) update.peer; - long dialog_id; + long dialogId; if (notifyPeer.peer.user_id != 0) { - dialog_id = notifyPeer.peer.user_id; + dialogId = notifyPeer.peer.user_id; } else if (notifyPeer.peer.chat_id != 0) { - dialog_id = -notifyPeer.peer.chat_id; + dialogId = -notifyPeer.peer.chat_id; } else { - dialog_id = -notifyPeer.peer.channel_id; + dialogId = -notifyPeer.peer.channel_id; } - TLRPC.Dialog dialog = dialogs_dict.get(dialog_id); + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null) { dialog.notify_settings = update.notify_settings; } if ((update.notify_settings.flags & 2) != 0) { - editor.putBoolean("silent_" + dialog_id, update.notify_settings.silent); + editor.putBoolean("silent_" + dialogId, update.notify_settings.silent); } else { - editor.remove("silent_" + dialog_id); + editor.remove("silent_" + dialogId); } if ((update.notify_settings.flags & 4) != 0) { if (update.notify_settings.mute_until > currentTime1) { int until = 0; if (update.notify_settings.mute_until > currentTime1 + 60 * 60 * 24 * 365) { - editor.putInt("notify2_" + dialog_id, 2); + editor.putInt("notify2_" + dialogId, 2); if (dialog != null) { update.notify_settings.mute_until = Integer.MAX_VALUE; } } else { until = update.notify_settings.mute_until; - editor.putInt("notify2_" + dialog_id, 3); - editor.putInt("notifyuntil_" + dialog_id, update.notify_settings.mute_until); + editor.putInt("notify2_" + dialogId, 3); + editor.putInt("notifyuntil_" + dialogId, update.notify_settings.mute_until); if (dialog != null) { update.notify_settings.mute_until = until; } } - getMessagesStorage().setDialogFlags(dialog_id, ((long) until << 32) | 1); - getNotificationsController().removeNotificationsForDialog(dialog_id); + getMessagesStorage().setDialogFlags(dialogId, ((long) until << 32) | 1); + getNotificationsController().removeNotificationsForDialog(dialogId); } else { if (dialog != null) { update.notify_settings.mute_until = 0; } - editor.putInt("notify2_" + dialog_id, 0); - getMessagesStorage().setDialogFlags(dialog_id, 0); + editor.putInt("notify2_" + dialogId, 0); + getMessagesStorage().setDialogFlags(dialogId, 0); } } else { if (dialog != null) { update.notify_settings.mute_until = 0; } - editor.remove("notify2_" + dialog_id); - getMessagesStorage().setDialogFlags(dialog_id, 0); + editor.remove("notify2_" + dialogId); + getMessagesStorage().setDialogFlags(dialogId, 0); } } else if (update.peer instanceof TLRPC.TL_notifyChats) { if ((update.notify_settings.flags & 1) != 0) { @@ -13089,8 +13062,8 @@ public class MessagesController extends BaseController implements NotificationCe getMessagesStorage().updateMutedDialogsFiltersCounters(); } } else if (baseUpdate instanceof TLRPC.TL_updateChannel) { - final TLRPC.TL_updateChannel update = (TLRPC.TL_updateChannel) baseUpdate; - TLRPC.Dialog dialog = dialogs_dict.get(-(long) update.channel_id); + TLRPC.TL_updateChannel update = (TLRPC.TL_updateChannel) baseUpdate; + TLRPC.Dialog dialog = dialogs_dict.get(-update.channel_id); TLRPC.Chat chat = getChat(update.channel_id); if (chat != null) { if (dialog == null && chat instanceof TLRPC.TL_channel && !chat.left) { @@ -13116,7 +13089,7 @@ public class MessagesController extends BaseController implements NotificationCe updateMask |= UPDATE_MASK_CHAT; loadFullChat(update.channel_id, 0, true); } else if (baseUpdate instanceof TLRPC.TL_updateChat) { - final TLRPC.TL_updateChat update = (TLRPC.TL_updateChat) baseUpdate; + TLRPC.TL_updateChat update = (TLRPC.TL_updateChat) baseUpdate; TLRPC.Chat chat = getChat(update.chat_id); if (chat != null && (chat instanceof TLRPC.TL_chatForbidden || chat.kicked)) { ChatObject.Call call = getGroupCall(chat.id, false); @@ -13140,7 +13113,7 @@ public class MessagesController extends BaseController implements NotificationCe loadFullChat(update.chat_id, 0, true); } else if (baseUpdate instanceof TLRPC.TL_updateChatDefaultBannedRights) { TLRPC.TL_updateChatDefaultBannedRights update = (TLRPC.TL_updateChatDefaultBannedRights) baseUpdate; - int chatId; + long chatId; if (update.peer.channel_id != 0) { chatId = update.peer.channel_id; } else { @@ -13365,21 +13338,21 @@ public class MessagesController extends BaseController implements NotificationCe loadRemoteFilters(true); } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionInbox) { TLRPC.TL_updateReadChannelDiscussionInbox update = (TLRPC.TL_updateReadChannelDiscussionInbox) baseUpdate; - getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, (long) -update.channel_id, update.top_msg_id, update.read_max_id, 0); + getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, -update.channel_id, update.top_msg_id, update.read_max_id, 0); if ((update.flags & 1) != 0) { getMessagesStorage().updateRepliesMaxReadId(update.broadcast_id, update.broadcast_post, update.read_max_id, true); getNotificationCenter().postNotificationName(NotificationCenter.commentsRead, update.broadcast_id, update.broadcast_post, update.read_max_id); } } else if (baseUpdate instanceof TLRPC.TL_updateReadChannelDiscussionOutbox) { TLRPC.TL_updateReadChannelDiscussionOutbox update = (TLRPC.TL_updateReadChannelDiscussionOutbox) baseUpdate; - getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, (long) -update.channel_id, update.top_msg_id, 0, update.read_max_id); + getNotificationCenter().postNotificationName(NotificationCenter.threadMessagesRead, -update.channel_id, update.top_msg_id, 0, update.read_max_id); } else if (baseUpdate instanceof TLRPC.TL_updatePeerHistoryTTL) { TLRPC.TL_updatePeerHistoryTTL updatePeerHistoryTTL = (TLRPC.TL_updatePeerHistoryTTL) baseUpdate; - int lowerId = MessageObject.getPeerId(updatePeerHistoryTTL.peer); + long peerId = MessageObject.getPeerId(updatePeerHistoryTTL.peer); TLRPC.ChatFull chatFull = null; TLRPC.UserFull userFull = null; - if (lowerId > 0) { - userFull = getUserFull(lowerId); + if (peerId > 0) { + userFull = getUserFull(peerId); if (userFull != null) { userFull.ttl_period = updatePeerHistoryTTL.ttl_period; if (userFull.ttl_period == 0) { @@ -13389,7 +13362,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } else { - chatFull = getChatFull(-lowerId); + chatFull = getChatFull(-peerId); if (chatFull != null) { chatFull.ttl_period = updatePeerHistoryTTL.ttl_period; if (chatFull instanceof TLRPC.TL_channelFull) { @@ -13411,7 +13384,7 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, chatFull, 0, false, false); getMessagesStorage().updateChatInfo(chatFull, false); } else if (userFull != null) { - getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, lowerId, userFull); + getNotificationCenter().postNotificationName(NotificationCenter.userInfoDidLoad, peerId, userFull); getMessagesStorage().updateUserInfo(userFull, false); } } @@ -13425,7 +13398,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (groupSpeakingActionsFinal != null) { for (int a = 0, N = groupSpeakingActionsFinal.size(); a < N; a++) { - int chatId = groupSpeakingActionsFinal.keyAt(a); + long chatId = groupSpeakingActionsFinal.keyAt(a); ChatObject.Call call = groupCallsByChatId.get(chatId); if (call != null) { call.processTypingsUpdate(getAccountInstance(), groupSpeakingActionsFinal.valueAt(a), date); @@ -13455,12 +13428,12 @@ public class MessagesController extends BaseController implements NotificationCe if (arrayList != null) { TLRPC.WebPage webpage = webPagesFinal.valueAt(b); ArrayList arr = new ArrayList<>(); - long dialog_id = 0; + long dialogId = 0; if (webpage instanceof TLRPC.TL_webPage || webpage instanceof TLRPC.TL_webPageEmpty) { for (int a = 0, size2 = arrayList.size(); a < size2; a++) { arrayList.get(a).messageOwner.media.webpage = webpage; if (a == 0) { - dialog_id = arrayList.get(a).getDialogId(); + dialogId = arrayList.get(a).getDialogId(); ImageLoader.saveMessageThumbs(arrayList.get(a).messageOwner); } arr.add(arrayList.get(a).messageOwner); @@ -13470,7 +13443,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (!arr.isEmpty()) { getMessagesStorage().putMessages(arr, true, true, false, getDownloadController().getAutodownloadMask(), i == 1); - getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialog_id, arrayList); + getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, arrayList); } } } @@ -13516,14 +13489,14 @@ public class MessagesController extends BaseController implements NotificationCe } if (editingMessagesFinal != null) { for (int b = 0, size = editingMessagesFinal.size(); b < size; b++) { - long dialog_id = editingMessagesFinal.keyAt(b); + long dialogId = editingMessagesFinal.keyAt(b); ArrayList arrayList = editingMessagesFinal.valueAt(b); - MessageObject oldObject = dialogMessage.get(dialog_id); + MessageObject oldObject = dialogMessage.get(dialogId); if (oldObject != null) { for (int a = 0, size2 = arrayList.size(); a < size2; a++) { MessageObject newMessage = arrayList.get(a); if (oldObject.getId() == newMessage.getId()) { - dialogMessage.put(dialog_id, newMessage); + dialogMessage.put(dialogId, newMessage); if (newMessage.messageOwner.peer_id != null && newMessage.messageOwner.peer_id.channel_id == 0) { dialogMessagesByIds.put(newMessage.getId(), newMessage); } @@ -13537,8 +13510,8 @@ public class MessagesController extends BaseController implements NotificationCe } } } - getMediaDataController().loadReplyMessagesForMessages(arrayList, dialog_id, false, null); - getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialog_id, arrayList, false); + getMediaDataController().loadReplyMessagesForMessages(arrayList, dialogId, false, null); + getNotificationCenter().postNotificationName(NotificationCenter.replaceMessagesObjects, dialogId, arrayList, false); } } if (updateDialogs) { @@ -13570,13 +13543,13 @@ public class MessagesController extends BaseController implements NotificationCe } }); - final SparseLongArray markAsReadMessagesInboxFinal = markAsReadMessagesInbox; - final SparseLongArray markAsReadMessagesOutboxFinal = markAsReadMessagesOutbox; - final ArrayList markAsReadMessagesFinal = markAsReadMessages; - final SparseIntArray markAsReadEncryptedFinal = markAsReadEncrypted; - final SparseArray> deletedMessagesFinal = deletedMessages; - final SparseArray> scheduledDeletedMessagesFinal = scheduledDeletedMessages; - final SparseIntArray clearHistoryMessagesFinal = clearHistoryMessages; + LongSparseIntArray markAsReadMessagesInboxFinal = markAsReadMessagesInbox; + LongSparseIntArray markAsReadMessagesOutboxFinal = markAsReadMessagesOutbox; + LongSparseArray> markContentAsReadMessagesFinal = markContentAsReadMessages; + SparseIntArray markAsReadEncryptedFinal = markAsReadEncrypted; + LongSparseArray> deletedMessagesFinal = deletedMessages; + LongSparseArray> scheduledDeletedMessagesFinal = scheduledDeletedMessages; + LongSparseIntArray clearHistoryMessagesFinal = clearHistoryMessages; getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { int updateMask = 0; if (markAsReadMessagesInboxFinal != null || markAsReadMessagesOutboxFinal != null) { @@ -13585,8 +13558,8 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationsController().processReadMessages(markAsReadMessagesInboxFinal, 0, 0, 0, false); SharedPreferences.Editor editor = notificationsPreferences.edit(); for (int b = 0, size = markAsReadMessagesInboxFinal.size(); b < size; b++) { - int key = markAsReadMessagesInboxFinal.keyAt(b); - int messageId = (int) markAsReadMessagesInboxFinal.valueAt(b); + long key = markAsReadMessagesInboxFinal.keyAt(b); + int messageId = markAsReadMessagesInboxFinal.valueAt(b); TLRPC.Dialog dialog = dialogs_dict.get(key); if (dialog != null && dialog.top_message > 0 && dialog.top_message <= messageId) { MessageObject obj = dialogMessage.get(dialog.id); @@ -13604,8 +13577,8 @@ public class MessagesController extends BaseController implements NotificationCe } if (markAsReadMessagesOutboxFinal != null) { for (int b = 0, size = markAsReadMessagesOutboxFinal.size(); b < size; b++) { - int key = markAsReadMessagesOutboxFinal.keyAt(b); - int messageId = (int) markAsReadMessagesOutboxFinal.valueAt(b); + long key = markAsReadMessagesOutboxFinal.keyAt(b); + int messageId = markAsReadMessagesOutboxFinal.valueAt(b); TLRPC.Dialog dialog = dialogs_dict.get(key); if (dialog != null && dialog.top_message > 0 && dialog.top_message <= messageId) { MessageObject obj = dialogMessage.get(dialog.id); @@ -13622,10 +13595,10 @@ public class MessagesController extends BaseController implements NotificationCe int key = markAsReadEncryptedFinal.keyAt(a); int value = markAsReadEncryptedFinal.valueAt(a); getNotificationCenter().postNotificationName(NotificationCenter.messagesReadEncrypted, key, value); - long dialog_id = (long) (key) << 32; - TLRPC.Dialog dialog = dialogs_dict.get(dialog_id); + long dialogId = DialogObject.makeEncryptedDialogId(key); + TLRPC.Dialog dialog = dialogs_dict.get(dialogId); if (dialog != null) { - MessageObject message = dialogMessage.get(dialog_id); + MessageObject message = dialogMessage.get(dialogId); if (message != null && message.messageOwner.date <= value) { message.setIsRead(); updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE; @@ -13633,18 +13606,22 @@ public class MessagesController extends BaseController implements NotificationCe } } } - if (markAsReadMessagesFinal != null) { - getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, markAsReadMessagesFinal); + if (markContentAsReadMessagesFinal != null) { + for (int a = 0, size = markContentAsReadMessagesFinal.size(); a < size; a++) { + long key = markContentAsReadMessagesFinal.keyAt(a); + ArrayList value = markContentAsReadMessagesFinal.valueAt(a); + getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, key, value); + } } if (deletedMessagesFinal != null) { for (int a = 0, size = deletedMessagesFinal.size(); a < size; a++) { - int key = deletedMessagesFinal.keyAt(a); + long dialogId = deletedMessagesFinal.keyAt(a); ArrayList arrayList = deletedMessagesFinal.valueAt(a); if (arrayList == null) { continue; } - getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, key, false); - if (key == 0) { + getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, -dialogId, false); + if (dialogId == 0) { for (int b = 0, size2 = arrayList.size(); b < size2; b++) { Integer id = arrayList.get(b); MessageObject obj = dialogMessagesByIds.get(id); @@ -13656,7 +13633,7 @@ public class MessagesController extends BaseController implements NotificationCe } } } else { - MessageObject obj = dialogMessage.get(-key); + MessageObject obj = dialogMessage.get(dialogId); if (obj != null) { for (int b = 0, size2 = arrayList.size(); b < size2; b++) { if (obj.getId() == arrayList.get(b)) { @@ -13671,17 +13648,18 @@ public class MessagesController extends BaseController implements NotificationCe } if (scheduledDeletedMessagesFinal != null) { for (int a = 0, size = scheduledDeletedMessagesFinal.size(); a < size; a++) { - int key = scheduledDeletedMessagesFinal.keyAt(a); + long key = scheduledDeletedMessagesFinal.keyAt(a); ArrayList arrayList = scheduledDeletedMessagesFinal.valueAt(a); if (arrayList == null) { continue; } - getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, key, true); + + getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, arrayList, DialogObject.isChatDialog(key) && ChatObject.isChannel(getChat(-key)) ? -key : 0, true); } } if (clearHistoryMessagesFinal != null) { for (int a = 0, size = clearHistoryMessagesFinal.size(); a < size; a++) { - int key = clearHistoryMessagesFinal.keyAt(a); + long key = clearHistoryMessagesFinal.keyAt(a); int id = clearHistoryMessagesFinal.valueAt(a); long did = -key; getNotificationCenter().postNotificationName(NotificationCenter.historyCleared, did, id); @@ -13703,39 +13681,44 @@ public class MessagesController extends BaseController implements NotificationCe if (webPages != null) { getMessagesStorage().putWebPages(webPages); } - if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markAsReadEncrypted != null || markAsReadMessages != null) { - if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markAsReadMessages != null) { - getMessagesStorage().updateDialogsWithReadMessages(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadMessages, true); + if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markAsReadEncrypted != null || markContentAsReadMessages != null) { + if (markAsReadMessagesInbox != null || markAsReadMessagesOutbox != null || markContentAsReadMessages != null) { + getMessagesStorage().updateDialogsWithReadMessages(markAsReadMessagesInbox, markAsReadMessagesOutbox, markContentAsReadMessages, true); } getMessagesStorage().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadEncrypted, true); } - if (markAsReadMessages != null) { - getMessagesStorage().markMessagesContentAsRead(markAsReadMessages, getConnectionsManager().getCurrentTime()); + if (markContentAsReadMessages != null) { + int time = getConnectionsManager().getCurrentTime(); + for (int a = 0, size = markContentAsReadMessages.size(); a < size; a++) { + long key = markContentAsReadMessages.keyAt(a); + ArrayList arrayList = markContentAsReadMessages.valueAt(a); + getMessagesStorage().markMessagesContentAsRead(key, arrayList, time); + } } if (deletedMessages != null) { for (int a = 0, size = deletedMessages.size(); a < size; a++) { - final int key = deletedMessages.keyAt(a); - final ArrayList arrayList = deletedMessages.valueAt(a); + long key = deletedMessages.keyAt(a); + ArrayList arrayList = deletedMessages.valueAt(a); getMessagesStorage().getStorageQueue().postRunnable(() -> { - ArrayList dialogIds = getMessagesStorage().markMessagesAsDeleted(arrayList, false, key, true, false); - getMessagesStorage().updateDialogsWithDeletedMessages(arrayList, dialogIds, false, key); + ArrayList dialogIds = getMessagesStorage().markMessagesAsDeleted(key, arrayList, false, true, false); + getMessagesStorage().updateDialogsWithDeletedMessages(key, -key, arrayList, dialogIds, false); }); } } if (scheduledDeletedMessages != null) { for (int a = 0, size = scheduledDeletedMessages.size(); a < size; a++) { - final int key = scheduledDeletedMessages.keyAt(a); - final ArrayList arrayList = scheduledDeletedMessages.valueAt(a); - getMessagesStorage().markMessagesAsDeleted(arrayList, true, key, false, true); + long key = scheduledDeletedMessages.keyAt(a); + ArrayList arrayList = scheduledDeletedMessages.valueAt(a); + getMessagesStorage().markMessagesAsDeleted(key, arrayList, true, false, true); } } if (clearHistoryMessages != null) { for (int a = 0, size = clearHistoryMessages.size(); a < size; a++) { - final int key = clearHistoryMessages.keyAt(a); - final int id = clearHistoryMessages.valueAt(a); + long key = clearHistoryMessages.keyAt(a); + int id = clearHistoryMessages.valueAt(a); getMessagesStorage().getStorageQueue().postRunnable(() -> { ArrayList dialogIds = getMessagesStorage().markMessagesAsDeleted(key, id, false, true); - getMessagesStorage().updateDialogsWithDeletedMessages(new ArrayList<>(), dialogIds, false, key); + getMessagesStorage().updateDialogsWithDeletedMessages(key, -key, new ArrayList<>(), dialogIds, false); }); } } @@ -13749,12 +13732,12 @@ public class MessagesController extends BaseController implements NotificationCe return true; } - public boolean isDialogMuted(long dialog_id) { - return isDialogMuted(dialog_id, null); + public boolean isDialogMuted(long dialogId) { + return isDialogMuted(dialogId, null); } - public boolean isDialogMuted(long dialog_id, TLRPC.Chat chat) { - int mute_type = notificationsPreferences.getInt("notify2_" + dialog_id, -1); + public boolean isDialogMuted(long dialogId, TLRPC.Chat chat) { + int mute_type = notificationsPreferences.getInt("notify2_" + dialogId, -1); if (mute_type == -1) { Boolean forceChannel; if (chat != null) { @@ -13762,12 +13745,12 @@ public class MessagesController extends BaseController implements NotificationCe } else { forceChannel = null; } - return !getNotificationsController().isGlobalNotificationsEnabled(dialog_id, forceChannel); + return !getNotificationsController().isGlobalNotificationsEnabled(dialogId, forceChannel); } if (mute_type == 2) { return true; } else if (mute_type == 3) { - int mute_until = notificationsPreferences.getInt("notifyuntil_" + dialog_id, 0); + int mute_until = notificationsPreferences.getInt("notifyuntil_" + dialogId, 0); if (mute_until >= getConnectionsManager().getCurrentTime()) { return true; } @@ -13780,7 +13763,7 @@ public class MessagesController extends BaseController implements NotificationCe if (info != null && (info.loading || Math.abs(SystemClock.elapsedRealtime() - info.loadTime) <= 5 * 60 * 1000)) { return info.messages; } - TLRPC.Chat chat = getChat((int) -dialogId); //TODO long + TLRPC.Chat chat = getChat(-dialogId); if (!ChatObject.isChannel(chat) || chat.megagroup || chat.gigagroup) { return null; } @@ -13802,8 +13785,8 @@ public class MessagesController extends BaseController implements NotificationCe putUsers(res.users, false); putChats(res.chats, false); }); - final SparseArray usersDict = new SparseArray<>(); - final SparseArray chatsDict = new SparseArray<>(); + final LongSparseArray usersDict = new LongSparseArray<>(); + final LongSparseArray chatsDict = new LongSparseArray<>(); for (int a = 0; a < res.users.size(); a++) { TLRPC.User u = res.users.get(a); @@ -13823,7 +13806,7 @@ public class MessagesController extends BaseController implements NotificationCe message.entities = sponsoredMessage.entities; message.flags |= 128; } - message.peer_id = getPeer((int) dialogId); //TODO long + message.peer_id = getPeer(dialogId); message.from_id = sponsoredMessage.from_id; message.flags |= 256; message.date = getConnectionsManager().getCurrentTime(); @@ -13851,8 +13834,8 @@ public class MessagesController extends BaseController implements NotificationCe } public CharSequence getPrintingString(long dialogId, int threadId, boolean isDialog) { - if (isDialog && (int) dialogId > 0) { - TLRPC.User user = getUser((int) dialogId); + if (isDialog && DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = getUser(dialogId); if (user != null && user.status != null && user.status.expires < 0) { return null; } @@ -13880,7 +13863,7 @@ public class MessagesController extends BaseController implements NotificationCe return true; } } else if (uid < 0) { - ArrayList messagesUsers = new ArrayList<>(); + ArrayList messagesUsers = new ArrayList<>(); for (MessageObject message : messages) { if (message.isFromUser() && !messagesUsers.contains(message.messageOwner.from_id.user_id)) { messagesUsers.add(message.messageOwner.from_id.user_id); @@ -13925,14 +13908,14 @@ public class MessagesController extends BaseController implements NotificationCe return false; } - protected boolean updateInterfaceWithMessages(final long uid, final ArrayList messages, boolean scheduled) { + protected boolean updateInterfaceWithMessages(long dialogId, ArrayList messages, boolean scheduled) { if (messages == null || messages.isEmpty()) { return false; } - boolean isEncryptedChat = ((int) uid) == 0; + boolean isEncryptedChat = DialogObject.isEncryptedDialog(dialogId); MessageObject lastMessage = null; - int channelId = 0; + long channelId = 0; boolean updateRating = false; boolean hasNotOutMessage = false; if (!scheduled) { @@ -13973,13 +13956,13 @@ public class MessagesController extends BaseController implements NotificationCe } } } - getMediaDataController().loadReplyMessagesForMessages(messages, uid, scheduled, null); - getNotificationCenter().postNotificationName(NotificationCenter.didReceiveNewMessages, uid, messages, scheduled); + getMediaDataController().loadReplyMessagesForMessages(messages, dialogId, scheduled, null); + getNotificationCenter().postNotificationName(NotificationCenter.didReceiveNewMessages, dialogId, messages, scheduled); if (lastMessage == null || scheduled) { return false; } - TLRPC.TL_dialog dialog = (TLRPC.TL_dialog) dialogs_dict.get(uid); + TLRPC.TL_dialog dialog = (TLRPC.TL_dialog) dialogs_dict.get(dialogId); if (lastMessage.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) { if (dialog != null) { allDialogs.remove(dialog); @@ -14018,9 +14001,8 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationsController().removeNotificationsForDialog(dialog.id); getNotificationCenter().postNotificationName(NotificationCenter.needReloadRecentDialogsSearch); } - int lowerId = (int) uid; - if (lowerId < 0) { - ChatObject.Call call = getGroupCall(-lowerId, false); + if (DialogObject.isChatDialog(dialogId)) { + ChatObject.Call call = getGroupCall(-dialogId, false); if (call != null) { TLRPC.Chat chat = getChat(lastMessage.messageOwner.action.channel_id); if (chat != null) { @@ -14039,16 +14021,16 @@ public class MessagesController extends BaseController implements NotificationCe return false; } if (BuildVars.LOGS_ENABLED) { - FileLog.d("not found dialog with id " + uid + " dictCount = " + dialogs_dict.size() + " allCount = " + allDialogs.size()); + FileLog.d("not found dialog with id " + dialogId + " dictCount = " + dialogs_dict.size() + " allCount = " + allDialogs.size()); } dialog = new TLRPC.TL_dialog(); - dialog.id = uid; + dialog.id = dialogId; int mid = dialog.top_message = lastMessage.getId(); dialog.last_message_date = lastMessage.messageOwner.date; dialog.flags = ChatObject.isChannel(chat) ? 1 : 0; - dialogs_dict.put(uid, dialog); + dialogs_dict.put(dialogId, dialog); allDialogs.add(dialog); - dialogMessage.put(uid, lastMessage); + dialogMessage.put(dialogId, lastMessage); if (lastMessage.messageOwner.peer_id.channel_id == 0) { dialogMessagesByIds.put(lastMessage.getId(), lastMessage); if (lastMessage.messageOwner.random_id != 0) { @@ -14058,7 +14040,7 @@ public class MessagesController extends BaseController implements NotificationCe changed = true; TLRPC.Dialog dialogFinal = dialog; - getMessagesStorage().getDialogFolderId(uid, param -> { + getMessagesStorage().getDialogFolderId(dialogId, param -> { if (param != -1) { if (param != 0) { dialogFinal.folder_id = param; @@ -14066,16 +14048,15 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload, true); } } else if (mid > 0) { - int lowerId = (int) uid; - if (lowerId != 0) { - loadUnknownDialog(getInputPeer(lowerId), 0); + if (!DialogObject.isEncryptedDialog(dialogId)) { + loadUnknownDialog(getInputPeer(dialogId), 0); } } }); } else { if ((dialog.top_message > 0 && lastMessage.getId() > 0 && lastMessage.getId() > dialog.top_message) || (dialog.top_message < 0 && lastMessage.getId() < 0 && lastMessage.getId() < dialog.top_message) || - dialogMessage.indexOfKey(uid) < 0 || dialog.top_message < 0 || dialog.last_message_date <= lastMessage.messageOwner.date) { + dialogMessage.indexOfKey(dialogId) < 0 || dialog.top_message < 0 || dialog.last_message_date <= lastMessage.messageOwner.date) { MessageObject object = dialogMessagesByIds.get(dialog.top_message); if (object != null && object.messageOwner.peer_id.channel_id == 0) { dialogMessagesByIds.remove(dialog.top_message); @@ -14086,7 +14067,7 @@ public class MessagesController extends BaseController implements NotificationCe dialog.top_message = lastMessage.getId(); dialog.last_message_date = lastMessage.messageOwner.date; changed = true; - dialogMessage.put(uid, lastMessage); + dialogMessage.put(dialogId, lastMessage); if (lastMessage.messageOwner.peer_id.channel_id == 0) { dialogMessagesByIds.put(lastMessage.getId(), lastMessage); if (lastMessage.messageOwner.random_id != 0) { @@ -14101,7 +14082,7 @@ public class MessagesController extends BaseController implements NotificationCe } if (updateRating) { - getMediaDataController().increasePeerRaiting(uid); + getMediaDataController().increasePeerRaiting(dialogId); } return changed; } @@ -14144,7 +14125,7 @@ public class MessagesController extends BaseController implements NotificationCe return clearingHistoryDialogs.get(did) != null; } - public void sortDialogs(SparseArray chatsDict) { + public void sortDialogs(LongSparseArray chatsDict) { dialogsServerOnly.clear(); dialogsCanAddUsers.clear(); dialogsChannelsOnly.clear(); @@ -14165,7 +14146,7 @@ public class MessagesController extends BaseController implements NotificationCe } unreadUnmutedDialogs = 0; boolean selfAdded = false; - int selfId = getUserConfig().getClientUserId(); + long selfId = getUserConfig().getClientUserId(); if (selectedDialogFilter[0] != null || selectedDialogFilter[1] != null) { for (int b = 0; b < selectedDialogFilter.length; b++) { sortingDialogFilter = selectedDialogFilter[b]; @@ -14178,15 +14159,14 @@ public class MessagesController extends BaseController implements NotificationCe for (int a = 0, N = allDialogs.size(); a < N; a++) { TLRPC.Dialog d = allDialogs.get(a); if (d instanceof TLRPC.TL_dialog) { - int high_id = (int) (d.id >> 32); - int lower_id = (int) d.id; - if (lower_id == 0 && high_id != 0) { - TLRPC.EncryptedChat encryptedChat = getEncryptedChat(high_id); + long dialogId = d.id; + if (DialogObject.isEncryptedDialog(dialogId)) { + TLRPC.EncryptedChat encryptedChat = getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (encryptedChat != null) { - lower_id = encryptedChat.user_id; + dialogId = encryptedChat.user_id; } } - if (sortingDialogFilter.includesDialog(getAccountInstance(), lower_id, d)) { + if (sortingDialogFilter.includesDialog(getAccountInstance(), dialogId, d)) { dialogsByFilter.add(d); } } @@ -14197,25 +14177,23 @@ public class MessagesController extends BaseController implements NotificationCe Collections.sort(allDialogs, dialogComparator); isLeftPromoChannel = true; if (promoDialog != null && promoDialog.id < 0) { - TLRPC.Chat chat = getChat(-(int) promoDialog.id); + TLRPC.Chat chat = getChat(-promoDialog.id); if (chat != null && !chat.left) { isLeftPromoChannel = false; } } for (int a = 0, N = allDialogs.size(); a < N; a++) { TLRPC.Dialog d = allDialogs.get(a); - int high_id = (int) (d.id >> 32); - int lower_id = (int) d.id; if (d instanceof TLRPC.TL_dialog) { MessageObject messageObject = dialogMessage.get(d.id); if (messageObject != null && messageObject.messageOwner.date < dialogsLoadedTillDate) { continue; } boolean canAddToForward = true; - if (lower_id != 0 && high_id != 1) { + if (!DialogObject.isEncryptedDialog(d.id)) { dialogsServerOnly.add(d); if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = getChat(-lower_id); + TLRPC.Chat chat = getChat(-d.id); if (chat != null && chat.megagroup && (chat.admin_rights != null && (chat.admin_rights.post_messages || chat.admin_rights.add_admins) || chat.creator)) { dialogsCanAddUsers.add(d); } @@ -14226,9 +14204,9 @@ public class MessagesController extends BaseController implements NotificationCe dialogsChannelsOnly.add(d); canAddToForward = ChatObject.hasAdminRights(chat) && ChatObject.canPost(chat); } - } else if (lower_id < 0) { + } else if (d.id < 0) { if (chatsDict != null) { - TLRPC.Chat chat = chatsDict.get(-lower_id); + TLRPC.Chat chat = chatsDict.get(-d.id); if (chat != null && chat.migrated_to != null) { allDialogs.remove(a); a--; @@ -14238,15 +14216,15 @@ public class MessagesController extends BaseController implements NotificationCe } dialogsCanAddUsers.add(d); dialogsGroupsOnly.add(d); - } else if (lower_id != selfId) { + } else if (d.id != selfId) { dialogsUsersOnly.add(d); - if (!UserObject.isReplyUser(lower_id)) { + if (!UserObject.isReplyUser(d.id)) { dialogsForBlock.add(d); } } } if (canAddToForward && d.folder_id == 0) { - if (lower_id == selfId) { + if (d.id == selfId) { dialogsForward.add(0, d); selfAdded = true; } else { @@ -14342,19 +14320,19 @@ public class MessagesController extends BaseController implements NotificationCe return checkCanOpenChat(bundle, fragment, null); } - public boolean checkCanOpenChat(final Bundle bundle, final BaseFragment fragment, MessageObject originalMessage) { + public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObject originalMessage) { if (bundle == null || fragment == null) { return true; } TLRPC.User user = null; TLRPC.Chat chat = null; - int user_id = bundle.getInt("user_id", 0); - int chat_id = bundle.getInt("chat_id", 0); + long userId = bundle.getLong("user_id", 0); + long chatId = bundle.getLong("chat_id", 0); int messageId = bundle.getInt("message_id", 0); - if (user_id != 0) { - user = getUser(user_id); - } else if (chat_id != 0) { - chat = getChat(chat_id); + if (userId != 0) { + user = getUser(userId); + } else if (chatId != 0) { + chat = getChat(chatId); } if (user == null && chat == null) { return true; @@ -14370,9 +14348,9 @@ public class MessagesController extends BaseController implements NotificationCe return false; } if (messageId != 0 && originalMessage != null && chat != null && chat.access_hash == 0) { - int did = (int) originalMessage.getDialogId(); - if (did != 0) { - final AlertDialog progressDialog = new AlertDialog(fragment.getParentActivity(), 3); + long did = originalMessage.getDialogId(); + if (!DialogObject.isEncryptedDialog(did)) { + AlertDialog progressDialog = new AlertDialog(fragment.getParentActivity(), 3); TLObject req; if (did < 0) { chat = getChat(-did); @@ -14388,7 +14366,7 @@ public class MessagesController extends BaseController implements NotificationCe request.id.add(originalMessage.getId()); req = request; } - final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { AndroidUtilities.runOnUIThread(() -> { try { @@ -14435,9 +14413,9 @@ public class MessagesController extends BaseController implements NotificationCe } else { Bundle args = new Bundle(); if (chat != null) { - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); } else { - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); } if (type == 0) { fragment.presentFragment(new ProfileActivity(args)); @@ -14449,7 +14427,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - public void openByUserName(String username, final BaseFragment fragment, final int type) { + public void openByUserName(String username, BaseFragment fragment, int type) { if (username == null || fragment == null) { return; } @@ -14475,11 +14453,11 @@ public class MessagesController extends BaseController implements NotificationCe if (fragment.getParentActivity() == null) { return; } - final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(fragment.getParentActivity(), 3)}; + AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(fragment.getParentActivity(), 3)}; TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername(); req.username = username; - final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { try { progressDialog[0].dismiss(); } catch (Exception ignored) { @@ -14523,25 +14501,23 @@ public class MessagesController extends BaseController implements NotificationCe messageId = sharedPreferences.getInt("diditem" + dialogId, 0); } int finalMessageId = messageId; - final int classGuid = ConnectionsManager.generateClassGuid(); + int classGuid = ConnectionsManager.generateClassGuid(); - int lower_part = (int) dialogId; - int chatId = 0; - - - if (lower_part < 0) { - chatId = -lower_part; + long chatId; + if (DialogObject.isChatDialog(dialogId)) { + chatId = -dialogId; + } else { + chatId = 0; } - TLRPC.Chat currentChat = null; + TLRPC.Chat currentChat; if (chatId != 0) { currentChat = getMessagesController().getChat(chatId); if (currentChat == null) { - final MessagesStorage messagesStorage = getMessagesStorage(); - int finalChatId = chatId; + MessagesStorage messagesStorage = getMessagesStorage(); messagesStorage.getStorageQueue().postRunnable(() -> { - TLRPC.Chat chat = messagesStorage.getChat(finalChatId); + TLRPC.Chat chat = messagesStorage.getChat(chatId); AndroidUtilities.runOnUIThread(() -> { if (chat != null) { getMessagesController().putChat(chat, true); @@ -14557,9 +14533,7 @@ public class MessagesController extends BaseController implements NotificationCe } } - final boolean isChannel = ChatObject.isChannel(currentChat); - - final int count = AndroidUtilities.isTablet() ? 30 : 20; + int count = AndroidUtilities.isTablet() ? 30 : 20; NotificationCenter.NotificationCenterDelegate delegate = new NotificationCenter.NotificationCenterDelegate() { @Override @@ -14571,9 +14545,9 @@ public class MessagesController extends BaseController implements NotificationCe int lastMessageId = (int) args[4]; if ((size < count / 2 && !isEnd) && isCache) { if (finalMessageId != 0) { - loadMessagesInternal(dialogId, 0, false, count, finalMessageId, 0, false, 0, classGuid, 3, lastMessageId, isChannel, 0, 0, 0, 0, 0, 0, false, 0, true, false); + loadMessagesInternal(dialogId, 0, false, count, finalMessageId, 0, false, 0, classGuid, 3, lastMessageId, 0, 0, 0, 0, 0, 0, false, 0, true, false); } else { - loadMessagesInternal(dialogId, 0, false, count, finalMessageId, 0, false, 0, classGuid, 2, lastMessageId, isChannel, 0, 0, 0, 0, 0, 0, false, 0, true, false); + loadMessagesInternal(dialogId, 0, false, count, finalMessageId, 0, false, 0, classGuid, 2, lastMessageId, 0, 0, 0, 0, 0, 0, false, 0, true, false); } } else { getNotificationCenter().removeObserver(this, NotificationCenter.messagesDidLoadWithoutProcess); @@ -14597,9 +14571,9 @@ public class MessagesController extends BaseController implements NotificationCe getNotificationCenter().addObserver(delegate, NotificationCenter.loadingMessagesFailed); if (messageId != 0) { - loadMessagesInternal(dialogId, 0, true, count, finalMessageId, 0, true, 0, classGuid, 3, 0, isChannel, 0, 0, 0, 0, 0, 0, false, 0, true, false); + loadMessagesInternal(dialogId, 0, true, count, finalMessageId, 0, true, 0, classGuid, 3, 0, 0, 0, 0, 0, 0, 0, false, 0, true, false); } else { - loadMessagesInternal(dialogId, 0, true, count, finalMessageId, 0, true, 0, classGuid, 2, 0, isChannel, 0, 0, 0, 0, 0, 0, false, 0, true, false); + loadMessagesInternal(dialogId, 0, true, count, finalMessageId, 0, true, 0, classGuid, 2, 0, 0, 0, 0, 0, 0, 0, false, 0, true, false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesStorage.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesStorage.java index 6805b6654..88bc00fa3 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesStorage.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesStorage.java @@ -15,7 +15,6 @@ import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; -import android.util.LongSparseArray; import android.util.Pair; import android.util.SparseArray; import android.util.SparseIntArray; @@ -23,8 +22,9 @@ import android.util.SparseIntArray; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteDatabase; +import org.telegram.SQLite.SQLiteException; import org.telegram.SQLite.SQLitePreparedStatement; -import org.telegram.messenger.support.SparseLongArray; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; @@ -46,6 +46,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicLong; import androidx.annotation.UiThread; +import androidx.collection.LongSparseArray; public class MessagesStorage extends BaseController { @@ -53,6 +54,10 @@ public class MessagesStorage extends BaseController { void run(int param); } + public interface LongCallback { + void run(long param); + } + public interface StringCallback { void run(String param); } @@ -93,7 +98,7 @@ public class MessagesStorage extends BaseController { private CountDownLatch openSync = new CountDownLatch(1); private static volatile MessagesStorage[] Instance = new MessagesStorage[UserConfig.MAX_ACCOUNT_COUNT]; - private final static int LAST_DB_VERSION = 80; + private final static int LAST_DB_VERSION = 84; public static MessagesStorage getInstance(int num) { MessagesStorage localInstance = Instance[num]; @@ -288,17 +293,18 @@ public class MessagesStorage extends BaseController { database.executeFast("CREATE TABLE media_holes_v2(uid INTEGER, type INTEGER, start INTEGER, end INTEGER, PRIMARY KEY(uid, type, start));").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS uid_end_media_holes_v2 ON media_holes_v2(uid, type, end);").stepThis().dispose(); - database.executeFast("CREATE TABLE scheduled_messages(mid INTEGER PRIMARY KEY, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB)").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages ON scheduled_messages(mid, send_state, date);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages ON scheduled_messages(uid, date);").stepThis().dispose(); + database.executeFast("CREATE TABLE scheduled_messages_v2(mid INTEGER, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, send_state, date);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages_v2 ON scheduled_messages_v2(uid, date);").stepThis().dispose(); - database.executeFast("CREATE TABLE messages(mid INTEGER PRIMARY KEY, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER)").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages ON messages(uid, mid, read_state, out);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages ON messages(uid, date, mid);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages ON messages(mid, out);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages ON messages(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages2 ON messages(mid, send_state, date);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages ON messages(uid, mention, read_state);").stepThis().dispose(); + database.executeFast("CREATE TABLE messages_v2(mid INTEGER, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER, is_channel INTEGER, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_v2 ON messages_v2(uid, mid, read_state, out);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages_v2 ON messages_v2(uid, date, mid);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages_v2 ON messages_v2(mid, out);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages_v2 ON messages_v2(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages_v2 ON messages_v2(mid, send_state, date);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_v2 ON messages_v2(uid, mention, read_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS is_channel_idx_messages_v2 ON messages_v2(mid, is_channel);").stepThis().dispose(); database.executeFast("CREATE TABLE download_queue(uid INTEGER, type INTEGER, date INTEGER, data BLOB, parent TEXT, PRIMARY KEY (uid, type));").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS type_date_idx_download_queue ON download_queue(type, date);").stepThis().dispose(); @@ -320,11 +326,11 @@ public class MessagesStorage extends BaseController { database.executeFast("CREATE TABLE dialog_filter_ep(id INTEGER, peer INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose(); database.executeFast("CREATE TABLE dialog_filter_pin_v2(id INTEGER, peer INTEGER, pin INTEGER, PRIMARY KEY (id, peer))").stepThis().dispose(); - database.executeFast("CREATE TABLE randoms(random_id INTEGER, mid INTEGER, PRIMARY KEY (random_id, mid))").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); + database.executeFast("CREATE TABLE randoms_v2(random_id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (random_id, mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms_v2 ON randoms_v2(mid, uid);").stepThis().dispose(); - database.executeFast("CREATE TABLE enc_tasks_v3(mid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, media))").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v3 ON enc_tasks_v3(date);").stepThis().dispose(); + database.executeFast("CREATE TABLE enc_tasks_v4(mid INTEGER, uid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, uid, media))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v4 ON enc_tasks_v4(date);").stepThis().dispose(); database.executeFast("CREATE TABLE messages_seq(mid INTEGER PRIMARY KEY, seq_in INTEGER, seq_out INTEGER);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS seq_idx_messages_seq ON messages_seq(seq_in, seq_out);").stepThis().dispose(); @@ -332,11 +338,11 @@ public class MessagesStorage extends BaseController { database.executeFast("CREATE TABLE params(id INTEGER PRIMARY KEY, seq INTEGER, pts INTEGER, date INTEGER, qts INTEGER, lsv INTEGER, sg INTEGER, pbytes BLOB)").stepThis().dispose(); database.executeFast("INSERT INTO params VALUES(1, 0, 0, 0, 0, 0, 0, NULL)").stepThis().dispose(); - database.executeFast("CREATE TABLE media_v2(mid INTEGER PRIMARY KEY, uid INTEGER, date INTEGER, type INTEGER, data BLOB)").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media ON media_v2(uid, mid, type, date);").stepThis().dispose(); + database.executeFast("CREATE TABLE media_v3(mid INTEGER, uid INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_v3 ON media_v3(uid, mid, type, date);").stepThis().dispose(); database.executeFast("CREATE TABLE bot_keyboard(uid INTEGER PRIMARY KEY, mid INTEGER, info BLOB)").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid ON bot_keyboard(mid);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid_v2 ON bot_keyboard(mid, uid);").stepThis().dispose(); database.executeFast("CREATE TABLE chat_settings_v2(uid INTEGER PRIMARY KEY, info BLOB, pinned INTEGER, online INTEGER, inviter INTEGER, links INTEGER)").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS chat_settings_pinned_idx ON chat_settings_v2(uid, pinned) WHERE pinned != 0;").stepThis().dispose(); @@ -367,7 +373,7 @@ public class MessagesStorage extends BaseController { database.executeFast("CREATE TABLE stickers_featured(id INTEGER PRIMARY KEY, data BLOB, unread BLOB, date INTEGER, hash INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE stickers_dice(emoji TEXT PRIMARY KEY, data BLOB, date INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose(); - database.executeFast("CREATE TABLE webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose(); + database.executeFast("CREATE TABLE webpage_pending_v2(id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (id, mid, uid));").stepThis().dispose(); database.executeFast("CREATE TABLE sent_files_v2(uid TEXT, type INTEGER, data BLOB, parent TEXT, PRIMARY KEY (uid, type))").stepThis().dispose(); database.executeFast("CREATE TABLE search_recent(did INTEGER PRIMARY KEY, date INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE media_counts_v2(uid INTEGER, type INTEGER, count INTEGER, old INTEGER, PRIMARY KEY(uid, type))").stepThis().dispose(); @@ -391,8 +397,8 @@ public class MessagesStorage extends BaseController { database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_date ON unread_push_messages(date);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS unread_push_messages_idx_random ON unread_push_messages(random);").stepThis().dispose(); - database.executeFast("CREATE TABLE polls(mid INTEGER PRIMARY KEY, id INTEGER);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS polls_id ON polls(id);").stepThis().dispose(); + database.executeFast("CREATE TABLE polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS polls_id_v2 ON polls_v2(id);").stepThis().dispose(); //version database.executeFast("PRAGMA user_version = " + LAST_DB_VERSION).stepThis().dispose(); @@ -439,7 +445,7 @@ public class MessagesStorage extends BaseController { } catch (Exception e) { FileLog.e(e); - if (openTries < 3 && e.getMessage().contains("malformed")) { + if (openTries < 3 && e.getMessage() != null && e.getMessage().contains("malformed")) { if (openTries == 2) { cleanupInternal(true); for (int a = 0; a < 2; a++) { @@ -463,7 +469,10 @@ public class MessagesStorage extends BaseController { } } - private void updateDbToLastVersion(final int currentVersion) { + private void updateDbToLastVersion(int currentVersion) { + AndroidUtilities.runOnUIThread(() -> { + NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.onDatabaseMigration, true); + }); storageQueue.postRunnable(() -> { try { int version = currentVersion; @@ -539,11 +548,6 @@ public class MessagesStorage extends BaseController { database.executeFast("PRAGMA user_version = 7").stepThis().dispose(); version = 7; } - /*if (version == 7 && version < 8) { - database.executeFast("CREATE TABLE IF NOT EXISTS secret_holes(uid INTEGER, seq_in INTEGER, seq_out INTEGER, data BLOB, PRIMARY KEY (uid, seq_in, seq_out));").stepThis().dispose(); - database.executeFast("PRAGMA user_version = 8").stepThis().dispose(); - version = 8; - }*/ if (version == 7 || version == 8 || version == 9) { database.executeFast("ALTER TABLE enc_chats ADD COLUMN use_count INTEGER default 0").stepThis().dispose(); database.executeFast("ALTER TABLE enc_chats ADD COLUMN exchange_id INTEGER default 0").stepThis().dispose(); @@ -623,14 +627,14 @@ public class MessagesStorage extends BaseController { SQLiteCursor cursor = database.queryFinalized("SELECT uid, participants FROM chat_settings WHERE uid < 0"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?)"); while (cursor.next()) { - int chat_id = cursor.intValue(0); + long chatId = cursor.intValue(0); NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { TLRPC.ChatParticipants participants = TLRPC.ChatParticipants.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (participants != null) { TLRPC.TL_chatFull chatFull = new TLRPC.TL_chatFull(); - chatFull.id = chat_id; + chatFull.id = chatId; chatFull.chat_photo = new TLRPC.TL_photoEmpty(); chatFull.notify_settings = new TLRPC.TL_peerNotifySettingsEmpty_layer77(); chatFull.exported_invite = null; @@ -638,7 +642,7 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data2 = new NativeByteBuffer(chatFull.getObjectSize()); chatFull.serializeToStream(data2); state.requery(); - state.bindInteger(1, chat_id); + state.bindLong(1, chatId); state.bindByteBuffer(2, data2); state.step(); data2.reuse(); @@ -814,8 +818,8 @@ public class MessagesStorage extends BaseController { version = 52; } if (version == 52) { - database.executeFast("CREATE TABLE IF NOT EXISTS polls(mid INTEGER PRIMARY KEY, id INTEGER);").stepThis().dispose(); - database.executeFast("CREATE INDEX IF NOT EXISTS polls_id ON polls(id);").stepThis().dispose(); + database.executeFast("CREATE TABLE IF NOT EXISTS polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS polls_id ON polls_v2(id);").stepThis().dispose(); database.executeFast("PRAGMA user_version = 53").stepThis().dispose(); version = 53; } @@ -987,11 +991,468 @@ public class MessagesStorage extends BaseController { version = 80; } if (version == 80) { + database.executeFast("CREATE TABLE IF NOT EXISTS scheduled_messages_v2(mid INTEGER, uid INTEGER, send_state INTEGER, date INTEGER, data BLOB, ttl INTEGER, replydata BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_scheduled_messages_v2 ON scheduled_messages_v2(mid, send_state, date);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_idx_scheduled_messages_v2 ON scheduled_messages_v2(uid, date);").stepThis().dispose(); + + database.executeFast("CREATE INDEX IF NOT EXISTS bot_keyboard_idx_mid_v2 ON bot_keyboard(mid, uid);").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS bot_keyboard_idx_mid;").stepThis().dispose(); + + database.beginTransaction(); + SQLiteCursor cursor; + try { + cursor = database.queryFinalized("SELECT mid, uid, send_state, date, data, ttl, replydata FROM scheduled_messages_v2 WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?)"); + while (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(4); + if (data == null) { + continue; + } + int mid = cursor.intValue(0); + long uid = cursor.longValue(1); + int sendState = cursor.intValue(2); + int date = cursor.intValue(3); + int ttl = cursor.intValue(5); + NativeByteBuffer replydata = cursor.byteBufferValue(6); + + statement.requery(); + statement.bindInteger(1, mid); + statement.bindLong(2, uid); + statement.bindInteger(3, sendState); + statement.bindByteBuffer(4, data); + statement.bindInteger(5, date); + statement.bindInteger(6, ttl); + if (replydata != null) { + statement.bindByteBuffer(7, replydata); + } else { + statement.bindNull(7); + } + statement.step(); + if (replydata != null) { + replydata.reuse(); + } + data.reuse(); + } + cursor.dispose(); + statement.dispose(); + } + + database.executeFast("DROP INDEX IF EXISTS send_state_idx_scheduled_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS uid_date_idx_scheduled_messages;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS scheduled_messages;").stepThis().dispose(); + + database.commitTransaction(); + database.executeFast("PRAGMA user_version = 81").stepThis().dispose(); + version = 81; + } + if (version == 81) { + database.executeFast("CREATE TABLE IF NOT EXISTS media_v3(mid INTEGER, uid INTEGER, date INTEGER, type INTEGER, data BLOB, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_type_date_idx_media_v3 ON media_v3(uid, mid, type, date);").stepThis().dispose(); + + database.beginTransaction(); + SQLiteCursor cursor; + try { + cursor = database.queryFinalized("SELECT mid, uid, date, type, data FROM media_v2 WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); + while (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(4); + if (data == null) { + continue; + } + int mid = cursor.intValue(0); + long uid = cursor.longValue(1); + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + int date = cursor.intValue(2); + int type = cursor.intValue(3); + + statement.requery(); + statement.bindInteger(1, mid); + statement.bindLong(2, uid); + statement.bindInteger(3, date); + statement.bindInteger(4, type); + statement.bindByteBuffer(5, data); + statement.step(); + data.reuse(); + } + cursor.dispose(); + statement.dispose(); + } + + database.executeFast("DROP INDEX IF EXISTS uid_mid_type_date_idx_media;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS media_v2;").stepThis().dispose(); + database.commitTransaction(); + + database.executeFast("PRAGMA user_version = 82").stepThis().dispose(); + version = 82; + } + if (version == 82) { + database.executeFast("CREATE TABLE IF NOT EXISTS randoms_v2(random_id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (random_id, mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms_v2 ON randoms_v2(mid, uid);").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS enc_tasks_v4(mid INTEGER, uid INTEGER, date INTEGER, media INTEGER, PRIMARY KEY(mid, uid, media))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS date_idx_enc_tasks_v4 ON enc_tasks_v4(date);").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS polls_v2(mid INTEGER, uid INTEGER, id INTEGER, PRIMARY KEY (mid, uid));").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS polls_id_v2 ON polls_v2(id);").stepThis().dispose(); + + database.executeFast("CREATE TABLE IF NOT EXISTS webpage_pending_v2(id INTEGER, mid INTEGER, uid INTEGER, PRIMARY KEY (id, mid, uid));").stepThis().dispose(); + + database.beginTransaction(); + + SQLiteCursor cursor; + try { + cursor = database.queryFinalized("SELECT r.random_id, r.mid, m.uid FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)"); + while (cursor.next()) { + long randomId = cursor.longValue(0); + int mid = cursor.intValue(1); + long uid = cursor.longValue(2); + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + + statement.requery(); + statement.bindLong(1, randomId); + statement.bindInteger(2, mid); + statement.bindLong(3, uid); + statement.step(); + } + cursor.dispose(); + statement.dispose(); + } + + try { + cursor = database.queryFinalized("SELECT p.mid, m.uid, p.id FROM polls as p INNER JOIN messages as m ON p.mid = m.mid WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)"); + while (cursor.next()) { + int mid = cursor.intValue(0); + long uid = cursor.longValue(1); + long id = cursor.longValue(2); + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + + statement.requery(); + statement.bindInteger(1, mid); + statement.bindLong(2, uid); + statement.bindLong(3, id); + statement.step(); + } + cursor.dispose(); + statement.dispose(); + } + + try { + cursor = database.queryFinalized("SELECT wp.id, wp.mid, m.uid FROM webpage_pending as wp INNER JOIN messages as m ON wp.mid = m.mid WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)"); + while (cursor.next()) { + long id = cursor.longValue(0); + int mid = cursor.intValue(1); + long uid = cursor.longValue(2); + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + + statement.requery(); + statement.bindLong(1, id); + statement.bindInteger(2, mid); + statement.bindLong(3, uid); + statement.step(); + } + cursor.dispose(); + statement.dispose(); + } + + try { + cursor = database.queryFinalized("SELECT et.mid, m.uid, et.date, et.media FROM enc_tasks_v3 as et INNER JOIN messages as m ON et.mid = m.mid WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); + while (cursor.next()) { + int mid = cursor.intValue(0); + long uid = cursor.longValue(1); + int date = cursor.intValue(2); + int media = cursor.intValue(3); + + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + + statement.requery(); + statement.bindInteger(1, mid); + statement.bindLong(2, uid); + statement.bindInteger(3, date); + statement.bindInteger(4, media); + statement.step(); + } + cursor.dispose(); + statement.dispose(); + } + + database.executeFast("DROP INDEX IF EXISTS mid_idx_randoms;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS randoms;").stepThis().dispose(); + + database.executeFast("DROP INDEX IF EXISTS date_idx_enc_tasks_v3;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS enc_tasks_v3;").stepThis().dispose(); + + database.executeFast("DROP INDEX IF EXISTS polls_id;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS polls;").stepThis().dispose(); + + database.executeFast("DROP TABLE IF EXISTS webpage_pending;").stepThis().dispose(); + database.commitTransaction(); + + database.executeFast("PRAGMA user_version = 83").stepThis().dispose(); + version = 83; + } + if (version == 83) { + database.executeFast("CREATE TABLE IF NOT EXISTS messages_v2(mid INTEGER, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB, imp INTEGER, mention INTEGER, forwards INTEGER, replies_data BLOB, thread_reply_id INTEGER, is_channel INTEGER, PRIMARY KEY(mid, uid))").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mid_read_out_idx_messages_v2 ON messages_v2(uid, mid, read_state, out);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_date_mid_idx_messages_v2 ON messages_v2(uid, date, mid);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS mid_out_idx_messages_v2 ON messages_v2(mid, out);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS task_idx_messages_v2 ON messages_v2(uid, out, read_state, ttl, date, send_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS send_state_idx_messages_v2 ON messages_v2(mid, send_state, date);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS uid_mention_idx_messages_v2 ON messages_v2(uid, mention, read_state);").stepThis().dispose(); + database.executeFast("CREATE INDEX IF NOT EXISTS is_channel_idx_messages_v2 ON messages_v2(mid, is_channel);").stepThis().dispose(); + + database.beginTransaction(); + + SQLiteCursor cursor; + try { + cursor = database.queryFinalized("SELECT mid, uid, read_state, send_state, date, data, out, ttl, media, replydata, imp, mention, forwards, replies_data, thread_reply_id FROM messages WHERE 1"); + } catch (Exception e) { + cursor = null; + FileLog.e(e); + } + if (cursor != null) { + SQLitePreparedStatement statement = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + int num = 0; + while (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(5); + if (data == null) { + continue; + } + num++; + long mid = cursor.intValue(0); + long uid = cursor.longValue(1); + int lowerId = (int) uid; + if (lowerId == 0) { + int highId = (int) (uid >> 32); + uid = DialogObject.makeEncryptedDialogId(highId); + } + int readState = cursor.intValue(2); + int sendState = cursor.intValue(3); + int date = cursor.intValue(4); + int out = cursor.intValue(6); + int ttl = cursor.intValue(7); + int media = cursor.intValue(8); + NativeByteBuffer replydata = cursor.byteBufferValue(9); + int imp = cursor.intValue(10); + int mention = cursor.intValue(11); + int forwards = cursor.intValue(12); + NativeByteBuffer repliesdata = cursor.byteBufferValue(13); + int thread_reply_id = cursor.intValue(14); + int channelId = (int) (uid >> 32); + if (ttl < 0) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + if (message != null) { + message.readAttachPath(data, getUserConfig().clientUserId); + if (message.params == null) { + message.params = new HashMap<>(); + message.params.put("fwd_peer", "" + ttl); + } + data.reuse(); + data = new NativeByteBuffer(message.getObjectSize()); + message.serializeToStream(data); + } + ttl = 0; + } + + statement.requery(); + statement.bindInteger(1, (int) mid); + statement.bindLong(2, uid); + statement.bindInteger(3, readState); + statement.bindInteger(4, sendState); + statement.bindInteger(5, date); + statement.bindByteBuffer(6, data); + statement.bindInteger(7, out); + statement.bindInteger(8, ttl); + statement.bindInteger(9, media); + if (replydata != null) { + statement.bindByteBuffer(10, replydata); + } else { + statement.bindNull(10); + } + statement.bindInteger(11, imp); + statement.bindInteger(12, mention); + statement.bindInteger(13, forwards); + if (repliesdata != null) { + statement.bindByteBuffer(14, repliesdata); + } else { + statement.bindNull(14); + } + statement.bindInteger(15, thread_reply_id); + statement.bindInteger(16, channelId > 0 ? 1 : 0); + statement.step(); + if (replydata != null) { + replydata.reuse(); + } + if (repliesdata != null) { + repliesdata.reuse(); + } + data.reuse(); + } + cursor.dispose(); + statement.dispose(); + } + + ArrayList secretChatsToUpdate = null; + ArrayList foldersToUpdate = null; + cursor = database.queryFinalized("SELECT did, last_mid, last_mid_i FROM dialogs WHERE 1"); + SQLitePreparedStatement statement4 = database.executeFast("UPDATE dialogs SET last_mid = ?, last_mid_i = ? WHERE did = ?"); + while (cursor.next()) { + long did = cursor.longValue(0); + int lowerId = (int) did; + int highId = (int) (did >> 32); + if (lowerId == 0) { + if (secretChatsToUpdate == null) { + secretChatsToUpdate = new ArrayList<>(); + } + secretChatsToUpdate.add(highId); + } else if (highId == 2) { + if (foldersToUpdate == null) { + foldersToUpdate = new ArrayList<>(); + } + foldersToUpdate.add(lowerId); + } + + statement4.requery(); + statement4.bindInteger(1, cursor.intValue(1)); + statement4.bindInteger(2, cursor.intValue(2)); + statement4.bindLong(3, did); + statement4.step(); + } + statement4.dispose(); + cursor.dispose(); + + cursor = database.queryFinalized("SELECT uid, mid FROM unread_push_messages WHERE 1"); + statement4 = database.executeFast("UPDATE unread_push_messages SET mid = ? WHERE uid = ? AND mid = ?"); + while (cursor.next()) { + long did = cursor.longValue(0); + int mid = cursor.intValue(1); + statement4.requery(); + statement4.bindInteger(1, mid); + statement4.bindLong(2, did); + statement4.bindInteger(3, mid); + statement4.step(); + } + statement4.dispose(); + cursor.dispose(); + + if (secretChatsToUpdate != null) { + SQLitePreparedStatement statement = database.executeFast("UPDATE dialogs SET did = ? WHERE did = ?"); + SQLitePreparedStatement statement2 = database.executeFast("UPDATE dialog_filter_pin_v2 SET peer = ? WHERE peer = ?"); + SQLitePreparedStatement statement3 = database.executeFast("UPDATE dialog_filter_ep SET peer = ? WHERE peer = ?"); + for (int a = 0, N = secretChatsToUpdate.size(); a < N; a++) { + int sid = secretChatsToUpdate.get(a); + + long newId = DialogObject.makeEncryptedDialogId(sid); + long oldId = ((long) sid) << 32; + statement.requery(); + statement.bindLong(1, newId); + statement.bindLong(2, oldId); + statement.step(); + + statement2.requery(); + statement2.bindLong(1, newId); + statement2.bindLong(2, oldId); + statement2.step(); + + statement3.requery(); + statement3.bindLong(1, newId); + statement3.bindLong(2, oldId); + statement3.step(); + } + statement.dispose(); + statement2.dispose(); + statement3.dispose(); + } + if (foldersToUpdate != null) { + SQLitePreparedStatement statement = database.executeFast("UPDATE dialogs SET did = ? WHERE did = ?"); + for (int a = 0, N = foldersToUpdate.size(); a < N; a++) { + int fid = foldersToUpdate.get(a); + + long newId = DialogObject.makeFolderDialogId(fid); + long oldId = (((long) 2) << 32) | fid; + statement.requery(); + statement.bindLong(1, newId); + statement.bindLong(2, oldId); + statement.step(); + } + statement.dispose(); + } + + database.executeFast("DROP INDEX IF EXISTS uid_mid_read_out_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS uid_date_mid_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS mid_out_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS task_idx_messages;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS send_state_idx_messages2;").stepThis().dispose(); + database.executeFast("DROP INDEX IF EXISTS uid_mention_idx_messages;").stepThis().dispose(); + database.executeFast("DROP TABLE IF EXISTS messages;").stepThis().dispose(); + database.commitTransaction(); + + database.executeFast("PRAGMA user_version = 84").stepThis().dispose(); + version = 84; + } + if (version == 84) { } } catch (Exception e) { FileLog.e(e); } + + AndroidUtilities.runOnUIThread(() -> { + NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.onDatabaseMigration, false); + }); }); } @@ -1044,7 +1505,7 @@ public class MessagesStorage extends BaseController { } } - public void cleanup(final boolean isLogin) { + public void cleanup(boolean isLogin) { storageQueue.postRunnable(() -> { cleanupInternal(true); openDatabase(1); @@ -1054,7 +1515,7 @@ public class MessagesStorage extends BaseController { }); } - public void saveSecretParams(final int lsv, final int sg, final byte[] pbytes) { + public void saveSecretParams(int lsv, int sg, byte[] pbytes) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE params SET lsv = ?, sg = ?, pbytes = ? WHERE id = 1"); @@ -1125,11 +1586,11 @@ public class MessagesStorage extends BaseController { }); } - public long createPendingTask(final NativeByteBuffer data) { + public long createPendingTask(NativeByteBuffer data) { if (data == null) { return 0; } - final long id = lastTaskId.getAndAdd(1); + long id = lastTaskId.getAndAdd(1); storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("REPLACE INTO pending_tasks VALUES(?, ?)"); @@ -1146,7 +1607,7 @@ public class MessagesStorage extends BaseController { return id; } - public void removePendingTask(final long id) { + public void removePendingTask(long id) { storageQueue.postRunnable(() -> { try { database.executeFast("DELETE FROM pending_tasks WHERE id = " + id).stepThis().dispose(); @@ -1161,21 +1622,21 @@ public class MessagesStorage extends BaseController { try { SQLiteCursor cursor = database.queryFinalized("SELECT id, data FROM pending_tasks WHERE 1"); while (cursor.next()) { - final long taskId = cursor.longValue(0); + long taskId = cursor.longValue(0); NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { int type = data.readInt32(false); switch (type) { case 0: { - final TLRPC.Chat chat = TLRPC.Chat.TLdeserialize(data, data.readInt32(false), false); + TLRPC.Chat chat = TLRPC.Chat.TLdeserialize(data, data.readInt32(false), false); if (chat != null) { Utilities.stageQueue.postRunnable(() -> getMessagesController().loadUnknownChannel(chat, taskId)); } break; } case 1: { - final int channelId = data.readInt32(false); - final int newDialogType = data.readInt32(false); + long channelId = data.readInt32(false); + int newDialogType = data.readInt32(false); Utilities.stageQueue.postRunnable(() -> getMessagesController().getChannelDifference(channelId, newDialogType, taskId, null)); break; } @@ -1184,7 +1645,7 @@ public class MessagesStorage extends BaseController { case 8: case 10: case 14: { - final TLRPC.Dialog dialog = new TLRPC.TL_dialog(); + TLRPC.Dialog dialog = new TLRPC.TL_dialog(); dialog.id = data.readInt64(false); dialog.top_message = data.readInt32(false); dialog.read_inbox_max_id = data.readInt32(false); @@ -1206,7 +1667,7 @@ public class MessagesStorage extends BaseController { if (type >= 14) { dialog.folder_id = data.readInt32(false); } - final TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); + TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); AndroidUtilities.runOnUIThread(() -> getMessagesController().checkLastDialogMessage(dialog, peer, taskId)); break; } @@ -1218,21 +1679,28 @@ public class MessagesStorage extends BaseController { break; } case 4: { - final long did = data.readInt64(false); - final boolean pin = data.readBool(false); - final TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); + long did = data.readInt64(false); + boolean pin = data.readBool(false); + TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); AndroidUtilities.runOnUIThread(() -> getMessagesController().pinDialog(did, pin, peer, taskId)); break; } case 6: { - final int channelId = data.readInt32(false); - final int newDialogType = data.readInt32(false); - final TLRPC.InputChannel inputChannel = TLRPC.InputChannel.TLdeserialize(data, data.readInt32(false), false); + long channelId = data.readInt32(false); + int newDialogType = data.readInt32(false); + TLRPC.InputChannel inputChannel = TLRPC.InputChannel.TLdeserialize(data, data.readInt32(false), false); + Utilities.stageQueue.postRunnable(() -> getMessagesController().getChannelDifference(channelId, newDialogType, taskId, inputChannel)); + break; + } + case 25: { + long channelId = data.readInt64(false); + int newDialogType = data.readInt32(false); + TLRPC.InputChannel inputChannel = TLRPC.InputChannel.TLdeserialize(data, data.readInt32(false), false); Utilities.stageQueue.postRunnable(() -> getMessagesController().getChannelDifference(channelId, newDialogType, taskId, inputChannel)); break; } case 7: { - final int channelId = data.readInt32(false); + long channelId = data.readInt32(false); int constructor = data.readInt32(false); TLObject request = TLRPC.TL_messages_deleteMessages.TLdeserialize(data, constructor, false); if (request == null) { @@ -1241,28 +1709,56 @@ public class MessagesStorage extends BaseController { if (request == null) { removePendingTask(taskId); } else { - final TLObject finalRequest = request; - AndroidUtilities.runOnUIThread(() -> getMessagesController().deleteMessages(null, null, null, 0, channelId, true, false, false, taskId, finalRequest)); + TLObject finalRequest = request; + AndroidUtilities.runOnUIThread(() -> getMessagesController().deleteMessages(null, null, null, -channelId, true, false, false, taskId, finalRequest)); + } + break; + } + case 24: { + long dialogId = data.readInt64(false); + int constructor = data.readInt32(false); + TLObject request = TLRPC.TL_messages_deleteMessages.TLdeserialize(data, constructor, false); + if (request == null) { + request = TLRPC.TL_channels_deleteMessages.TLdeserialize(data, constructor, false); + } + if (request == null) { + removePendingTask(taskId); + } else { + TLObject finalRequest = request; + AndroidUtilities.runOnUIThread(() -> getMessagesController().deleteMessages(null, null, null, dialogId, true, false, false, taskId, finalRequest)); } break; } case 9: { - final long did = data.readInt64(false); - final TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); + long did = data.readInt64(false); + TLRPC.InputPeer peer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); AndroidUtilities.runOnUIThread(() -> getMessagesController().markDialogAsUnread(did, peer, taskId)); break; } case 11: { TLRPC.InputChannel inputChannel; - final int mid = data.readInt32(false); - final int channelId = data.readInt32(false); - final int ttl = data.readInt32(false); + int mid = data.readInt32(false); + long channelId = data.readInt32(false); + int ttl = data.readInt32(false); if (channelId != 0) { inputChannel = TLRPC.InputChannel.TLdeserialize(data, data.readInt32(false), false); } else { inputChannel = null; } - AndroidUtilities.runOnUIThread(() -> getMessagesController().markMessageAsRead(mid, channelId, inputChannel, ttl, taskId)); + AndroidUtilities.runOnUIThread(() -> getMessagesController().markMessageAsRead2(-channelId, mid, inputChannel, ttl, taskId)); + break; + } + case 23: { + TLRPC.InputChannel inputChannel; + long dialogId = data.readInt64(false); + int mid = data.readInt32(false); + int ttl = data.readInt32(false); + if (!DialogObject.isEncryptedDialog(dialogId) && DialogObject.isChatDialog(dialogId) && data.hasRemaining()) { + inputChannel = TLRPC.InputChannel.TLdeserialize(data, data.readInt32(false), false); + } else { + inputChannel = null; + } + AndroidUtilities.runOnUIThread(() -> getMessagesController().markMessageAsRead2(dialogId, mid, inputChannel, ttl, taskId)); break; } case 12: @@ -1286,11 +1782,11 @@ public class MessagesStorage extends BaseController { break; } case 13: { - final long did = data.readInt64(false); - final boolean first = data.readBool(false); - final int onlyHistory = data.readInt32(false); - final int maxIdDelete = data.readInt32(false); - final boolean revoke = data.readBool(false); + long did = data.readInt64(false); + boolean first = data.readBool(false); + int onlyHistory = data.readInt32(false); + int maxIdDelete = data.readInt32(false); + boolean revoke = data.readBool(false); TLRPC.InputPeer inputPeer = TLRPC.InputPeer.TLdeserialize(data, data.readInt32(false), false); AndroidUtilities.runOnUIThread(() -> getMessagesController().deleteDialog(did, first ? 1 : 0, onlyHistory, maxIdDelete, revoke, inputPeer, taskId)); break; @@ -1301,7 +1797,7 @@ public class MessagesStorage extends BaseController { break; } case 16: { - final int folderId = data.readInt32(false); + int folderId = data.readInt32(false); int count = data.readInt32(false); ArrayList peers = new ArrayList<>(); for (int a = 0; a < count; a++) { @@ -1312,7 +1808,7 @@ public class MessagesStorage extends BaseController { break; } case 17: { - final int folderId = data.readInt32(false); + int folderId = data.readInt32(false); int count = data.readInt32(false); ArrayList peers = new ArrayList<>(); for (int a = 0; a < count; a++) { @@ -1323,15 +1819,14 @@ public class MessagesStorage extends BaseController { break; } case 18: { - final long dialogId = data.readInt64(false); - final int channelId = data.readInt32(false); + long dialogId = data.readInt64(false); + data.readInt32(false); int constructor = data.readInt32(false); TLObject request = TLRPC.TL_messages_deleteScheduledMessages.TLdeserialize(data, constructor, false); if (request == null) { removePendingTask(taskId); } else { - final TLObject finalRequest = request; - AndroidUtilities.runOnUIThread(() -> MessagesController.getInstance(currentAccount).deleteMessages(null, null, null, dialogId, channelId, true, true, false, taskId, finalRequest)); + AndroidUtilities.runOnUIThread(() -> getMessagesController().deleteMessages(null, null, null, dialogId, true, true, false, taskId, request)); } break; } @@ -1357,12 +1852,12 @@ public class MessagesStorage extends BaseController { }); } - public void saveChannelPts(final int channelId, final int pts) { + public void saveChannelPts(long channelId, int pts) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE dialogs SET pts = ? WHERE did = ?"); state.bindInteger(1, pts); - state.bindInteger(2, -channelId); + state.bindLong(2, -channelId); state.step(); state.dispose(); } catch (Exception e) { @@ -1371,7 +1866,7 @@ public class MessagesStorage extends BaseController { }); } - private void saveDiffParamsInternal(final int seq, final int pts, final int date, final int qts) { + private void saveDiffParamsInternal(int seq, int pts, int date, int qts) { try { if (lastSavedSeq == seq && lastSavedPts == pts && lastSavedDate == date && lastQtsValue == qts) { return; @@ -1392,7 +1887,7 @@ public class MessagesStorage extends BaseController { } } - public void saveDiffParams(final int seq, final int pts, final int date, final int qts) { + public void saveDiffParams(int seq, int pts, int date, int qts) { storageQueue.postRunnable(() -> saveDiffParamsInternal(seq, pts, date, qts)); } @@ -1400,7 +1895,7 @@ public class MessagesStorage extends BaseController { storageQueue.postRunnable(() -> resetAllUnreadCounters(true)); } - public void setDialogFlags(final long did, final long flags) { + public void setDialogFlags(long did, long flags) { storageQueue.postRunnable(() -> { try { int oldFlags = 0; @@ -1426,11 +1921,6 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(message.messageOwner.getObjectSize()); message.messageOwner.serializeToStream(data); - long messageId = message.getId(); - if (message.messageOwner.peer_id.channel_id != 0) { - messageId |= ((long) message.messageOwner.peer_id.channel_id) << 32; - } - int flags = 0; if (message.localType == 2) { flags |= 1; @@ -1442,7 +1932,7 @@ public class MessagesStorage extends BaseController { SQLitePreparedStatement state = database.executeFast("REPLACE INTO unread_push_messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"); state.requery(); state.bindLong(1, message.getDialogId()); - state.bindLong(2, messageId); + state.bindInteger(2, message.getId()); state.bindLong(3, message.messageOwner.random_id); state.bindInteger(4, message.messageOwner.date); state.bindByteBuffer(5, data); @@ -1481,11 +1971,11 @@ public class MessagesStorage extends BaseController { public void readAllDialogs(int folderId) { storageQueue.postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedChatIds = new ArrayList<>(); - final LongSparseArray dialogs = new LongSparseArray<>(); + LongSparseArray dialogs = new LongSparseArray<>(); SQLiteCursor cursor; if (folderId >= 0) { cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, last_mid, unread_count, date FROM dialogs WHERE unread_count > 0 AND folder_id = %1$d", folderId)); @@ -1503,29 +1993,28 @@ public class MessagesStorage extends BaseController { dialog.date = cursor.intValue(3); dialogs.put(did, dialog); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); + if (!DialogObject.isEncryptedDialog(did)) { + if (DialogObject.isChatDialog(did)) { + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); + if (!usersToLoad.contains(did)) { + usersToLoad.add(did); } } } else { - if (!encryptedChatIds.contains(high_id)) { - encryptedChatIds.add(high_id); + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedChatIds.contains(encryptedChatId)) { + encryptedChatIds.add(encryptedChatId); } } } cursor.dispose(); - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - final ArrayList encryptedChats = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList encryptedChats = new ArrayList<>(); if (!encryptedChatIds.isEmpty()) { getEncryptedChatsInternal(TextUtils.join(",", encryptedChatIds), encryptedChats, usersToLoad); } @@ -1551,12 +2040,11 @@ public class MessagesStorage extends BaseController { }); } - private TLRPC.messages_Dialogs loadDialogsByIds(String ids, ArrayList usersToLoad, ArrayList chatsToLoad, ArrayList encryptedToLoad) throws Exception { + private TLRPC.messages_Dialogs loadDialogsByIds(String ids, ArrayList usersToLoad, ArrayList chatsToLoad, ArrayList encryptedToLoad) throws Exception { TLRPC.messages_Dialogs dialogs = new TLRPC.TL_messages_dialogs(); - ArrayList replyMessages = new ArrayList<>(); LongSparseArray replyMessageOwners = new LongSparseArray<>(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date, d.pts, d.inbox_max, d.outbox_max, m.replydata, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.did IN (%s) ORDER BY d.pinned DESC, d.date DESC", ids)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date, d.pts, d.inbox_max, d.outbox_max, m.replydata, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.did IN (%s) ORDER BY d.pinned DESC, d.date DESC", ids)); while (cursor.next()) { long dialogId = cursor.longValue(0); TLRPC.Dialog dialog = new TLRPC.TL_dialog(); @@ -1565,7 +2053,7 @@ public class MessagesStorage extends BaseController { dialog.unread_count = cursor.intValue(2); dialog.last_message_date = cursor.intValue(3); dialog.pts = cursor.intValue(10); - dialog.flags = dialog.pts == 0 || (int) dialog.id > 0 ? 0 : 1; + dialog.flags = dialog.pts == 0 || DialogObject.isUserDialog(dialog.id) ? 0 : 1; dialog.read_inbox_max_id = cursor.intValue(11); dialog.read_outbox_max_id = cursor.intValue(12); dialog.pinnedNum = cursor.intValue(14); @@ -1620,17 +2108,6 @@ public class MessagesStorage extends BaseController { } } if (message.replyMessage == null) { - long messageId = message.reply_to.reply_to_msg_id; - if (message.reply_to.reply_to_peer_id != null) { - if (message.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) message.reply_to.reply_to_peer_id.channel_id) << 32; - } - } else if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - if (!replyMessages.contains(messageId)) { - replyMessages.add(messageId); - } replyMessageOwners.put(dialog.id, message); } } @@ -1641,49 +2118,46 @@ public class MessagesStorage extends BaseController { data.reuse(); } } - - int lower_id = (int) dialog.id; - int high_id = (int) (dialog.id >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } - } else { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(dialogId)) { + if (!usersToLoad.contains(dialogId)) { + usersToLoad.add(dialogId); } } else { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + if (!chatsToLoad.contains(-dialogId)) { + chatsToLoad.add(-dialogId); } } } cursor.dispose(); - if (!replyMessages.isEmpty()) { - SQLiteCursor replyCursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages))); - while (replyCursor.next()) { - NativeByteBuffer data = replyCursor.byteBufferValue(0); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - message.id = replyCursor.intValue(1); - message.date = replyCursor.intValue(2); - message.dialog_id = replyCursor.longValue(3); + if (!replyMessageOwners.isEmpty()) { + for (int a = 0, N = replyMessageOwners.size(); a < N; a++) { + long dialogId = replyMessageOwners.keyAt(a); + TLRPC.Message ownerMessage = replyMessageOwners.valueAt(a); + SQLiteCursor replyCursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages_v2 WHERE mid = %d and uid = %d", ownerMessage.id, dialogId)); + while (replyCursor.next()) { + NativeByteBuffer data = replyCursor.byteBufferValue(0); + if (data != null) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + message.readAttachPath(data, getUserConfig().clientUserId); + data.reuse(); + message.id = replyCursor.intValue(1); + message.date = replyCursor.intValue(2); + message.dialog_id = replyCursor.longValue(3); - addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); + addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - TLRPC.Message owner = replyMessageOwners.get(message.dialog_id); - if (owner != null) { - owner.replyMessage = message; - message.dialog_id = owner.dialog_id; + ownerMessage.replyMessage = message; + message.dialog_id = ownerMessage.dialog_id; } } + replyCursor.dispose(); } - replyCursor.dispose(); } return dialogs; } @@ -1691,8 +2165,8 @@ public class MessagesStorage extends BaseController { private void loadDialogFilters() { storageQueue.postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); ArrayList dialogsToLoad = new ArrayList<>(); SparseArray filtersById = new SparseArray<>(); @@ -1725,10 +2199,9 @@ public class MessagesStorage extends BaseController { } while (cursor2.next()) { long did = cursor2.longValue(0); - int lower_id = (int) did; if (a == 0) { - if (lower_id != 0) { - filter.alwaysShow.add(lower_id); + if (!DialogObject.isEncryptedDialog(did)) { + filter.alwaysShow.add(did); } int pin = cursor2.intValue(1); if (pin != Integer.MIN_VALUE) { @@ -1738,22 +2211,22 @@ public class MessagesStorage extends BaseController { } } } else { - if (lower_id != 0) { - filter.neverShow.add(lower_id); + if (!DialogObject.isEncryptedDialog(did)) { + filter.neverShow.add(did); } } - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); + if (DialogObject.isChatDialog(did)) { + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } - } else if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); + } else if (DialogObject.isUserDialog(did)) { + if (!usersToLoad.contains(did)) { + usersToLoad.add(did); } } else { - int high_id = (int) (did >> 32); - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); } } } @@ -1782,8 +2255,8 @@ public class MessagesStorage extends BaseController { dialogs = new TLRPC.TL_messages_dialogs(); } - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); if (!encryptedToLoad.isEmpty()) { @@ -1822,13 +2295,13 @@ public class MessagesStorage extends BaseController { dialogsWithMentions.clear(); dialogsWithUnread.clear(); - final ArrayList users = new ArrayList<>(); - final ArrayList encUsers = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList encUsers = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); - LongSparseArray dialogsByFolders = new LongSparseArray<>(); + LongSparseIntArray dialogsByFolders = new LongSparseIntArray(); SQLiteCursor cursor = database.queryFinalized("SELECT did, folder_id, unread_count, unread_count_i FROM dialogs WHERE unread_count > 0 OR flags > 0 UNION ALL " + "SELECT did, folder_id, unread_count, unread_count_i FROM dialogs WHERE unread_count_i > 0"); while (cursor.next()) { @@ -1846,31 +2319,28 @@ public class MessagesStorage extends BaseController { FileLog.d("unread chat " + did + " counters = " + unread + " and " + mentions); }*/ dialogsByFolders.put(did, folderId); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } - } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } + if (DialogObject.isEncryptedDialog(did)) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(did)) { + if (!usersToLoad.contains(did)) { + usersToLoad.add(did); } } else { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } } } cursor.dispose(); - SparseArray usersDict = new SparseArray<>(); - SparseArray chatsDict = new SparseArray<>(); - SparseArray encUsersDict = new SparseArray<>(); - SparseArray encryptedChatsByUsersCount = new SparseArray<>(); - SparseArray mutedDialogs = new SparseArray<>(); - SparseArray archivedDialogs = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); + LongSparseArray encUsersDict = new LongSparseArray<>(); + LongSparseIntArray encryptedChatsByUsersCount = new LongSparseIntArray(); + LongSparseArray mutedDialogs = new LongSparseArray<>(); + LongSparseArray archivedDialogs = new LongSparseArray<>(); if (!usersToLoad.isEmpty()) { getUsersInternal(TextUtils.join(",", usersToLoad), users); for (int a = 0, N = users.size(); a < N; a++) { @@ -1895,7 +2365,7 @@ public class MessagesStorage extends BaseController { } } if (!encryptedToLoad.isEmpty()) { - ArrayList encUsersToLoad = new ArrayList<>(); + ArrayList encUsersToLoad = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, encUsersToLoad); if (!encUsersToLoad.isEmpty()) { @@ -1910,7 +2380,7 @@ public class MessagesStorage extends BaseController { if (user == null) { continue; } - long did = ((long) encryptedChat.id) << 32; + long did = DialogObject.makeEncryptedDialogId(encryptedChat.id); boolean muted = getMessagesController().isDialogMuted(did); int idx1 = dialogsByFolders.get(did); int idx2 = muted ? 1 : 0; @@ -2059,10 +2529,10 @@ public class MessagesStorage extends BaseController { } if (filter != null) { for (int b = 0, N2 = filter.alwaysShow.size(); b < N2; b++) { - int did = filter.alwaysShow.get(b); - if (did > 0) { + long did = filter.alwaysShow.get(b); + if (DialogObject.isUserDialog(did)) { for (int i = 0; i < 2; i++) { - SparseArray dict = i == 0 ? usersDict : encUsersDict; + LongSparseArray dict = i == 0 ? usersDict : encUsersDict; TLRPC.User user = dict.get(did); if (user != null) { int count; @@ -2111,10 +2581,10 @@ public class MessagesStorage extends BaseController { } } for (int b = 0, N2 = filter.neverShow.size(); b < N2; b++) { - int did = filter.neverShow.get(b); - if (did > 0) { + long did = filter.neverShow.get(b); + if (DialogObject.isUserDialog(did)) { for (int i = 0; i < 2; i++) { - SparseArray dict = i == 0 ? usersDict : encUsersDict; + LongSparseArray dict = i == 0 ? usersDict : encUsersDict; TLRPC.User user = dict.get(did); if (user != null) { int count; @@ -2218,7 +2688,7 @@ public class MessagesStorage extends BaseController { } for (int a = 0, N = filter.pinnedDialogs.size(); a < N; a++) { long key = filter.pinnedDialogs.keyAt(a); - if ((int) key != 0) { + if (!DialogObject.isEncryptedDialog(key)) { continue; } state.requery(); @@ -2253,15 +2723,15 @@ public class MessagesStorage extends BaseController { filtersToDelete.put(filter.id, filter); } ArrayList filtersOrder = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - HashMap usersToLoadMap = new HashMap<>(); - ArrayList chatsToLoad = new ArrayList<>(); - HashMap chatsToLoadMap = new HashMap<>(); - ArrayList dialogsToLoad = new ArrayList<>(); - HashMap dialogsToLoadMap = new HashMap<>(); + ArrayList usersToLoad = new ArrayList<>(); + HashMap usersToLoadMap = new HashMap<>(); + ArrayList chatsToLoad = new ArrayList<>(); + HashMap chatsToLoadMap = new HashMap<>(); + ArrayList dialogsToLoad = new ArrayList<>(); + HashMap dialogsToLoadMap = new HashMap<>(); ArrayList filtersToSave = new ArrayList<>(); - HashMap> filterUserRemovals = new HashMap<>(); - HashMap> filterDialogRemovals = new HashMap<>(); + HashMap> filterUserRemovals = new HashMap<>(); + HashMap> filterDialogRemovals = new HashMap<>(); HashSet filtersUnreadCounterReset = new HashSet<>(); for (int a = 0, N = vector.objects.size(); a < N; a++) { TLRPC.TL_dialogFilter newFilter = (TLRPC.TL_dialogFilter) vector.objects.get(a); @@ -2307,9 +2777,9 @@ public class MessagesStorage extends BaseController { unreadChanged = true; } - HashSet existingIds = new HashSet<>(filter.alwaysShow); + HashSet existingIds = new HashSet<>(filter.alwaysShow); existingIds.addAll(filter.neverShow); - HashSet existingDialogsIds = new HashSet<>(); + HashSet existingDialogsIds = new HashSet<>(); LinkedHashMap secretChatsMap = null; if (filter.pinnedDialogs.size() != 0) { @@ -2317,14 +2787,14 @@ public class MessagesStorage extends BaseController { boolean hasSecret = false; for (int c = 0, N2 = filter.pinnedDialogs.size(); c < N2; c++) { long did = filter.pinnedDialogs.keyAt(c); - if ((int) did == 0) { + if (DialogObject.isEncryptedDialog(did)) { hasSecret = true; } pinArray.add(did); } if (hasSecret) { secretChatsMap = new LinkedHashMap<>(); - LongSparseArray pinnedDialogs = filter.pinnedDialogs; + LongSparseIntArray pinnedDialogs = filter.pinnedDialogs; Collections.sort(pinArray, (o1, o2) -> { int idx1 = pinnedDialogs.get(o1); int idx2 = pinnedDialogs.get(o2); @@ -2337,7 +2807,7 @@ public class MessagesStorage extends BaseController { }); for (int c = 0, N2 = pinArray.size(); c < N2; c++) { long did = pinArray.get(c); - if ((int) did != 0) { + if (!DialogObject.isEncryptedDialog(did)) { continue; } secretChatsMap.put(c, did); @@ -2347,22 +2817,21 @@ public class MessagesStorage extends BaseController { for (int c = 0, N2 = filter.pinnedDialogs.size(); c < N2; c++) { long did = filter.pinnedDialogs.keyAt(c); - int lowerId = (int) did; - if (lowerId == 0) { + if (DialogObject.isEncryptedDialog(did)) { continue; } - existingDialogsIds.add(lowerId); - existingIds.remove(lowerId); + existingDialogsIds.add(did); + existingIds.remove(did); } for (int c = 0; c < 2; c++) { ArrayList fromArray = c == 0 ? newFilter.include_peers : newFilter.exclude_peers; - ArrayList toArray = c == 0 ? filter.alwaysShow : filter.neverShow; + ArrayList toArray = c == 0 ? filter.alwaysShow : filter.neverShow; if (c == 0) { filter.pinnedDialogs.clear(); for (int b = 0, N2 = newFilter.pinned_peers.size(); b < N2; b++) { TLRPC.InputPeer peer = newFilter.pinned_peers.get(b); - Integer id; + Long id; if (peer.user_id != 0) { id = peer.user_id; } else { @@ -2398,7 +2867,7 @@ public class MessagesStorage extends BaseController { for (int b = 0, N2 = fromArray.size(); b < N2; b++) { TLRPC.InputPeer peer = fromArray.get(b); if (peer.user_id != 0) { - Integer uid = peer.user_id; + Long uid = peer.user_id; if (!existingIds.remove(uid)) { changed = true; if (!toArray.contains(uid)) { @@ -2411,12 +2880,12 @@ public class MessagesStorage extends BaseController { } } } else { - Integer chatId = peer.chat_id != 0 ? peer.chat_id : peer.channel_id; - Integer lowerId = -chatId; - if (!existingIds.remove(lowerId)) { + Long chatId = peer.chat_id != 0 ? peer.chat_id : peer.channel_id; + Long dialogId = -chatId; + if (!existingIds.remove(dialogId)) { changed = true; - if (!toArray.contains(lowerId)) { - toArray.add(lowerId); + if (!toArray.contains(dialogId)) { + toArray.add(dialogId); } if (!chatsToLoadMap.containsKey(chatId)) { chatsToLoad.add(chatId); @@ -2452,7 +2921,7 @@ public class MessagesStorage extends BaseController { if (c == 0) { for (int b = 0, N2 = newFilter.pinned_peers.size(); b < N2; b++) { TLRPC.InputPeer peer = newFilter.pinned_peers.get(b); - Integer id; + Long id; if (peer.user_id != 0) { id = peer.user_id; } else { @@ -2469,11 +2938,11 @@ public class MessagesStorage extends BaseController { } } ArrayList fromArray = c == 0 ? newFilter.include_peers : newFilter.exclude_peers; - ArrayList toArray = c == 0 ? filter.alwaysShow : filter.neverShow; + ArrayList toArray = c == 0 ? filter.alwaysShow : filter.neverShow; for (int b = 0, N2 = fromArray.size(); b < N2; b++) { TLRPC.InputPeer peer = fromArray.get(b); if (peer.user_id != 0) { - Integer uid = peer.user_id; + Long uid = peer.user_id; if (!toArray.contains(uid)) { toArray.add(uid); } @@ -2482,10 +2951,10 @@ public class MessagesStorage extends BaseController { usersToLoadMap.put(uid, peer); } } else { - Integer chatId = peer.chat_id != 0 ? peer.chat_id : peer.channel_id; - Integer lowerId = -chatId; - if (!toArray.contains(lowerId)) { - toArray.add(lowerId); + Long chatId = peer.chat_id != 0 ? peer.chat_id : peer.channel_id; + Long dialogId = -chatId; + if (!toArray.contains(dialogId)) { + toArray.add(dialogId); } if (!chatsToLoadMap.containsKey(chatId)) { chatsToLoad.add(chatId); @@ -2503,7 +2972,7 @@ public class MessagesStorage extends BaseController { dialogs = loadDialogsByIds(TextUtils.join(",", dialogsToLoad), usersToLoad, chatsToLoad, new ArrayList<>()); for (int a = 0, N = dialogs.dialogs.size(); a < N; a++) { TLRPC.Dialog dialog = dialogs.dialogs.get(a); - dialogsToLoadMap.remove((int) dialog.id); + dialogsToLoadMap.remove(dialog.id); } } else { dialogs = new TLRPC.TL_messages_dialogs(); @@ -2536,7 +3005,7 @@ public class MessagesStorage extends BaseController { }); } - private void processLoadedFilterPeersInternal(TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { + private void processLoadedFilterPeersInternal(TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { boolean anythingChanged = false; putUsersAndChats(users, chats, true, false); for (int a = 0, N = filtersToDelete.size(); a < N; a++) { @@ -2550,24 +3019,24 @@ public class MessagesStorage extends BaseController { } filter.pendingUnreadCount = -1; } - for (HashMap.Entry> entry : filterUserRemovals.entrySet()) { + for (HashMap.Entry> entry : filterUserRemovals.entrySet()) { MessagesController.DialogFilter filter = dialogFiltersMap.get(entry.getKey()); if (filter == null) { continue; } - HashSet set = entry.getValue(); + HashSet set = entry.getValue(); filter.alwaysShow.removeAll(set); filter.neverShow.removeAll(set); anythingChanged = true; } - for (HashMap.Entry> entry : filterDialogRemovals.entrySet()) { + for (HashMap.Entry> entry : filterDialogRemovals.entrySet()) { MessagesController.DialogFilter filter = dialogFiltersMap.get(entry.getKey()); if (filter == null) { continue; } - HashSet set = entry.getValue(); - for (Integer id : set) { - filter.pinnedDialogs.remove((long) id); + HashSet set = entry.getValue(); + for (Long id : set) { + filter.pinnedDialogs.delete(id); } anythingChanged = true; } @@ -2601,7 +3070,7 @@ public class MessagesStorage extends BaseController { getMessagesController().processLoadedDialogFilters(new ArrayList<>(dialogFilters), pinnedDialogs, pinnedRemoteDialogs, users, chats, null, remote); } - protected void processLoadedFilterPeers(TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { + protected void processLoadedFilterPeers(TLRPC.messages_Dialogs pinnedDialogs, TLRPC.messages_Dialogs pinnedRemoteDialogs, ArrayList users, ArrayList chats, ArrayList filtersToSave, SparseArray filtersToDelete, ArrayList filtersOrder, HashMap> filterDialogRemovals, HashMap> filterUserRemovals, HashSet filtersUnreadCounterReset) { storageQueue.postRunnable(() -> processLoadedFilterPeersInternal(pinnedDialogs, pinnedRemoteDialogs, users, chats, filtersToSave, filtersToDelete, filtersOrder, filterDialogRemovals, filterUserRemovals, filtersUnreadCounterReset)); } @@ -2658,14 +3127,77 @@ public class MessagesStorage extends BaseController { storageQueue.postRunnable(this::saveDialogFiltersOrderInternal); } + protected static void addReplyMessages(TLRPC.Message message, LongSparseArray>> replyMessageOwners, LongSparseArray> dialogReplyMessagesIds) { + int messageId = message.reply_to.reply_to_msg_id; + long dialogId = MessageObject.getReplyToDialogId(message); + SparseArray> sparseArray = replyMessageOwners.get(dialogId); + ArrayList ids = dialogReplyMessagesIds.get(dialogId); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + replyMessageOwners.put(dialogId, sparseArray); + } + if (ids == null) { + ids = new ArrayList<>(); + dialogReplyMessagesIds.put(dialogId, ids); + } + ArrayList arrayList = sparseArray.get(message.reply_to.reply_to_msg_id); + if (arrayList == null) { + arrayList = new ArrayList<>(); + sparseArray.put(message.reply_to.reply_to_msg_id, arrayList); + if (!ids.contains(message.reply_to.reply_to_msg_id)) { + ids.add(message.reply_to.reply_to_msg_id); + } + } + arrayList.add(message); + } + + protected void loadReplyMessages(LongSparseArray>> replyMessageOwners, LongSparseArray> dialogReplyMessagesIds, ArrayList usersToLoad, ArrayList chatsToLoad) throws SQLiteException { + if (replyMessageOwners.isEmpty()) { + return; + } + + for (int b = 0, N2 = replyMessageOwners.size(); b < N2; b++) { + long dialogId = replyMessageOwners.keyAt(b); + SparseArray> owners = replyMessageOwners.valueAt(b); + ArrayList ids = dialogReplyMessagesIds.get(dialogId); + if (ids == null) { + continue; + } + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages_v2 WHERE mid IN(%s) AND uid = %d", TextUtils.join(",", ids), dialogId)); + while (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(0); + if (data != null) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + message.readAttachPath(data, getUserConfig().clientUserId); + data.reuse(); + message.id = cursor.intValue(1); + message.date = cursor.intValue(2); + message.dialog_id = cursor.longValue(3); + + addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); + + ArrayList arrayList = owners.get(message.id); + if (arrayList != null) { + for (int a = 0, N = arrayList.size(); a < N; a++) { + TLRPC.Message m = arrayList.get(a); + m.replyMessage = message; + MessageObject.getDialogId(message); + } + } + } + } + cursor.dispose(); + } + } + public void loadUnreadMessages() { storageQueue.postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedChatIds = new ArrayList<>(); - final LongSparseArray pushDialogs = new LongSparseArray<>(); + LongSparseArray pushDialogs = new LongSparseArray<>(); SQLiteCursor cursor = database.queryFinalized("SELECT d.did, d.unread_count, s.flags FROM dialogs as d LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.unread_count > 0"); StringBuilder ids = new StringBuilder(); int currentTime = getConnectionsManager().getCurrentTime(); @@ -2684,37 +3216,34 @@ public class MessagesStorage extends BaseController { ids.append(","); } ids.append(did); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } - } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } + if (DialogObject.isEncryptedDialog(did)) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedChatIds.contains(encryptedChatId)) { + encryptedChatIds.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(did)) { + if (!usersToLoad.contains(did)) { + usersToLoad.add(did); } } else { - if (!encryptedChatIds.contains(high_id)) { - encryptedChatIds.add(high_id); + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } } } } cursor.dispose(); - ArrayList replyMessages = new ArrayList<>(); - SparseArray> replyMessageOwners = new SparseArray<>(); - final ArrayList messages = new ArrayList<>(); - final ArrayList pushMessages = new ArrayList<>(); - final ArrayList users = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - final ArrayList encryptedChats = new ArrayList<>(); + LongSparseArray>> replyMessageOwners = new LongSparseArray<>(); + LongSparseArray> dialogReplyMessagesIds = new LongSparseArray<>(); + ArrayList messages = new ArrayList<>(); + ArrayList pushMessages = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList encryptedChats = new ArrayList<>(); int maxDate = 0; if (ids.length() > 0) { - cursor = database.queryFinalized("SELECT read_state, data, send_state, mid, date, uid, replydata FROM messages WHERE uid IN (" + ids.toString() + ") AND out = 0 AND read_state IN(0,2) ORDER BY date DESC LIMIT 50"); + cursor = database.queryFinalized("SELECT read_state, data, send_state, mid, date, uid, replydata FROM messages_v2 WHERE uid IN (" + ids.toString() + ") AND out = 0 AND read_state IN(0,2) ORDER BY date DESC LIMIT 50"); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { @@ -2728,13 +3257,12 @@ public class MessagesStorage extends BaseController { messages.add(message); maxDate = Math.max(maxDate, message.date); - int lower_id = (int) message.dialog_id; addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); message.send_state = cursor.intValue(2); - if (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && lower_id != 0 || message.id > 0) { + if (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && !DialogObject.isEncryptedDialog(message.dialog_id) || message.id > 0) { message.send_state = 0; } - if (lower_id == 0 && !cursor.isNull(5)) { + if (DialogObject.isEncryptedDialog(message.dialog_id) && !cursor.isNull(5)) { message.random_id = cursor.longValue(5); } @@ -2755,23 +3283,7 @@ public class MessagesStorage extends BaseController { } } if (message.replyMessage == null) { - long messageId = message.reply_to.reply_to_msg_id; - if (message.reply_to.reply_to_peer_id != null) { - if (message.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) message.reply_to.reply_to_peer_id.channel_id) << 32; - } - } else if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - if (!replyMessages.contains(messageId)) { - replyMessages.add(messageId); - } - ArrayList arrayList = replyMessageOwners.get(message.reply_to.reply_to_msg_id); - if (arrayList == null) { - arrayList = new ArrayList<>(); - replyMessageOwners.put(message.reply_to.reply_to_msg_id, arrayList); - } - arrayList.add(message); + addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds); } } } catch (Exception e) { @@ -2797,20 +3309,18 @@ public class MessagesStorage extends BaseController { String userName = cursor.isNull(7) ? null : cursor.stringValue(7); int flags = cursor.intValue(8); if (MessageObject.getFromChatId(message) == 0) { - int lowerId = (int) message.dialog_id; - if (lowerId > 0) { + if (DialogObject.isUserDialog(message.dialog_id)) { message.from_id = new TLRPC.TL_peerUser(); - message.from_id.user_id = lowerId; + message.from_id.user_id = message.dialog_id; } } - int lower_id = (int) message.dialog_id; - if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); + if (DialogObject.isUserDialog(message.dialog_id)) { + if (!usersToLoad.contains(message.dialog_id)) { + usersToLoad.add(message.dialog_id); } - } else if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); + } else if (DialogObject.isChatDialog(message.dialog_id)) { + if (!chatsToLoad.contains(-message.dialog_id)) { + chatsToLoad.add(-message.dialog_id); } } @@ -2820,31 +3330,7 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); - if (!replyMessages.isEmpty()) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages))); - while (cursor.next()) { - NativeByteBuffer data = cursor.byteBufferValue(0); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - message.id = cursor.intValue(1); - message.date = cursor.intValue(2); - message.dialog_id = cursor.longValue(3); - - addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - - ArrayList arrayList = replyMessageOwners.get(message.id); - if (arrayList != null) { - for (int a = 0; a < arrayList.size(); a++) { - TLRPC.Message m = arrayList.get(a); - m.replyMessage = message; - } - } - } - } - cursor.dispose(); - } + loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad); if (!encryptedChatIds.isEmpty()) { getEncryptedChatsInternal(TextUtils.join(",", encryptedChatIds), encryptedChats, usersToLoad); @@ -2861,7 +3347,7 @@ public class MessagesStorage extends BaseController { if (chat != null && (ChatObject.isNotInChat(chat) || chat.min || chat.migrated_to != null)) { long did = -chat.id; database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = 3 WHERE uid = %d AND mid > 0 AND read_state IN(0,2) AND out = 0", did)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = 3 WHERE uid = %d AND mid > 0 AND read_state IN(0,2) AND out = 0", did)).stepThis().dispose(); chats.remove(a); a--; pushDialogs.remove(did); @@ -2884,7 +3370,7 @@ public class MessagesStorage extends BaseController { }); } - public void putWallpapers(final ArrayList wallPapers, int action) { + public void putWallpapers(ArrayList wallPapers, int action) { storageQueue.postRunnable(() -> { try { if (action == 1) { @@ -2940,7 +3426,7 @@ public class MessagesStorage extends BaseController { SQLiteCursor cursor = null; try { cursor = database.queryFinalized("SELECT data FROM wallpapers2 WHERE 1 ORDER BY num ASC"); - final ArrayList wallPapers = new ArrayList<>(); + ArrayList wallPapers = new ArrayList<>(); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -2962,7 +3448,7 @@ public class MessagesStorage extends BaseController { }); } - public void addRecentLocalFile(final String imageUrl, final String localUrl, final TLRPC.Document document) { + public void addRecentLocalFile(String imageUrl, String localUrl, TLRPC.Document document) { if (imageUrl == null || imageUrl.length() == 0 || ((localUrl == null || localUrl.length() == 0) && document == null)) { return; } @@ -2992,11 +3478,11 @@ public class MessagesStorage extends BaseController { }); } - public void deleteUserChatHistory(long did, int channelId, int fromId) { + public void deleteUserChatHistory(long dialogId, long fromId) { storageQueue.postRunnable(() -> { try { - final ArrayList mids = new ArrayList<>(); - SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages WHERE uid = " + did); + ArrayList mids = new ArrayList<>(); + SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + dialogId); ArrayList filesToDelete = new ArrayList<>(); ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); @@ -3007,7 +3493,7 @@ public class MessagesStorage extends BaseController { TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); if (message != null) { message.readAttachPath(data, getUserConfig().clientUserId); - if (UserObject.isReplyUser(did) && MessageObject.getPeerId(message.fwd_from.from_id) == fromId || MessageObject.getFromChatId(message) == fromId && message.id != 1) { + if (UserObject.isReplyUser(dialogId) && MessageObject.getPeerId(message.fwd_from.from_id) == fromId || MessageObject.getFromChatId(message) == fromId && message.id != 1) { mids.add(message.id); addFilesToDelete(message, filesToDelete, idsToDelete, namesToDelete, false); } @@ -3022,13 +3508,13 @@ public class MessagesStorage extends BaseController { deleteFromDownloadQueue(idsToDelete, true); AndroidUtilities.runOnUIThread(() -> { getFileLoader().cancelLoadFiles(namesToDelete); - getMessagesController().markDialogMessageAsDeleted(mids, did); + getMessagesController().markDialogMessageAsDeleted(dialogId, mids); }); - markMessagesAsDeletedInternal(mids, channelId, false, false); - updateDialogsWithDeletedMessagesInternal(mids, null, channelId); + markMessagesAsDeletedInternal(dialogId, mids, false, false); + updateDialogsWithDeletedMessagesInternal(dialogId, DialogObject.isChatDialog(dialogId) ? -dialogId : 0, mids, null); getFileLoader().deleteFiles(filesToDelete, 0); if (!mids.isEmpty()) { - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, mids, channelId, false)); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, mids, DialogObject.isChatDialog(dialogId) ? -dialogId : 0, false)); } } catch (Exception e) { FileLog.e(e); @@ -3045,12 +3531,21 @@ public class MessagesStorage extends BaseController { TLRPC.Document document = MessageObject.getDocument(message); TLRPC.Photo photo = MessageObject.getPhoto(message); if (MessageObject.isVoiceMessage(message)) { + if (document == null) { + return false; + } id = document.id; type = DownloadController.AUTODOWNLOAD_TYPE_AUDIO; } else if (MessageObject.isStickerMessage(message) || MessageObject.isAnimatedStickerMessage(message)) { + if (document == null) { + return false; + } id = document.id; type = DownloadController.AUTODOWNLOAD_TYPE_PHOTO; } else if (MessageObject.isVideoMessage(message) || MessageObject.isRoundVideoMessage(message) || MessageObject.isGifMessage(message)) { + if (document == null) { + return false; + } id = document.id; type = DownloadController.AUTODOWNLOAD_TYPE_VIDEO; } else if (document != null) { @@ -3100,7 +3595,7 @@ public class MessagesStorage extends BaseController { return false; } - public void deleteDialog(final long did, final int messagesOnly) { + public void deleteDialog(long did, int messagesOnly) { storageQueue.postRunnable(() -> { try { if (messagesOnly == 3) { @@ -3114,8 +3609,8 @@ public class MessagesStorage extends BaseController { return; } } - if ((int) did == 0 || messagesOnly == 2) { - SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages WHERE uid = " + did); + if (DialogObject.isEncryptedDialog(did) || messagesOnly == 2) { + SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + did); ArrayList filesToDelete = new ArrayList<>(); ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); @@ -3144,14 +3639,12 @@ public class MessagesStorage extends BaseController { database.executeFast("DELETE FROM chat_pinned_count WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM channel_users_v2 WHERE did = " + did).stepThis().dispose(); database.executeFast("DELETE FROM search_recent WHERE did = " + did).stepThis().dispose(); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - database.executeFast("DELETE FROM chat_settings_v2 WHERE uid = " + (-lower_id)).stepThis().dispose(); + if (!DialogObject.isEncryptedDialog(did)) { + if (DialogObject.isChatDialog(did)) { + database.executeFast("DELETE FROM chat_settings_v2 WHERE uid = " + (-did)).stepThis().dispose(); } } else { - database.executeFast("DELETE FROM enc_chats WHERE uid = " + high_id).stepThis().dispose(); + database.executeFast("DELETE FROM enc_chats WHERE uid = " + DialogObject.getEncryptedChatId(did)).stepThis().dispose(); } } else if (messagesOnly == 2) { SQLiteCursor cursor = database.queryFinalized("SELECT last_mid_i, last_mid FROM dialogs WHERE did = " + did); @@ -3159,7 +3652,7 @@ public class MessagesStorage extends BaseController { if (cursor.next()) { long last_mid_i = cursor.longValue(0); long last_mid = cursor.longValue(1); - SQLiteCursor cursor2 = database.queryFinalized("SELECT data FROM messages WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")"); + SQLiteCursor cursor2 = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")"); try { while (cursor2.next()) { NativeByteBuffer data = cursor2.byteBufferValue(0); @@ -3179,11 +3672,11 @@ public class MessagesStorage extends BaseController { } cursor2.dispose(); - database.executeFast("DELETE FROM messages WHERE uid = " + did + " AND mid != " + last_mid_i + " AND mid != " + last_mid).stepThis().dispose(); + database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did + " AND mid != " + last_mid_i + " AND mid != " + last_mid).stepThis().dispose(); database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM media_v2 WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM media_v3 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose(); getMediaDataController().clearBotKeyboard(did, null); @@ -3201,10 +3694,10 @@ public class MessagesStorage extends BaseController { } database.executeFast("UPDATE dialogs SET unread_count = 0, unread_count_i = 0 WHERE did = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM media_v2 WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM media_v3 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose(); getMediaDataController().clearBotKeyboard(did, null); @@ -3217,7 +3710,7 @@ public class MessagesStorage extends BaseController { }); } - public void onDeleteQueryComplete(final long did) { + public void onDeleteQueryComplete(long did) { storageQueue.postRunnable(() -> { try { database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose(); @@ -3227,18 +3720,18 @@ public class MessagesStorage extends BaseController { }); } - public void getDialogPhotos(final int did, final int count, final long max_id, final int classGuid) { + public void getDialogPhotos(long did, int count, int maxId, int classGuid) { storageQueue.postRunnable(() -> { try { SQLiteCursor cursor; - if (max_id != 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d AND id < %d ORDER BY rowid ASC LIMIT %d", did, max_id, count)); + if (maxId != 0) { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d AND id < %d ORDER BY rowid ASC LIMIT %d", did, maxId, count)); } else { cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM user_photos WHERE uid = %d ORDER BY rowid ASC LIMIT %d", did, count)); } - final TLRPC.photos_Photos res = new TLRPC.TL_photos_photos(); + TLRPC.photos_Photos res = new TLRPC.TL_photos_photos(); ArrayList messages = new ArrayList<>(); while (cursor.next()) { @@ -3256,42 +3749,42 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); - Utilities.stageQueue.postRunnable(() -> getMessagesController().processLoadedUserPhotos(res, messages, did, count, max_id, true, classGuid)); + Utilities.stageQueue.postRunnable(() -> getMessagesController().processLoadedUserPhotos(res, messages, did, count, maxId, true, classGuid)); } catch (Exception e) { FileLog.e(e); } }); } - public void clearUserPhotos(final int uid) { + public void clearUserPhotos(long dialogId) { storageQueue.postRunnable(() -> { try { - database.executeFast("DELETE FROM user_photos WHERE uid = " + uid).stepThis().dispose(); + database.executeFast("DELETE FROM user_photos WHERE uid = " + dialogId).stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } }); } - public void clearUserPhoto(final int uid, final long pid) { + public void clearUserPhoto(long dialogId, long pid) { storageQueue.postRunnable(() -> { try { - database.executeFast("DELETE FROM user_photos WHERE uid = " + uid + " AND id = " + pid).stepThis().dispose(); + database.executeFast("DELETE FROM user_photos WHERE uid = " + dialogId + " AND id = " + pid).stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } }); } - public void resetDialogs(final TLRPC.messages_Dialogs dialogsRes, final int messagesCount, final int seq, final int newPts, final int date, final int qts, final LongSparseArray new_dialogs_dict, final LongSparseArray new_dialogMessage, final TLRPC.Message lastMessage, final int dialogsCount) { + public void resetDialogs(TLRPC.messages_Dialogs dialogsRes, int messagesCount, int seq, int newPts, int date, int qts, LongSparseArray new_dialogs_dict, LongSparseArray new_dialogMessage, TLRPC.Message lastMessage, int dialogsCount) { storageQueue.postRunnable(() -> { try { int maxPinnedNum = 0; - ArrayList dids = new ArrayList<>(); + ArrayList dids = new ArrayList<>(); int totalPinnedCount = dialogsRes.dialogs.size() - dialogsCount; - final LongSparseArray oldPinnedDialogNums = new LongSparseArray<>(); + LongSparseIntArray oldPinnedDialogNums = new LongSparseIntArray(); ArrayList oldPinnedOrder = new ArrayList<>(); ArrayList orderArrayList = new ArrayList<>(); @@ -3304,9 +3797,8 @@ public class MessagesStorage extends BaseController { while (cursor.next()) { long did = cursor.longValue(0); int pinnedNum = cursor.intValue(1); - int lower_id = (int) did; - if (lower_id != 0) { - dids.add(lower_id); + if (!DialogObject.isEncryptedDialog(did)) { + dids.add(did); if (pinnedNum > 0) { maxPinnedNum = Math.max(pinnedNum, maxPinnedNum); oldPinnedDialogNums.put(did, pinnedNum); @@ -3315,8 +3807,8 @@ public class MessagesStorage extends BaseController { } } Collections.sort(oldPinnedOrder, (o1, o2) -> { - Integer val1 = oldPinnedDialogNums.get(o1); - Integer val2 = oldPinnedDialogNums.get(o2); + int val1 = oldPinnedDialogNums.get(o1); + int val2 = oldPinnedDialogNums.get(o2); if (val1 < val2) { return 1; } else if (val1 > val2) { @@ -3334,10 +3826,10 @@ public class MessagesStorage extends BaseController { database.executeFast("DELETE FROM chat_pinned_count WHERE uid IN " + ids).stepThis().dispose(); database.executeFast("DELETE FROM chat_pinned_v2 WHERE uid IN " + ids).stepThis().dispose(); database.executeFast("DELETE FROM dialogs WHERE did IN " + ids).stepThis().dispose(); - database.executeFast("DELETE FROM messages WHERE uid IN " + ids).stepThis().dispose(); - database.executeFast("DELETE FROM polls WHERE 1").stepThis().dispose(); + database.executeFast("DELETE FROM messages_v2 WHERE uid IN " + ids).stepThis().dispose(); + database.executeFast("DELETE FROM polls_v2 WHERE 1").stepThis().dispose(); database.executeFast("DELETE FROM bot_keyboard WHERE uid IN " + ids).stepThis().dispose(); - database.executeFast("DELETE FROM media_v2 WHERE uid IN " + ids).stepThis().dispose(); + database.executeFast("DELETE FROM media_v3 WHERE uid IN " + ids).stepThis().dispose(); database.executeFast("DELETE FROM messages_holes WHERE uid IN " + ids).stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid IN " + ids).stepThis().dispose(); database.commitTransaction(); @@ -3351,14 +3843,14 @@ public class MessagesStorage extends BaseController { int newIdx = orderArrayList.indexOf(dialog.id); if (oldIdx != -1 && newIdx != -1) { if (oldIdx == newIdx) { - Integer oldNum = oldPinnedDialogNums.get(dialog.id); - if (oldNum != null) { + int oldNum = oldPinnedDialogNums.get(dialog.id, -1); + if (oldNum != -1) { dialog.pinnedNum = oldNum; } } else { long oldDid = oldPinnedOrder.get(newIdx); - Integer oldNum = oldPinnedDialogNums.get(oldDid); - if (oldNum != null) { + int oldNum = oldPinnedDialogNums.get(oldDid, -1); + if (oldNum != -1) { dialog.pinnedNum = oldNum; } } @@ -3372,12 +3864,11 @@ public class MessagesStorage extends BaseController { saveDiffParamsInternal(seq, newPts, date, qts); int totalDialogsLoadCount = getUserConfig().getTotalDialogsCount(0); - int[] dialogsLoadOffset = getUserConfig().getDialogLoadOffsets(0); int dialogsLoadOffsetId; int dialogsLoadOffsetDate; - int dialogsLoadOffsetChannelId = 0; - int dialogsLoadOffsetChatId = 0; - int dialogsLoadOffsetUserId = 0; + long dialogsLoadOffsetChannelId = 0; + long dialogsLoadOffsetChatId = 0; + long dialogsLoadOffsetUserId = 0; long dialogsLoadOffsetAccess = 0; totalDialogsLoadCount += dialogsRes.dialogs.size(); @@ -3436,7 +3927,7 @@ public class MessagesStorage extends BaseController { }); } - public void putDialogPhotos(int did, TLRPC.photos_Photos photos, ArrayList messages) { + public void putDialogPhotos(long did, TLRPC.photos_Photos photos, ArrayList messages) { if (photos == null) { return; } @@ -3459,7 +3950,7 @@ public class MessagesStorage extends BaseController { if (messages != null) { messages.get(a).serializeToStream(data); } - state.bindInteger(1, did); + state.bindLong(1, did); state.bindLong(2, photo.id); state.bindByteBuffer(3, data); state.step(); @@ -3472,14 +3963,14 @@ public class MessagesStorage extends BaseController { }); } - public void emptyMessagesMedia(final ArrayList mids) { + public void emptyMessagesMedia(long dialogId, ArrayList mids) { storageQueue.postRunnable(() -> { try { ArrayList filesToDelete = new ArrayList<>(); ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); - final ArrayList messages = new ArrayList<>(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages WHERE mid IN (%s)", TextUtils.join(",", mids))); + ArrayList messages = new ArrayList<>(); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages_v2 WHERE mid IN (%s) AND uid = %d", TextUtils.join(",", mids), dialogId)); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -3507,7 +3998,7 @@ public class MessagesStorage extends BaseController { cursor.dispose(); deleteFromDownloadQueue(idsToDelete, true); if (!messages.isEmpty()) { - SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)"); + SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)"); for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); @@ -3515,7 +4006,7 @@ public class MessagesStorage extends BaseController { message.serializeToStream(data); state.requery(); - state.bindLong(1, message.id); + state.bindInteger(1, message.id); state.bindLong(2, message.dialog_id); state.bindInteger(3, MessageObject.getUnreadFlags(message)); state.bindInteger(4, message.send_state); @@ -3550,6 +4041,7 @@ public class MessagesStorage extends BaseController { } else { state.bindInteger(14, 0); } + state.bindLong(15, MessageObject.getChannelId(message)); state.step(); data.reuse(); @@ -3575,51 +4067,62 @@ public class MessagesStorage extends BaseController { public void updateMessagePollResults(long pollId, TLRPC.Poll poll, TLRPC.PollResults results) { storageQueue.postRunnable(() -> { try { - ArrayList mids = null; - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM polls WHERE id = %d", pollId)); + LongSparseArray> dialogs = null; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, mid FROM polls_v2 WHERE id = %d", pollId)); while (cursor.next()) { + long dialogId = cursor.longValue(0); + if (dialogs == null) { + dialogs = new LongSparseArray<>(); + } + ArrayList mids = dialogs.get(dialogId); if (mids == null) { mids = new ArrayList<>(); + dialogs.put(dialogId, mids); } - mids.add(cursor.longValue(0)); + mids.add(cursor.intValue(1)); } cursor.dispose(); - if (mids != null) { + if (dialogs != null) { database.beginTransaction(); - for (int a = 0, N = mids.size(); a < N; a++) { - Long mid = mids.get(a); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages WHERE mid = %d", mid)); - if (cursor.next()) { - NativeByteBuffer data = cursor.byteBufferValue(0); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - if (message.media instanceof TLRPC.TL_messageMediaPoll) { - TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) message.media; - if (poll != null) { - media.poll = poll; - } - if (results != null) { - MessageObject.updatePollResults(media, results); - } - - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET data = ? WHERE mid = ?"); - data = new NativeByteBuffer(message.getObjectSize()); - message.serializeToStream(data); - state.requery(); - state.bindByteBuffer(1, data); - state.bindLong(2, mid); - state.step(); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET data = ? WHERE mid = ? AND uid = ?"); + for (int b = 0, N2 = dialogs.size(); b < N2; b++) { + long dialogId = dialogs.keyAt(b); + ArrayList mids = dialogs.valueAt(b); + for (int a = 0, N = mids.size(); a < N; a++) { + Integer mid = mids.get(a); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, dialogId)); + if (cursor.next()) { + NativeByteBuffer data = cursor.byteBufferValue(0); + if (data != null) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + message.readAttachPath(data, getUserConfig().clientUserId); data.reuse(); - state.dispose(); + if (message.media instanceof TLRPC.TL_messageMediaPoll) { + TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) message.media; + if (poll != null) { + media.poll = poll; + } + if (results != null) { + MessageObject.updatePollResults(media, results); + } + + data = new NativeByteBuffer(message.getObjectSize()); + message.serializeToStream(data); + state.requery(); + state.bindByteBuffer(1, data); + state.bindInteger(2, mid); + state.bindLong(3, dialogId); + state.step(); + data.reuse(); + } } + } else { + database.executeFast(String.format(Locale.US, "DELETE FROM polls_v2 WHERE mid = %d AND uid = %d", mid, dialogId)).stepThis().dispose(); } - } else { - database.executeFast(String.format(Locale.US, "DELETE FROM polls WHERE mid = %d", mid)).stepThis().dispose(); + cursor.dispose(); } - cursor.dispose(); } + state.dispose(); database.commitTransaction(); } } catch (Exception e) { @@ -3628,15 +4131,11 @@ public class MessagesStorage extends BaseController { }); } - public void updateMessageReactions(long dialogId, int msgId, int channelId, TLRPC.TL_messageReactions reactions) { + public void updateMessageReactions(long dialogId, int msgId, TLRPC.TL_messageReactions reactions) { storageQueue.postRunnable(() -> { try { database.beginTransaction(); - long mid = msgId; - if (channelId != 0) { - mid |= ((long) channelId) << 32; - } - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages WHERE mid = %d", mid)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages_v2 WHERE mid = %d AND uid = %d", msgId, dialogId)); if (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -3645,12 +4144,13 @@ public class MessagesStorage extends BaseController { message.readAttachPath(data, getUserConfig().clientUserId); data.reuse(); MessageObject.updateReactions(message, reactions); - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET data = ? WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET data = ? WHERE mid = ? AND uid = ?"); NativeByteBuffer data2 = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data2); state.requery(); state.bindByteBuffer(1, data2); - state.bindLong(2, mid); + state.bindInteger(2, msgId); + state.bindLong(3, dialogId); state.step(); data2.reuse(); state.dispose(); @@ -3667,83 +4167,65 @@ public class MessagesStorage extends BaseController { }); } - public void getNewTask(final ArrayList oldTask, final int channelId, boolean isMediaTask) { + public void getNewTask(LongSparseArray> oldTask, LongSparseArray> oldTaskMedia) { storageQueue.postRunnable(() -> { try { if (oldTask != null) { - String ids; - if (channelId != 0) { - StringBuilder builder = new StringBuilder(); - for (int a = 0, N = oldTask.size(); a < N; a++) { - long messageId = oldTask.get(a); - messageId |= ((long) channelId) << 32; - if (builder.length() > 0) { - builder.append(","); - } - builder.append(messageId); - } - ids = builder.toString(); - } else { - ids = TextUtils.join(",", oldTask); + for (int a = 0, N = oldTask.size(); a < N; a++) { + database.executeFast(String.format(Locale.US, "DELETE FROM enc_tasks_v4 WHERE mid IN(%s) AND uid = %d AND media = 0", TextUtils.join(",", oldTask.valueAt(a)), oldTask.keyAt(a))).stepThis().dispose(); } - if (isMediaTask) { - database.executeFast(String.format(Locale.US, "DELETE FROM enc_tasks_v3 WHERE mid IN(%s) AND media = 1", ids)).stepThis().dispose(); - } else { - database.executeFast(String.format(Locale.US, "DELETE FROM enc_tasks_v3 WHERE mid IN(%s) AND media = 0", ids)).stepThis().dispose(); + } + if (oldTaskMedia != null) { + for (int a = 0, N = oldTaskMedia.size(); a < N; a++) { + database.executeFast(String.format(Locale.US, "DELETE FROM enc_tasks_v4 WHERE mid IN(%s) AND uid = %d AND media = 1", TextUtils.join(",", oldTaskMedia.valueAt(a)), oldTaskMedia.keyAt(a))).stepThis().dispose(); } } int date = 0; - int channelId1 = -1; - Boolean media = null; - ArrayList arr = null; - SQLiteCursor cursor = database.queryFinalized("SELECT mid, date, media FROM enc_tasks_v3 WHERE date = (SELECT min(date) FROM enc_tasks_v3)"); + LongSparseArray> newTask = null; + LongSparseArray> newTaskMedia = null; + SQLiteCursor cursor = database.queryFinalized("SELECT mid, date, media, uid FROM enc_tasks_v4 WHERE date = (SELECT min(date) FROM enc_tasks_v4)"); while (cursor.next()) { - long mid = cursor.longValue(0); - if (channelId1 == -1) { - channelId1 = (int) (mid >> 32); - if (channelId1 < 0) { - channelId1 = 0; - } - } + int mid = cursor.intValue(0); date = cursor.intValue(1); + int isMedia = cursor.intValue(2); + long uid = cursor.longValue(3); + boolean media; + if (isMedia == -1) { + media = mid > 0; + } else { + media = isMedia != 0; + } + LongSparseArray> task; + if (media) { + if (newTaskMedia == null) { + newTaskMedia = new LongSparseArray<>(); + } + task = newTaskMedia; + } else { + if (newTask == null) { + newTask = new LongSparseArray<>(); + } + task = newTask; + } + ArrayList arr = task.get(uid); if (arr == null) { arr = new ArrayList<>(); + task.put(uid, arr); } - int m = (int) mid; - boolean newMedia; - int isMedia = cursor.intValue(2); - if (isMedia == -1) { - newMedia = m > 0; - } else { - newMedia = isMedia != 0; - } - if (media == null) { - media = newMedia; - } else if (media != newMedia) { - continue; - } - arr.add(m); + arr.add(mid); } cursor.dispose(); - if (media == null) { - media = false; - } - getMessagesController().processLoadedDeleteTask(date, arr, media, channelId1); + getMessagesController().processLoadedDeleteTask(date, newTask, newTaskMedia); } catch (Exception e) { FileLog.e(e); } }); } - public void markMentionMessageAsRead(final int messageId, final int channelId, final long did) { + public void markMentionMessageAsRead(long dialogId, int messageId, long did) { storageQueue.postRunnable(() -> { try { - long mid = messageId; - if (channelId != 0) { - mid |= ((long) channelId) << 32; - } - - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 2 WHERE mid = %d", mid)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = read_state | 2 WHERE mid = %d AND uid = %d", messageId, dialogId)).stepThis().dispose(); SQLiteCursor cursor = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + did); int old_mentions_count = 0; @@ -3752,7 +4234,7 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); database.executeFast(String.format(Locale.US, "UPDATE dialogs SET unread_count_i = %d WHERE did = %d", old_mentions_count, did)).stepThis().dispose(); - LongSparseArray sparseArray = new LongSparseArray<>(1); + LongSparseIntArray sparseArray = new LongSparseIntArray(1); sparseArray.put(did, old_mentions_count); if (old_mentions_count == 0) { updateFiltersReadCounter(null, sparseArray, true); @@ -3764,17 +4246,17 @@ public class MessagesStorage extends BaseController { }); } - public void markMessageAsMention(final long mid) { + public void markMessageAsMention(long dialogId, int mid) { storageQueue.postRunnable(() -> { try { - database.executeFast(String.format(Locale.US, "UPDATE messages SET mention = 1, read_state = read_state & ~2 WHERE mid = %d", mid)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET mention = 1, read_state = read_state & ~2 WHERE mid = %d AND uid = %d", mid, dialogId)).stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } }); } - public void resetMentionsCount(final long did, final int count) { + public void resetMentionsCount(long did, int count) { storageQueue.postRunnable(() -> { try { int prevUnreadCount = 0; @@ -3785,10 +4267,10 @@ public class MessagesStorage extends BaseController { cursor.dispose(); if (prevUnreadCount != 0 || count != 0) { if (count == 0) { - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 2 WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", did)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = read_state | 2 WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", did)).stepThis().dispose(); } database.executeFast(String.format(Locale.US, "UPDATE dialogs SET unread_count_i = %d WHERE did = %d", count, did)).stepThis().dispose(); - LongSparseArray sparseArray = new LongSparseArray<>(1); + LongSparseIntArray sparseArray = new LongSparseIntArray(1); sparseArray.put(did, count); getMessagesController().processDialogsUpdateRead(null, sparseArray); if (count == 0) { @@ -3801,65 +4283,63 @@ public class MessagesStorage extends BaseController { }); } - public void createTaskForMid(final int messageId, final int channelId, final int time, final int readTime, final int ttl, final boolean inner) { + public void createTaskForMid(long dialogId, int messageId, int time, int readTime, int ttl, boolean inner) { storageQueue.postRunnable(() -> { try { int minDate = Math.max(time, readTime) + ttl; - SparseArray> messages = new SparseArray<>(); - final ArrayList midsArray = new ArrayList<>(); + SparseArray> messages = new SparseArray<>(); + ArrayList midsArray = new ArrayList<>(); - long mid = messageId; - if (channelId != 0) { - mid |= ((long) channelId) << 32; - } - midsArray.add(mid); + midsArray.add(messageId); messages.put(minDate, midsArray); AndroidUtilities.runOnUIThread(() -> { if (!inner) { - markMessagesContentAsRead(midsArray, 0); + markMessagesContentAsRead(dialogId, midsArray, 0); } - getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, midsArray); + getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, dialogId, midsArray); }); - SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)"); + SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); for (int a = 0; a < messages.size(); a++) { int key = messages.keyAt(a); - ArrayList arr = messages.get(key); + ArrayList arr = messages.get(key); for (int b = 0; b < arr.size(); b++) { state.requery(); - state.bindLong(1, arr.get(b)); - state.bindInteger(2, key); - state.bindInteger(3, 1); + state.bindInteger(1, arr.get(b)); + state.bindLong(2, dialogId); + state.bindInteger(3, key); + state.bindInteger(4, 1); state.step(); } } state.dispose(); - database.executeFast(String.format(Locale.US, "UPDATE messages SET ttl = 0 WHERE mid = %d", mid)).stepThis().dispose(); - getMessagesController().didAddedNewTask(minDate, messages); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET ttl = 0 WHERE mid = %d AND uid = %d", messageId, dialogId)).stepThis().dispose(); + getMessagesController().didAddedNewTask(minDate, dialogId, messages); } catch (Exception e) { FileLog.e(e); } }); } - public void createTaskForSecretChat(final int chatId, final int time, final int readTime, final int isOut, final ArrayList random_ids) { + public void createTaskForSecretChat(int chatId, int time, int readTime, int isOut, ArrayList random_ids) { storageQueue.postRunnable(() -> { try { + long dialogId = DialogObject.makeEncryptedDialogId(chatId); int minDate = Integer.MAX_VALUE; - SparseArray> messages = new SparseArray<>(); - final ArrayList midsArray = new ArrayList<>(); + SparseArray> messages = new SparseArray<>(); + ArrayList midsArray = new ArrayList<>(); StringBuilder mids = new StringBuilder(); SQLiteCursor cursor; if (random_ids == null) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE uid = %d AND out = %d AND read_state > 0 AND ttl > 0 AND date <= %d AND send_state = 0 AND media != 1", ((long) chatId) << 32, isOut, time)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages_v2 WHERE uid = %d AND out = %d AND read_state > 0 AND ttl > 0 AND date <= %d AND send_state = 0 AND media != 1", dialogId, isOut, time)); } else { String ids = TextUtils.join(",", random_ids); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.mid, m.ttl FROM messages as m INNER JOIN randoms as r ON m.mid = r.mid WHERE r.random_id IN (%s)", ids)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.mid, m.ttl FROM messages_v2 as m INNER JOIN randoms_v2 as r ON m.mid = r.mid AND m.uid = r.uid WHERE r.random_id IN (%s)", ids)); } while (cursor.next()) { int ttl = cursor.intValue(1); - long mid = cursor.intValue(0); + int mid = cursor.intValue(0); if (random_ids != null) { midsArray.add(mid); } @@ -3868,7 +4348,7 @@ public class MessagesStorage extends BaseController { } int date = Math.max(time, readTime) + ttl; minDate = Math.min(minDate, date); - ArrayList arr = messages.get(date); + ArrayList arr = messages.get(date); if (arr == null) { arr = new ArrayList<>(); messages.put(date, arr); @@ -3883,29 +4363,30 @@ public class MessagesStorage extends BaseController { if (random_ids != null) { AndroidUtilities.runOnUIThread(() -> { - markMessagesContentAsRead(midsArray, 0); - getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, midsArray); + markMessagesContentAsRead(dialogId, midsArray, 0); + getNotificationCenter().postNotificationName(NotificationCenter.messagesReadContent, dialogId, midsArray); }); } if (messages.size() != 0) { database.beginTransaction(); - SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)"); + SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); for (int a = 0; a < messages.size(); a++) { int key = messages.keyAt(a); - ArrayList arr = messages.get(key); + ArrayList arr = messages.get(key); for (int b = 0; b < arr.size(); b++) { state.requery(); - state.bindLong(1, arr.get(b)); - state.bindInteger(2, key); - state.bindInteger(3, 0); + state.bindInteger(1, arr.get(b)); + state.bindLong(2, dialogId); + state.bindInteger(3, key); + state.bindInteger(4, 0); state.step(); } } state.dispose(); database.commitTransaction(); - database.executeFast(String.format(Locale.US, "UPDATE messages SET ttl = 0 WHERE mid IN(%s)", mids.toString())).stepThis().dispose(); - getMessagesController().didAddedNewTask(minDate, messages); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET ttl = 0 WHERE mid IN(%s) AND uid = %d", mids.toString(), dialogId)).stepThis().dispose(); + getMessagesController().didAddedNewTask(minDate, dialogId, messages); } } catch (Exception e) { FileLog.e(e); @@ -3913,7 +4394,7 @@ public class MessagesStorage extends BaseController { }); } - private void updateFiltersReadCounter(LongSparseArray dialogsToUpdate, LongSparseArray dialogsToUpdateMentions, boolean read) throws Exception { + private void updateFiltersReadCounter(LongSparseIntArray dialogsToUpdate, LongSparseIntArray dialogsToUpdateMentions, boolean read) throws Exception { if ((dialogsToUpdate == null || dialogsToUpdate.size() == 0) && (dialogsToUpdateMentions == null || dialogsToUpdateMentions.size() == 0)) { return; } @@ -3924,17 +4405,17 @@ public class MessagesStorage extends BaseController { mentionChannels[a] = mentionGroups[a] = 0; } - final ArrayList users = new ArrayList<>(); - final ArrayList encUsers = new ArrayList<>(); - final ArrayList chats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList users = new ArrayList<>(); + ArrayList encUsers = new ArrayList<>(); + ArrayList chats = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); LongSparseArray dialogsByFolders = new LongSparseArray<>(); LongSparseArray newUnreadDialogs = new LongSparseArray<>(); for (int b = 0; b < 2; b++) { - LongSparseArray array = b == 0 ? dialogsToUpdate : dialogsToUpdateMentions; + LongSparseIntArray array = b == 0 ? dialogsToUpdate : dialogsToUpdateMentions; if (array == null) { continue; } @@ -3983,31 +4464,28 @@ public class MessagesStorage extends BaseController { dialogsByFolders.put(did, folderId); } - int lowerId = (int) did; - int highId = (int) (did >> 32); - if (lowerId != 0) { - if (lowerId < 0) { - if (!chatsToLoad.contains(-lowerId)) { - chatsToLoad.add(-lowerId); - } - } else { - if (!usersToLoad.contains(lowerId)) { - usersToLoad.add(lowerId); - } + if (DialogObject.isEncryptedDialog(did)) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(did)) { + if (!usersToLoad.contains(did)) { + usersToLoad.add(did); } } else { - if (!encryptedToLoad.contains(highId)) { - encryptedToLoad.add(highId); + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } } } } - SparseArray usersDict = new SparseArray<>(); - SparseArray chatsDict = new SparseArray<>(); - SparseArray encUsersDict = new SparseArray<>(); - SparseArray encryptedChatsByUsersCount = new SparseArray<>(); - SparseArray mutedDialogs = new SparseArray<>(); - SparseArray archivedDialogs = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); + LongSparseArray chatsDict = new LongSparseArray<>(); + LongSparseArray encUsersDict = new LongSparseArray<>(); + LongSparseArray encryptedChatsByUsersCount = new LongSparseArray<>(); + LongSparseArray mutedDialogs = new LongSparseArray<>(); + LongSparseArray archivedDialogs = new LongSparseArray<>(); if (!usersToLoad.isEmpty()) { getUsersInternal(TextUtils.join(",", usersToLoad), users); for (int a = 0, N = users.size(); a < N; a++) { @@ -4032,7 +4510,7 @@ public class MessagesStorage extends BaseController { } } if (!encryptedToLoad.isEmpty()) { - ArrayList encUsersToLoad = new ArrayList<>(); + ArrayList encUsersToLoad = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, encUsersToLoad); if (!encUsersToLoad.isEmpty()) { @@ -4047,7 +4525,7 @@ public class MessagesStorage extends BaseController { if (user == null) { continue; } - long did = ((long) encryptedChat.id) << 32; + long did = DialogObject.makeEncryptedDialogId(encryptedChat.id); boolean muted = getMessagesController().isDialogMuted(did); int idx1 = dialogsByFolders.get(did); int idx2 = muted ? 1 : 0; @@ -4218,10 +4696,10 @@ public class MessagesStorage extends BaseController { } if (filter != null) { for (int b = 0, N2 = filter.alwaysShow.size(); b < N2; b++) { - int did = filter.alwaysShow.get(b); - if (did > 0) { + long did = filter.alwaysShow.get(b); + if (DialogObject.isUserDialog(did)) { for (int i = 0; i < 2; i++) { - SparseArray dict = i == 0 ? usersDict : encUsersDict; + LongSparseArray dict = i == 0 ? usersDict : encUsersDict; TLRPC.User user = dict.get(did); if (user != null) { int count; @@ -4270,13 +4748,13 @@ public class MessagesStorage extends BaseController { } } for (int b = 0, N2 = filter.neverShow.size(); b < N2; b++) { - int did = filter.neverShow.get(b); + long did = filter.neverShow.get(b); if (dialogsToUpdateMentions != null && dialogsToUpdateMentions.indexOfKey(did) >= 0 && mutedDialogs.indexOfKey(did) < 0) { continue; } - if (did > 0) { + if (DialogObject.isUserDialog(did)) { for (int i = 0; i < 2; i++) { - SparseArray dict = i == 0 ? usersDict : encUsersDict; + LongSparseArray dict = i == 0 ? usersDict : encUsersDict; TLRPC.User user = dict.get(did); if (user != null) { int count; @@ -4409,7 +4887,7 @@ public class MessagesStorage extends BaseController { if (!filter.alwaysShow.isEmpty()) { if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0) { for (int b = 0, N2 = dialogsToUpdateMentions.size(); b < N2; b++) { - int did = (int) dialogsToUpdateMentions.keyAt(b); + long did = dialogsToUpdateMentions.keyAt(b); TLRPC.Chat chat = chatsDict.get(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { if ((flags & MessagesController.DIALOG_FILTER_FLAG_CHANNELS) == 0) { @@ -4426,11 +4904,11 @@ public class MessagesStorage extends BaseController { } } for (int b = 0, N2 = filter.alwaysShow.size(); b < N2; b++) { - int did = filter.alwaysShow.get(b); + long did = filter.alwaysShow.get(b); if (newUnreadDialogs.indexOfKey(did) < 0) { continue; } - if (did > 0) { + if (DialogObject.isUserDialog(did)) { TLRPC.User user = usersDict.get(did); if (user != null) { if ((flags & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED) != 0 && mutedDialogs.indexOfKey(user.id) >= 0) { @@ -4493,8 +4971,8 @@ public class MessagesStorage extends BaseController { } } for (int b = 0, N2 = filter.neverShow.size(); b < N2; b++) { - int did = filter.neverShow.get(b); - if (did > 0) { + long did = filter.neverShow.get(b); + if (DialogObject.isUserDialog(did)) { TLRPC.User user = usersDict.get(did); if (user != null) { unreadCount--; @@ -4533,15 +5011,15 @@ public class MessagesStorage extends BaseController { }); } - private void updateDialogsWithReadMessagesInternal(final ArrayList messages, final SparseLongArray inbox, SparseLongArray outbox, final ArrayList mentions) { + private void updateDialogsWithReadMessagesInternal(ArrayList messages, LongSparseIntArray inbox, LongSparseIntArray outbox, LongSparseArray> mentions) { try { - LongSparseArray dialogsToUpdate = new LongSparseArray<>(); - LongSparseArray dialogsToUpdateMentions = new LongSparseArray<>(); - ArrayList channelMentionsToReload = new ArrayList<>(); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(); + LongSparseIntArray dialogsToUpdateMentions = new LongSparseIntArray(); + ArrayList channelMentionsToReload = new ArrayList<>(); if (!isEmpty(messages)) { String ids = TextUtils.join(",", messages); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state, out FROM messages WHERE mid IN(%s)", ids)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state, out FROM messages_v2 WHERE mid IN(%s) AND is_channel = 0", ids)); while (cursor.next()) { int out = cursor.intValue(2); if (out != 0) { @@ -4552,8 +5030,8 @@ public class MessagesStorage extends BaseController { continue; } long uid = cursor.longValue(0); - Integer currentCount = dialogsToUpdate.get(uid); - if (currentCount == null) { + int currentCount = dialogsToUpdate.get(uid); + if (currentCount == 0) { dialogsToUpdate.put(uid, 1); } else { dialogsToUpdate.put(uid, currentCount + 1); @@ -4563,9 +5041,9 @@ public class MessagesStorage extends BaseController { } else { if (!isEmpty(inbox)) { for (int b = 0; b < inbox.size(); b++) { - int key = inbox.keyAt(b); - long messageId = inbox.get(key); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages WHERE uid = %d AND mid > %d AND read_state IN(0,2) AND out = 0", key, messageId)); + long key = inbox.keyAt(b); + int messageId = inbox.get(key); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages_v2 WHERE uid = %d AND mid > %d AND read_state IN(0,2) AND out = 0", key, messageId)); if (cursor.next()) { dialogsToUpdate.put(key, cursor.intValue(0)); } @@ -4574,50 +5052,54 @@ public class MessagesStorage extends BaseController { SQLitePreparedStatement state = database.executeFast("UPDATE dialogs SET inbox_max = max((SELECT inbox_max FROM dialogs WHERE did = ?), ?) WHERE did = ?"); state.requery(); state.bindLong(1, key); - state.bindInteger(2, (int) messageId); + state.bindInteger(2, messageId); state.bindLong(3, key); state.step(); state.dispose(); } } if (!isEmpty(mentions)) { - ArrayList notFoundMentions = new ArrayList<>(mentions); - String ids = TextUtils.join(",", mentions); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state, out, mention, mid FROM messages WHERE mid IN(%s)", ids)); - while (cursor.next()) { - long did = cursor.longValue(0); - notFoundMentions.remove(cursor.longValue(4)); - if (cursor.intValue(1) < 2 && cursor.intValue(2) == 0 && cursor.intValue(3) == 1) { - Integer unread_count = dialogsToUpdateMentions.get(did); - if (unread_count == null) { - SQLiteCursor cursor2 = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + did); - int old_mentions_count = 0; - if (cursor2.next()) { - old_mentions_count = cursor2.intValue(0); + for (int b = 0, N = mentions.size(); b < N; b++) { + ArrayList arrayList = mentions.valueAt(b); + ArrayList notFoundMentions = new ArrayList<>(arrayList); + String ids = TextUtils.join(",", arrayList); + long channelId = 0; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state, out, mention, mid, is_channel FROM messages_v2 WHERE mid IN(%s)", ids)); + while (cursor.next()) { + long did = cursor.longValue(0); + notFoundMentions.remove((Integer) cursor.intValue(4)); + if (cursor.intValue(1) < 2 && cursor.intValue(2) == 0 && cursor.intValue(3) == 1) { + int unread_count = dialogsToUpdateMentions.get(did, -1); + if (unread_count < 0) { + SQLiteCursor cursor2 = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + did); + int old_mentions_count = 0; + if (cursor2.next()) { + old_mentions_count = cursor2.intValue(0); + } + cursor2.dispose(); + dialogsToUpdateMentions.put(did, Math.max(0, old_mentions_count - 1)); + } else { + dialogsToUpdateMentions.put(did, Math.max(0, unread_count - 1)); } - cursor2.dispose(); - dialogsToUpdateMentions.put(did, Math.max(0, old_mentions_count - 1)); - } else { - dialogsToUpdateMentions.put(did, Math.max(0, unread_count - 1)); } + channelId = cursor.longValue(5); } - } - cursor.dispose(); - for (int a = 0; a < notFoundMentions.size(); a++) { - int channelId = (int) (notFoundMentions.get(a) >> 32); - if (channelId > 0 && !channelMentionsToReload.contains(channelId)) { - channelMentionsToReload.add(channelId); + cursor.dispose(); + if (!notFoundMentions.isEmpty() && channelId != 0) { + if (!channelMentionsToReload.contains(channelId)) { + channelMentionsToReload.add(channelId); + } } } } if (!isEmpty(outbox)) { for (int b = 0; b < outbox.size(); b++) { - int key = outbox.keyAt(b); - long messageId = outbox.get(key); + long key = outbox.keyAt(b); + int messageId = outbox.get(key); SQLitePreparedStatement state = database.executeFast("UPDATE dialogs SET outbox_max = max((SELECT outbox_max FROM dialogs WHERE did = ?), ?) WHERE did = ?"); state.requery(); state.bindLong(1, key); - state.bindInteger(2, (int) messageId); + state.bindInteger(2, messageId); state.bindLong(3, key); state.step(); state.dispose(); @@ -4681,7 +5163,7 @@ public class MessagesStorage extends BaseController { return array == null || array.size() == 0; } - private static boolean isEmpty(SparseLongArray array) { + private static boolean isEmpty(LongSparseIntArray array) { return array == null || array.size() == 0; } @@ -4697,7 +5179,7 @@ public class MessagesStorage extends BaseController { return array == null || array.size() == 0; } - public void updateDialogsWithReadMessages(final SparseLongArray inbox, final SparseLongArray outbox, final ArrayList mentions, boolean useQueue) { + public void updateDialogsWithReadMessages(LongSparseIntArray inbox, LongSparseIntArray outbox, LongSparseArray> mentions, boolean useQueue) { if (isEmpty(inbox) && isEmpty(outbox) && isEmpty(mentions)) { return; } @@ -4708,7 +5190,7 @@ public class MessagesStorage extends BaseController { } } - public void updateChatParticipants(final TLRPC.ChatParticipants participants) { + public void updateChatParticipants(TLRPC.ChatParticipants participants) { if (participants == null) { return; } @@ -4724,23 +5206,23 @@ public class MessagesStorage extends BaseController { data.reuse(); info.pinned_msg_id = cursor.intValue(1); info.online_count = cursor.intValue(2); - info.inviterId = cursor.intValue(3); + info.inviterId = cursor.longValue(3); } } cursor.dispose(); if (info instanceof TLRPC.TL_chatFull) { info.participants = participants; - final TLRPC.ChatFull finalInfo = info; + TLRPC.ChatFull finalInfo = info; AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, finalInfo, 0, false, false)); SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?, ?, ?, ?, ?)"); NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize()); info.serializeToStream(data); - state.bindInteger(1, info.id); + state.bindLong(1, info.id); state.bindByteBuffer(2, data); state.bindInteger(3, info.pinned_msg_id); state.bindInteger(4, info.online_count); - state.bindInteger(5, info.inviterId); + state.bindLong(5, info.inviterId); state.bindInteger(6, info.invitesCount); state.step(); state.dispose(); @@ -4752,18 +5234,18 @@ public class MessagesStorage extends BaseController { }); } - public void loadChannelAdmins(final int chatId) { + public void loadChannelAdmins(long chatId) { storageQueue.postRunnable(() -> { try { SQLiteCursor cursor = database.queryFinalized("SELECT uid, data FROM channel_admins_v3 WHERE did = " + chatId); - SparseArray ids = new SparseArray<>(); + LongSparseArray ids = new LongSparseArray<>(); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { TLRPC.ChannelParticipant participant = TLRPC.ChannelParticipant.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (participant != null) { - ids.put(cursor.intValue(0), participant); + ids.put(cursor.longValue(0), participant); } } } @@ -4775,7 +5257,7 @@ public class MessagesStorage extends BaseController { }); } - public void putChannelAdmins(final int chatId, final SparseArray ids) { + public void putChannelAdmins(long chatId, LongSparseArray ids) { storageQueue.postRunnable(() -> { try { database.executeFast("DELETE FROM channel_admins_v3 WHERE did = " + chatId).stepThis().dispose(); @@ -4785,8 +5267,8 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data; for (int a = 0; a < ids.size(); a++) { state.requery(); - state.bindInteger(1, chatId); - state.bindInteger(2, ids.keyAt(a)); + state.bindLong(1, chatId); + state.bindLong(2, ids.keyAt(a)); TLRPC.ChannelParticipant participant = ids.valueAt(a); data = new NativeByteBuffer(participant.getObjectSize()); participant.serializeToStream(data); @@ -4802,7 +5284,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateChannelUsers(final int channelId, final ArrayList participants) { + public void updateChannelUsers(long channelId, ArrayList participants) { storageQueue.postRunnable(() -> { try { long did = -channelId; @@ -4815,7 +5297,7 @@ public class MessagesStorage extends BaseController { TLRPC.ChannelParticipant participant = participants.get(a); state.requery(); state.bindLong(1, did); - state.bindInteger(2, MessageObject.getPeerId(participant.peer)); + state.bindLong(2, MessageObject.getPeerId(participant.peer)); state.bindInteger(3, date); data = new NativeByteBuffer(participant.getObjectSize()); participant.serializeToStream(data); @@ -4833,7 +5315,7 @@ public class MessagesStorage extends BaseController { }); } - public void saveBotCache(final String key, final TLObject result) { + public void saveBotCache(String key, TLObject result) { if (result == null || TextUtils.isEmpty(key)) { return; } @@ -4860,11 +5342,11 @@ public class MessagesStorage extends BaseController { }); } - public void getBotCache(final String key, final RequestDelegate requestDelegate) { + public void getBotCache(String key, RequestDelegate requestDelegate) { if (key == null || requestDelegate == null) { return; } - final int currentDate = getConnectionsManager().getCurrentTime(); + int currentDate = getConnectionsManager().getCurrentTime(); storageQueue.postRunnable(() -> { TLObject result = null; try { @@ -4895,7 +5377,7 @@ public class MessagesStorage extends BaseController { }); } - public void loadUserInfo(TLRPC.User user, final boolean force, int classGuid, int fromMessageId) { + public void loadUserInfo(TLRPC.User user, boolean force, int classGuid, int fromMessageId) { if (user == null) { return; } @@ -4957,7 +5439,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateUserInfo(final TLRPC.UserFull info, final boolean ifExist) { + public void updateUserInfo(TLRPC.UserFull info, boolean ifExist) { storageQueue.postRunnable(() -> { try { if (ifExist) { @@ -4971,7 +5453,7 @@ public class MessagesStorage extends BaseController { SQLitePreparedStatement state = database.executeFast("REPLACE INTO user_settings VALUES(?, ?, ?)"); NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize()); info.serializeToStream(data); - state.bindInteger(1, info.user.id); + state.bindLong(1, info.user.id); state.bindByteBuffer(2, data); state.bindInteger(3, info.pinned_msg_id); state.step(); @@ -4991,13 +5473,13 @@ public class MessagesStorage extends BaseController { }); } - public void saveChatInviter(int chatId, int inviterId) { + public void saveChatInviter(long chatId, long inviterId) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE chat_settings_v2 SET inviter = ? WHERE uid = ?"); state.requery(); - state.bindInteger(1, inviterId); - state.bindInteger(2, chatId); + state.bindLong(1, inviterId); + state.bindLong(2, chatId); state.step(); state.dispose(); } catch (Exception e) { @@ -5006,13 +5488,13 @@ public class MessagesStorage extends BaseController { }); } - public void saveChatLinksCount(int chatId, int linksCount) { + public void saveChatLinksCount(long chatId, int linksCount) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE chat_settings_v2 SET links = ? WHERE uid = ?"); state.requery(); state.bindInteger(1, linksCount); - state.bindInteger(2, chatId); + state.bindLong(2, chatId); state.step(); state.dispose(); } catch (Exception e) { @@ -5021,7 +5503,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateChatInfo(final TLRPC.ChatFull info, final boolean ifExist) { + public void updateChatInfo(TLRPC.ChatFull info, boolean ifExist) { storageQueue.postRunnable(() -> { try { int currentOnline = -1; @@ -5030,7 +5512,7 @@ public class MessagesStorage extends BaseController { SQLiteCursor cursor = database.queryFinalized("SELECT online, inviter, links FROM chat_settings_v2 WHERE uid = " + info.id); if (cursor.next()) { currentOnline = cursor.intValue(0); - info.inviterId = cursor.intValue(1); + info.inviterId = cursor.longValue(1); links = cursor.intValue(2); } cursor.dispose(); @@ -5049,11 +5531,11 @@ public class MessagesStorage extends BaseController { SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?, ?, ?, ?, ?)"); NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize()); info.serializeToStream(data); - state.bindInteger(1, info.id); + state.bindLong(1, info.id); state.bindByteBuffer(2, data); state.bindInteger(3, info.pinned_msg_id); state.bindInteger(4, info.online_count); - state.bindInteger(5, info.inviterId); + state.bindLong(5, info.inviterId); state.bindInteger(6, info.invitesCount); state.step(); state.dispose(); @@ -5091,13 +5573,13 @@ public class MessagesStorage extends BaseController { }); } - public void updateChatOnlineCount(final int channelId, final int onlineCount) { + public void updateChatOnlineCount(long channelId, int onlineCount) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE chat_settings_v2 SET online = ? WHERE uid = ?"); state.requery(); state.bindInteger(1, onlineCount); - state.bindInteger(2, channelId); + state.bindLong(2, channelId); state.step(); state.dispose(); } catch (Exception e) { @@ -5184,7 +5666,7 @@ public class MessagesStorage extends BaseController { boolean endReached; if (ids == null) { database.executeFast("DELETE FROM chat_pinned_v2 WHERE uid = " + dialogId).stepThis().dispose(); - if (dialogId < 0) { + if (DialogObject.isChatDialog(dialogId)) { database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d", -dialogId)).stepThis().dispose(); } else { database.executeFast(String.format(Locale.US, "UPDATE user_settings SET pinned = 0 WHERE uid = %d", dialogId)).stepThis().dispose(); @@ -5193,7 +5675,7 @@ public class MessagesStorage extends BaseController { endReached = true; } else { String idsStr = TextUtils.join(",", ids); - if (dialogId < 0) { + if (DialogObject.isChatDialog(dialogId)) { database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", -dialogId, idsStr)).stepThis().dispose(); } else { database.executeFast(String.format(Locale.US, "UPDATE user_settings SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", dialogId, idsStr)).stepThis().dispose(); @@ -5238,10 +5720,10 @@ public class MessagesStorage extends BaseController { }); } - public void updateChatInfo(final int chat_id, final int user_id, final int what, final int invited_id, final int version) { + public void updateChatInfo(long chatId, long userId, int what, long invited_id, int version) { storageQueue.postRunnable(() -> { try { - SQLiteCursor cursor = database.queryFinalized("SELECT info, pinned, online, inviter FROM chat_settings_v2 WHERE uid = " + chat_id); + SQLiteCursor cursor = database.queryFinalized("SELECT info, pinned, online, inviter FROM chat_settings_v2 WHERE uid = " + chatId); TLRPC.ChatFull info = null; ArrayList loadedUsers = new ArrayList<>(); if (cursor.next()) { @@ -5251,7 +5733,7 @@ public class MessagesStorage extends BaseController { data.reuse(); info.pinned_msg_id = cursor.intValue(1); info.online_count = cursor.intValue(2); - info.inviterId = cursor.intValue(3); + info.inviterId = cursor.longValue(3); } } cursor.dispose(); @@ -5259,26 +5741,26 @@ public class MessagesStorage extends BaseController { if (what == 1) { for (int a = 0; a < info.participants.participants.size(); a++) { TLRPC.ChatParticipant participant = info.participants.participants.get(a); - if (participant.user_id == user_id) { + if (participant.user_id == userId) { info.participants.participants.remove(a); break; } } } else if (what == 0) { for (TLRPC.ChatParticipant part : info.participants.participants) { - if (part.user_id == user_id) { + if (part.user_id == userId) { return; } } TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant(); - participant.user_id = user_id; + participant.user_id = userId; participant.inviter_id = invited_id; participant.date = getConnectionsManager().getCurrentTime(); info.participants.participants.add(participant); } else if (what == 2) { for (int a = 0; a < info.participants.participants.size(); a++) { TLRPC.ChatParticipant participant = info.participants.participants.get(a); - if (participant.user_id == user_id) { + if (participant.user_id == userId) { TLRPC.ChatParticipant newParticipant; if (invited_id == 1) { newParticipant = new TLRPC.TL_chatParticipantAdmin(); @@ -5295,17 +5777,17 @@ public class MessagesStorage extends BaseController { } info.participants.version = version; - final TLRPC.ChatFull finalInfo = info; + TLRPC.ChatFull finalInfo = info; AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.chatInfoDidLoad, finalInfo, 0, false, false)); SQLitePreparedStatement state = database.executeFast("REPLACE INTO chat_settings_v2 VALUES(?, ?, ?, ?, ?, ?)"); NativeByteBuffer data = new NativeByteBuffer(info.getObjectSize()); info.serializeToStream(data); - state.bindInteger(1, chat_id); + state.bindLong(1, chatId); state.bindByteBuffer(2, data); state.bindInteger(3, info.pinned_msg_id); state.bindInteger(4, info.online_count); - state.bindInteger(5, info.inviterId); + state.bindLong(5, info.inviterId); state.bindInteger(6, info.invitesCount); state.step(); state.dispose(); @@ -5317,12 +5799,12 @@ public class MessagesStorage extends BaseController { }); } - public boolean isMigratedChat(final int chat_id) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final boolean[] result = new boolean[1]; + public boolean isMigratedChat(long chatId) { + CountDownLatch countDownLatch = new CountDownLatch(1); + boolean[] result = new boolean[1]; storageQueue.postRunnable(() -> { try { - SQLiteCursor cursor = database.queryFinalized("SELECT info FROM chat_settings_v2 WHERE uid = " + chat_id); + SQLiteCursor cursor = database.queryFinalized("SELECT info FROM chat_settings_v2 WHERE uid = " + chatId); TLRPC.ChatFull info = null; ArrayList loadedUsers = new ArrayList<>(); if (cursor.next()) { @@ -5349,13 +5831,13 @@ public class MessagesStorage extends BaseController { return result[0]; } - public boolean hasInviteMeMessage(final int chat_id) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final boolean[] result = new boolean[1]; + public boolean hasInviteMeMessage(long chatId) { + CountDownLatch countDownLatch = new CountDownLatch(1); + boolean[] result = new boolean[1]; storageQueue.postRunnable(() -> { try { - int selfId = getUserConfig().getClientUserId(); - SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages WHERE uid = " + -chat_id + " AND out = 0 ORDER BY mid DESC LIMIT 100"); + long selfId = getUserConfig().getClientUserId(); + SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + -chatId + " AND out = 0 ORDER BY mid DESC LIMIT 100"); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -5382,7 +5864,7 @@ public class MessagesStorage extends BaseController { return result[0]; } - private TLRPC.ChatFull loadChatInfoInternal(final int chatId, boolean isChannel, final boolean force, final boolean byChannelUsers, int fromMessageId) { + private TLRPC.ChatFull loadChatInfoInternal(long chatId, boolean isChannel, boolean force, boolean byChannelUsers, int fromMessageId) { TLRPC.ChatFull info = null; ArrayList loadedUsers = new ArrayList<>(); @@ -5400,7 +5882,7 @@ public class MessagesStorage extends BaseController { data.reuse(); info.pinned_msg_id = cursor.intValue(1); info.online_count = cursor.intValue(2); - info.inviterId = cursor.intValue(3); + info.inviterId = cursor.longValue(3); info.invitesCount = cursor.intValue(4); } } @@ -5508,11 +5990,11 @@ public class MessagesStorage extends BaseController { return info; } - public TLRPC.ChatFull loadChatInfo(int chatId, boolean isChannel, CountDownLatch countDownLatch, boolean force, boolean byChannelUsers) { + public TLRPC.ChatFull loadChatInfo(long chatId, boolean isChannel, CountDownLatch countDownLatch, boolean force, boolean byChannelUsers) { return loadChatInfo(chatId, isChannel, countDownLatch, force, byChannelUsers, 0); } - public TLRPC.ChatFull loadChatInfo(int chatId, boolean isChannel, CountDownLatch countDownLatch, boolean force, boolean byChannelUsers, int fromMessageId) { + public TLRPC.ChatFull loadChatInfo(long chatId, boolean isChannel, CountDownLatch countDownLatch, boolean force, boolean byChannelUsers, int fromMessageId) { TLRPC.ChatFull[] result = new TLRPC.ChatFull[1]; storageQueue.postRunnable(() -> { result[0] = loadChatInfoInternal(chatId, isChannel, force, byChannelUsers, fromMessageId); @@ -5530,15 +6012,15 @@ public class MessagesStorage extends BaseController { return result[0]; } - public void processPendingRead(final long dialog_id, final long maxPositiveId, final long maxNegativeId, final boolean isChannel, final int scheduledCount) { - final int maxDate = lastSavedDate; + public void processPendingRead(long dialogId, int maxPositiveId, int maxNegativeId, int scheduledCount) { + int maxDate = lastSavedDate; storageQueue.postRunnable(() -> { try { - long currentMaxId = 0; + int currentMaxId = 0; int unreadCount = 0; long last_mid = 0; int prevUnreadCount = 0; - SQLiteCursor cursor = database.queryFinalized("SELECT unread_count, inbox_max, last_mid FROM dialogs WHERE did = " + dialog_id); + SQLiteCursor cursor = database.queryFinalized("SELECT unread_count, inbox_max, last_mid FROM dialogs WHERE did = " + dialogId); if (cursor.next()) { prevUnreadCount = unreadCount = cursor.intValue(0); currentMaxId = cursor.intValue(1); @@ -5549,18 +6031,13 @@ public class MessagesStorage extends BaseController { database.beginTransaction(); SQLitePreparedStatement state; - int lower_id = (int) dialog_id; + if (!DialogObject.isEncryptedDialog(dialogId)) { + currentMaxId = Math.max(currentMaxId, maxPositiveId); - if (lower_id != 0) { - currentMaxId = Math.max(currentMaxId, (int) maxPositiveId); - if (isChannel) { - currentMaxId |= ((long) -lower_id) << 32; - } - - state = database.executeFast("UPDATE messages SET read_state = read_state | 1 WHERE uid = ? AND mid <= ? AND read_state IN(0,2) AND out = 0"); + state = database.executeFast("UPDATE messages_v2 SET read_state = read_state | 1 WHERE uid = ? AND mid <= ? AND read_state IN(0,2) AND out = 0"); state.requery(); - state.bindLong(1, dialog_id); - state.bindLong(2, currentMaxId); + state.bindLong(1, dialogId); + state.bindInteger(2, currentMaxId); state.step(); state.dispose(); @@ -5578,24 +6055,24 @@ public class MessagesStorage extends BaseController { state = database.executeFast("DELETE FROM unread_push_messages WHERE uid = ? AND mid <= ?"); state.requery(); - state.bindLong(1, dialog_id); - state.bindLong(2, currentMaxId); + state.bindLong(1, dialogId); + state.bindInteger(2, currentMaxId); state.step(); state.dispose(); state = database.executeFast("DELETE FROM unread_push_messages WHERE uid = ? AND date <= ?"); state.requery(); - state.bindLong(1, dialog_id); - state.bindLong(2, maxDate); + state.bindLong(1, dialogId); + state.bindInteger(2, maxDate); state.step(); state.dispose(); } else { - currentMaxId = (int) maxNegativeId; + currentMaxId = maxNegativeId; - state = database.executeFast("UPDATE messages SET read_state = read_state | 1 WHERE uid = ? AND mid >= ? AND read_state IN(0,2) AND out = 0"); + state = database.executeFast("UPDATE messages_v2 SET read_state = read_state | 1 WHERE uid = ? AND mid >= ? AND read_state IN(0,2) AND out = 0"); state.requery(); - state.bindLong(1, dialog_id); - state.bindLong(2, currentMaxId); + state.bindLong(1, dialogId); + state.bindInteger(2, currentMaxId); state.step(); state.dispose(); @@ -5615,30 +6092,30 @@ public class MessagesStorage extends BaseController { state = database.executeFast("UPDATE dialogs SET unread_count = ?, inbox_max = ? WHERE did = ?"); state.requery(); state.bindInteger(1, unreadCount); - state.bindInteger(2, (int) currentMaxId); - state.bindLong(3, dialog_id); + state.bindInteger(2, currentMaxId); + state.bindLong(3, dialogId); state.step(); state.dispose(); database.commitTransaction(); if (prevUnreadCount != 0 && unreadCount == 0) { - LongSparseArray dialogsToUpdate = new LongSparseArray<>(); - dialogsToUpdate.put(dialog_id, unreadCount); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(); + dialogsToUpdate.put(dialogId, unreadCount); updateFiltersReadCounter(dialogsToUpdate, null, true); } - updateWidgets(dialog_id); + updateWidgets(dialogId); } catch (Exception e) { FileLog.e(e); } }); } - public void putContacts(ArrayList contacts, final boolean deleteAll) { + public void putContacts(ArrayList contacts, boolean deleteAll) { if (contacts.isEmpty() && !deleteAll) { return; } - final ArrayList contactsCopy = new ArrayList<>(contacts); + ArrayList contactsCopy = new ArrayList<>(contacts); storageQueue.postRunnable(() -> { try { if (deleteAll) { @@ -5649,7 +6126,7 @@ public class MessagesStorage extends BaseController { for (int a = 0; a < contactsCopy.size(); a++) { TLRPC.TL_contact contact = contactsCopy.get(a); state.requery(); - state.bindInteger(1, contact.user_id); + state.bindLong(1, contact.user_id); state.bindInteger(2, contact.mutual ? 1 : 0); state.step(); } @@ -5661,7 +6138,7 @@ public class MessagesStorage extends BaseController { }); } - public void deleteContacts(final ArrayList uids) { + public void deleteContacts(ArrayList uids) { if (uids == null || uids.isEmpty()) { return; } @@ -5675,7 +6152,7 @@ public class MessagesStorage extends BaseController { }); } - public void applyPhoneBookUpdates(final String adds, final String deletes) { + public void applyPhoneBookUpdates(String adds, String deletes) { if (TextUtils.isEmpty(adds)) { return; } @@ -5693,7 +6170,7 @@ public class MessagesStorage extends BaseController { }); } - public void putCachedPhoneBook(final HashMap contactHashMap, final boolean migrate, final boolean delete) { + public void putCachedPhoneBook(HashMap contactHashMap, boolean migrate, boolean delete) { if (contactHashMap == null || contactHashMap.isEmpty() && !migrate && !delete) { return; } @@ -5743,7 +6220,7 @@ public class MessagesStorage extends BaseController { }); } - public void getCachedPhoneBook(final boolean byError) { + public void getCachedPhoneBook(boolean byError) { storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; try { @@ -5898,9 +6375,9 @@ public class MessagesStorage extends BaseController { SQLiteCursor cursor = database.queryFinalized("SELECT * FROM contacts WHERE 1"); StringBuilder uids = new StringBuilder(); while (cursor.next()) { - int user_id = cursor.intValue(0); + long userId = cursor.intValue(0); TLRPC.TL_contact contact = new TLRPC.TL_contact(); - contact.user_id = user_id; + contact.user_id = userId; contact.mutual = cursor.intValue(1) == 1; if (uids.length() != 0) { uids.append(","); @@ -5922,7 +6399,7 @@ public class MessagesStorage extends BaseController { }); } - public void getUnsentMessages(final int count) { + public void getUnsentMessages(int count) { storageQueue.postRunnable(() -> { try { SparseArray messageHashMap = new SparseArray<>(); @@ -5932,11 +6409,11 @@ public class MessagesStorage extends BaseController { ArrayList chats = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedChatIds = new ArrayList<>(); - SQLiteCursor cursor = database.queryFinalized("SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.uid, s.seq_in, s.seq_out, m.ttl FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid LEFT JOIN messages_seq as s ON m.mid = s.mid WHERE (m.mid < 0 AND m.send_state = 1) OR (m.mid > 0 AND m.send_state = 3) ORDER BY m.mid DESC LIMIT " + count); + SQLiteCursor cursor = database.queryFinalized("SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.uid, s.seq_in, s.seq_out, m.ttl FROM messages_v2 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid AND r.uid = m.uid LEFT JOIN messages_seq as s ON m.mid = s.mid WHERE (m.mid < 0 AND m.send_state = 1) OR (m.mid > 0 AND m.send_state = 3) ORDER BY m.mid DESC LIMIT " + count); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { @@ -5958,28 +6435,24 @@ public class MessagesStorage extends BaseController { messages.add(message); messageHashMap.put(message.id, message); - int lower_id = (int) message.dialog_id; - int high_id = (int) (message.dialog_id >> 32); - - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } - } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } + if (DialogObject.isEncryptedDialog(message.dialog_id)) { + int encryptedChatId = DialogObject.getEncryptedChatId(message.dialog_id); + if (!encryptedChatIds.contains(encryptedChatId)) { + encryptedChatIds.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(message.dialog_id)) { + if (!usersToLoad.contains(message.dialog_id)) { + usersToLoad.add(message.dialog_id); } } else { - if (!encryptedChatIds.contains(high_id)) { - encryptedChatIds.add(high_id); + if (!chatsToLoad.contains(-message.dialog_id)) { + chatsToLoad.add(-message.dialog_id); } } addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - if (message.send_state != 3 && (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && lower_id != 0 || message.id > 0)) { + if (message.send_state != 3 && (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && !DialogObject.isEncryptedDialog(message.dialog_id) || message.id > 0)) { message.send_state = 0; } } @@ -5987,7 +6460,7 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); - cursor = database.queryFinalized("SELECT m.data, m.send_state, m.mid, m.date, r.random_id, m.uid, m.ttl FROM scheduled_messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE (m.mid < 0 AND m.send_state = 1) OR (m.mid > 0 AND m.send_state = 3) ORDER BY date ASC"); + cursor = database.queryFinalized("SELECT m.data, m.send_state, m.mid, m.date, r.random_id, m.uid, m.ttl FROM scheduled_messages_v2 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid AND r.uid = m.uid WHERE (m.mid < 0 AND m.send_state = 1) OR (m.mid > 0 AND m.send_state = 3) ORDER BY date ASC"); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -6006,28 +6479,24 @@ public class MessagesStorage extends BaseController { scheduledMessages.add(message); messageHashMap.put(message.id, message); - int lower_id = (int) message.dialog_id; - int high_id = (int) (message.dialog_id >> 32); - - if (lower_id != 0) { - if (lower_id < 0) { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } - } else { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } + if (DialogObject.isEncryptedDialog(message.dialog_id)) { + int encryptedChatId = DialogObject.getEncryptedChatId(message.dialog_id); + if (!encryptedChatIds.contains(encryptedChatId)) { + encryptedChatIds.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(message.dialog_id)) { + if (!usersToLoad.contains(message.dialog_id)) { + usersToLoad.add(message.dialog_id); } } else { - if (!encryptedChatIds.contains(high_id)) { - encryptedChatIds.add(high_id); + if (!chatsToLoad.contains(-message.dialog_id)) { + chatsToLoad.add(-message.dialog_id); } } addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - if (message.send_state != 3 && (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && lower_id != 0 || message.id > 0)) { + if (message.send_state != 3 && (message.peer_id.channel_id == 0 && !MessageObject.isUnread(message) && !DialogObject.isEncryptedDialog(message.dialog_id) || message.id > 0)) { message.send_state = 0; } } @@ -6046,7 +6515,7 @@ public class MessagesStorage extends BaseController { if (!chatsToLoad.isEmpty()) { StringBuilder stringToLoad = new StringBuilder(); for (int a = 0; a < chatsToLoad.size(); a++) { - Integer cid = chatsToLoad.get(a); + Long cid = chatsToLoad.get(a); if (stringToLoad.length() != 0) { stringToLoad.append(","); } @@ -6062,13 +6531,13 @@ public class MessagesStorage extends BaseController { }); } - public boolean checkMessageByRandomId(final long random_id) { - final boolean[] result = new boolean[1]; - final CountDownLatch countDownLatch = new CountDownLatch(1); + public boolean checkMessageByRandomId(long random_id) { + boolean[] result = new boolean[1]; + CountDownLatch countDownLatch = new CountDownLatch(1); storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; try { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT random_id FROM randoms WHERE random_id = %d", random_id)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT random_id FROM randoms_v2 WHERE random_id = %d", random_id)); if (cursor.next()) { result[0] = true; } @@ -6089,17 +6558,13 @@ public class MessagesStorage extends BaseController { return result[0]; } - public boolean checkMessageId(final long dialog_id, boolean isChannel, final int mid) { - final boolean[] result = new boolean[1]; - final CountDownLatch countDownLatch = new CountDownLatch(1); + public boolean checkMessageId(long dialogId, int mid) { + boolean[] result = new boolean[1]; + CountDownLatch countDownLatch = new CountDownLatch(1); storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; try { - long messageId = mid; - if (isChannel) { - messageId |= ((-dialog_id) << 32); - } - cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages WHERE uid = %d AND mid = %d", dialog_id, messageId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE uid = %d AND mid = %d", dialogId, mid)); if (cursor.next()) { result[0] = true; } @@ -6120,11 +6585,11 @@ public class MessagesStorage extends BaseController { return result[0]; } - public void getUnreadMention(final long dialog_id, final IntCallback callback) { + public void getUnreadMention(long dialog_id, IntCallback callback) { storageQueue.postRunnable(() -> { try { - final int result; - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT MIN(mid) FROM messages WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", dialog_id)); + int result; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT MIN(mid) FROM messages_v2 WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", dialog_id)); if (cursor.next()) { result = cursor.intValue(0); } else { @@ -6138,11 +6603,11 @@ public class MessagesStorage extends BaseController { }); } - public void getMessagesCount(final long dialog_id, final IntCallback callback) { + public void getMessagesCount(long dialog_id, IntCallback callback) { storageQueue.postRunnable(() -> { try { - final int result; - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages WHERE uid = %d", dialog_id)); + int result; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages_v2 WHERE uid = %d", dialog_id)); if (cursor.next()) { result = cursor.intValue(0); } else { @@ -6156,9 +6621,9 @@ public class MessagesStorage extends BaseController { }); } - public Runnable getMessagesInternal(long dialogId, long mergeDialogId, int count, int max_id, int offset_date, int minDate, int classGuid, int load_type, boolean isChannel, boolean scheduled, int replyMessageId, int loadIndex, boolean processMessages) { + public Runnable getMessagesInternal(long dialogId, long mergeDialogId, int count, int max_id, int offset_date, int minDate, int classGuid, int load_type, boolean scheduled, int replyMessageId, int loadIndex, boolean processMessages) { TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages(); - int currentUserId = getUserConfig().clientUserId; + long currentUserId = getUserConfig().clientUserId; int count_unread = 0; int mentions_unread = 0; int count_query = count; @@ -6167,33 +6632,27 @@ public class MessagesStorage extends BaseController { int last_message_id = 0; boolean queryFromServer = false; int max_unread_date = 0; - long messageMaxId = max_id; + int messageMaxId = max_id; int max_id_query = max_id; boolean unreadCountIsLocal = false; int max_id_override = max_id; - int channelId = 0; - if (isChannel) { - channelId = -(int) dialogId; - } - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } boolean isEnd = false; int num = dialogId == 777000 ? 10 : 1; int messagesCount = 0; long startLoadTime = SystemClock.elapsedRealtime(); try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); - ArrayList replyMessages = new ArrayList<>(); - SparseArray> replyMessageOwners = new SparseArray<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); + LongSparseArray>> replyMessageOwners = new LongSparseArray<>(); + LongSparseArray> dialogReplyMessagesIds = new LongSparseArray<>(); LongSparseArray> replyMessageRandomOwners = new LongSparseArray<>(); + ArrayList replyMessageRandomIds = new ArrayList<>(); SQLiteCursor cursor; - final String messageSelect = "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata, m.media, m.ttl, m.mention, m.imp, m.forwards, m.replies_data FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid"; + String messageSelect = "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata, m.media, m.ttl, m.mention, m.imp, m.forwards, m.replies_data FROM messages_v2 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid AND r.uid = m.uid"; if (scheduled) { isEnd = true; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata, m.ttl FROM scheduled_messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d ORDER BY m.date DESC", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata, m.ttl FROM scheduled_messages_v2 as m LEFT JOIN randoms_v2 as r ON r.mid = m.mid AND r.uid = m.uid WHERE m.uid = %d ORDER BY m.date DESC", dialogId)); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -6234,32 +6693,16 @@ public class MessagesStorage extends BaseController { } if (message.replyMessage == null) { if (message.reply_to.reply_to_msg_id != 0) { - long messageId = message.reply_to.reply_to_msg_id; - if (message.reply_to.reply_to_peer_id != null) { - if (message.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) message.reply_to.reply_to_peer_id.channel_id) << 32; - } - } else if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - if (!replyMessages.contains(messageId)) { - replyMessages.add(messageId); - } - ArrayList messages = replyMessageOwners.get(message.reply_to.reply_to_msg_id); - if (messages == null) { - messages = new ArrayList<>(); - replyMessageOwners.put(message.reply_to.reply_to_msg_id, messages); - } - messages.add(message); + addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds); } else { - if (!replyMessages.contains(message.reply_to.reply_to_random_id)) { - replyMessages.add(message.reply_to.reply_to_random_id); - } ArrayList messages = replyMessageRandomOwners.get(message.reply_to.reply_to_random_id); if (messages == null) { messages = new ArrayList<>(); replyMessageRandomOwners.put(message.reply_to.reply_to_random_id, messages); } + if (!replyMessageRandomIds.contains(message.reply_to.reply_to_random_id)) { + replyMessageRandomIds.add(message.reply_to.reply_to_random_id); + } messages.add(message); } } @@ -6268,8 +6711,7 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); } else { - int lower_id = (int) dialogId; - if (lower_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if (load_type == 3 && minDate == 0) { cursor = database.queryFinalized("SELECT inbox_max, unread_count, date, unread_count_i FROM dialogs WHERE did = " + dialogId); if (cursor.next()) { @@ -6288,23 +6730,20 @@ public class MessagesStorage extends BaseController { max_unread_date = cursor.intValue(2); mentions_unread = cursor.intValue(3); queryFromServer = true; - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } if (dialogId == currentUserId) { count_unread = 0; } } cursor.dispose(); if (!queryFromServer) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid), max(date) FROM messages WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid), max(date) FROM messages_v2 WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > 0", dialogId)); if (cursor.next()) { min_unread_id = cursor.intValue(0); max_unread_date = cursor.intValue(1); } cursor.dispose(); if (min_unread_id != 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages WHERE uid = %d AND mid >= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages_v2 WHERE uid = %d AND mid >= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id)); if (cursor.next()) { count_unread = cursor.intValue(0); } @@ -6312,18 +6751,15 @@ public class MessagesStorage extends BaseController { } } else if (max_id_query == 0) { int existingUnreadCount = 0; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages WHERE uid = %d AND mid > 0 AND out = 0 AND read_state IN(0,2)", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages_v2 WHERE uid = %d AND mid > 0 AND out = 0 AND read_state IN(0,2)", dialogId)); if (cursor.next()) { existingUnreadCount = cursor.intValue(0); } cursor.dispose(); if (existingUnreadCount == count_unread) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > 0", dialogId)); if (cursor.next()) { messageMaxId = max_id_query = min_unread_id = cursor.intValue(0); - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } } cursor.dispose(); } @@ -6333,12 +6769,9 @@ public class MessagesStorage extends BaseController { cursor.dispose(); if (containMessage) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > %d", dialogId, max_id_query)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid > %d", dialogId, max_id_query)); if (cursor.next()) { messageMaxId = max_id_query = cursor.intValue(0); - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } } cursor.dispose(); } @@ -6365,7 +6798,7 @@ public class MessagesStorage extends BaseController { isEnd = cursor.intValue(0) == 1; } else { cursor.dispose(); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND mid > 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND mid > 0", dialogId)); if (cursor.next()) { int mid = cursor.intValue(0); if (mid != 0) { @@ -6382,7 +6815,7 @@ public class MessagesStorage extends BaseController { cursor.dispose(); if (load_type == 3 || load_type == 4 || queryFromServer && load_type == 2) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages WHERE uid = %d AND mid > 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages_v2 WHERE uid = %d AND mid > 0", dialogId)); if (cursor.next()) { last_message_id = cursor.intValue(0); } @@ -6392,14 +6825,14 @@ public class MessagesStorage extends BaseController { int startMid; int endMid; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages WHERE uid = %d AND date <= %d AND mid > 0", dialogId, offset_date)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages_v2 WHERE uid = %d AND date <= %d AND mid > 0", dialogId, offset_date)); if (cursor.next()) { startMid = cursor.intValue(0); } else { startMid = -1; } cursor.dispose(); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND date >= %d AND mid > 0", dialogId, offset_date)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND date >= %d AND mid > 0", dialogId, offset_date)); if (cursor.next()) { endMid = cursor.intValue(0); } else { @@ -6424,9 +6857,6 @@ public class MessagesStorage extends BaseController { if (endMid != -1) { max_id_override = endMid; messageMaxId = max_id_query = endMid; - if (messageMaxId != 0 && channelId != 0) { - messageMaxId |= ((long) channelId) << 32; - } } } } @@ -6443,30 +6873,21 @@ public class MessagesStorage extends BaseController { } if (containMessage) { - long holeMessageMaxId = 0; - long holeMessageMinId = 1; + int holeMessageMaxId = 0; + int holeMessageMinId = 1; cursor = database.queryFinalized(String.format(Locale.US, "SELECT start FROM messages_holes WHERE uid = %d AND start >= %d ORDER BY start ASC LIMIT 1", dialogId, max_id_query)); if (cursor.next()) { holeMessageMaxId = cursor.intValue(0); - if (channelId != 0) { - holeMessageMaxId |= ((long) channelId) << 32; - } } cursor.dispose(); cursor = database.queryFinalized(String.format(Locale.US, "SELECT end FROM messages_holes WHERE uid = %d AND end <= %d ORDER BY end DESC LIMIT 1", dialogId, max_id_query)); if (cursor.next()) { holeMessageMinId = cursor.intValue(0); - if (channelId != 0) { - holeMessageMinId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageMaxId != 0 || holeMessageMinId != 1) { if (holeMessageMaxId == 0) { holeMessageMaxId = 1000000000; - if (channelId != 0) { - holeMessageMaxId |= ((long) channelId) << 32; - } } cursor = database.queryFinalized(String.format(Locale.US, "SELECT * FROM (" + messageSelect + " WHERE m.uid = %d AND m.mid <= %d AND (m.mid >= %d OR m.mid < 0) ORDER BY m.date DESC, m.mid DESC LIMIT %d) UNION " + "SELECT * FROM (" + messageSelect + " WHERE m.uid = %d AND m.mid > %d AND (m.mid <= %d OR m.mid < 0) ORDER BY m.date ASC, m.mid ASC LIMIT %d)", dialogId, messageMaxId, holeMessageMinId, count_query / 2, dialogId, messageMaxId, holeMessageMaxId, count_query / 2)); @@ -6477,7 +6898,7 @@ public class MessagesStorage extends BaseController { } else { if (load_type == 2) { int existingUnreadCount = 0; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages WHERE uid = %d AND mid != 0 AND out = 0 AND read_state IN(0,2)", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages_v2 WHERE uid = %d AND mid != 0 AND out = 0 AND read_state IN(0,2)", dialogId)); if (cursor.next()) { existingUnreadCount = cursor.intValue(0); } @@ -6494,13 +6915,10 @@ public class MessagesStorage extends BaseController { } } } else if (load_type == 1) { - long holeMessageId = 0; + int holeMessageId = 0; cursor = database.queryFinalized(String.format(Locale.US, "SELECT start, end FROM messages_holes WHERE uid = %d AND (start >= %d AND start != 1 AND end != 1 OR start < %d AND end > %d) ORDER BY start ASC LIMIT 1", dialogId, max_id, max_id, max_id)); if (cursor.next()) { holeMessageId = cursor.intValue(0); - if (channelId != 0) { - holeMessageId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageId != 0) { @@ -6510,13 +6928,10 @@ public class MessagesStorage extends BaseController { } } else if (minDate != 0) { if (messageMaxId != 0) { - long holeMessageId = 0; + int holeMessageId = 0; cursor = database.queryFinalized(String.format(Locale.US, "SELECT end FROM messages_holes WHERE uid = %d AND end <= %d ORDER BY end DESC LIMIT 1", dialogId, max_id)); if (cursor.next()) { holeMessageId = cursor.intValue(0); - if (channelId != 0) { - holeMessageId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageId != 0) { @@ -6528,19 +6943,16 @@ public class MessagesStorage extends BaseController { cursor = database.queryFinalized(String.format(Locale.US, "" + messageSelect + " WHERE m.uid = %d AND m.date <= %d ORDER BY m.date DESC, m.mid DESC LIMIT %d,%d", dialogId, minDate, offset_query, count_query)); } } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages WHERE uid = %d AND mid > 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid) FROM messages_v2 WHERE uid = %d AND mid > 0", dialogId)); if (cursor.next()) { last_message_id = cursor.intValue(0); } cursor.dispose(); - long holeMessageId = 0; + int holeMessageId = 0; cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(end) FROM messages_holes WHERE uid = %d", dialogId)); if (cursor.next()) { holeMessageId = cursor.intValue(0); - if (channelId != 0) { - holeMessageId |= ((long) channelId) << 32; - } } cursor.dispose(); if (holeMessageId != 0) { @@ -6553,14 +6965,14 @@ public class MessagesStorage extends BaseController { isEnd = true; if (load_type == 3 && minDate == 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND mid < 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND mid < 0", dialogId)); if (cursor.next()) { min_unread_id = cursor.intValue(0); } cursor.dispose(); int min_unread_id2 = 0; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid), max(date) FROM messages WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid < 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid), max(date) FROM messages_v2 WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid < 0", dialogId)); if (cursor.next()) { min_unread_id2 = cursor.intValue(0); max_unread_date = cursor.intValue(1); @@ -6568,7 +6980,7 @@ public class MessagesStorage extends BaseController { cursor.dispose(); if (min_unread_id2 != 0) { min_unread_id = min_unread_id2; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages WHERE uid = %d AND mid <= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id2)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages_v2 WHERE uid = %d AND mid <= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id2)); if (cursor.next()) { count_unread = cursor.intValue(0); } @@ -6577,7 +6989,7 @@ public class MessagesStorage extends BaseController { } if (load_type == 3 || load_type == 4) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND mid < 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND mid < 0", dialogId)); if (cursor.next()) { last_message_id = cursor.intValue(0); } @@ -6595,20 +7007,20 @@ public class MessagesStorage extends BaseController { } } else { if (load_type == 2) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages WHERE uid = %d AND mid < 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT min(mid) FROM messages_v2 WHERE uid = %d AND mid < 0", dialogId)); if (cursor.next()) { last_message_id = cursor.intValue(0); } cursor.dispose(); - cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid), max(date) FROM messages WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid < 0", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT max(mid), max(date) FROM messages_v2 WHERE uid = %d AND out = 0 AND read_state IN(0,2) AND mid < 0", dialogId)); if (cursor.next()) { min_unread_id = cursor.intValue(0); max_unread_date = cursor.intValue(1); } cursor.dispose(); if (min_unread_id != 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages WHERE uid = %d AND mid <= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(*) FROM messages_v2 WHERE uid = %d AND mid <= %d AND out = 0 AND read_state IN(0,2)", dialogId, min_unread_id)); if (cursor.next()) { count_unread = cursor.intValue(0); } @@ -6672,13 +7084,13 @@ public class MessagesStorage extends BaseController { } NativeByteBuffer repliesData = cursor.byteBufferValue(12); if (repliesData != null) { - TLRPC.TL_messageReplies replies = TLRPC.TL_messageReplies.TLdeserialize(repliesData, repliesData.readInt32(false), false); + TLRPC.MessageReplies replies = TLRPC.MessageReplies.TLdeserialize(repliesData, repliesData.readInt32(false), false); if (replies != null) { message.replies = replies; } repliesData.reuse(); } - if (lower_id != 0 && message.ttl == 0) { + if (!DialogObject.isEncryptedDialog(dialogId) && message.ttl == 0) { message.ttl = cursor.intValue(8); } if (cursor.intValue(9) != 0) { @@ -6708,46 +7120,26 @@ public class MessagesStorage extends BaseController { } if (message.replyMessage == null) { if (message.reply_to.reply_to_msg_id != 0) { - long messageId = message.reply_to.reply_to_msg_id; - if (message.reply_to.reply_to_peer_id != null) { - if (message.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) message.reply_to.reply_to_peer_id.channel_id) << 32; - } - } else if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - if (!replyMessages.contains(messageId)) { - replyMessages.add(messageId); - } - ArrayList messages = replyMessageOwners.get(message.reply_to.reply_to_msg_id); - if (messages == null) { - messages = new ArrayList<>(); - replyMessageOwners.put(message.reply_to.reply_to_msg_id, messages); - } - messages.add(message); + addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds); } else { - if (!replyMessages.contains(message.reply_to.reply_to_random_id)) { - replyMessages.add(message.reply_to.reply_to_random_id); - } ArrayList messages = replyMessageRandomOwners.get(message.reply_to.reply_to_random_id); if (messages == null) { messages = new ArrayList<>(); replyMessageRandomOwners.put(message.reply_to.reply_to_random_id, messages); } + if (!replyMessageRandomIds.contains(message.reply_to.reply_to_random_id)) { + replyMessageRandomIds.add(message.reply_to.reply_to_random_id); + } messages.add(message); } } } - if (lower_id == 0 && !cursor.isNull(5)) { + if (DialogObject.isEncryptedDialog(dialogId) && !cursor.isNull(5)) { message.random_id = cursor.longValue(5); } if (MessageObject.isSecretMedia(message)) { try { - long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - SQLiteCursor cursor2 = database.queryFinalized(String.format(Locale.US, "SELECT date FROM enc_tasks_v3 WHERE mid = %d AND media = 1", messageId)); + SQLiteCursor cursor2 = database.queryFinalized(String.format(Locale.US, "SELECT date FROM enc_tasks_v4 WHERE mid = %d AND uid = %d AND media = 1", message.id, MessageObject.getDialogId(message))); if (cursor2.next()) { message.destroyTime = cursor2.intValue(0); } @@ -6760,22 +7152,6 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); } - if (messageIdsToFix != null) { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET mid = ? WHERE mid = ?"); - try { - for (int a = 0, N = messageIdsToFix.size(); a < N; a++) { - long id = messageIdsToFix.get(a); - state.requery(); - state.bindLong(1, (int) id); - state.bindLong(2, id); - state.step(); - } - } catch (Exception e) { - FileLog.e(e); - } - state.dispose(); - } - Collections.sort(res.messages, (lhs, rhs) -> { if (lhs.id > 0 && rhs.id > 0) { @@ -6800,10 +7176,9 @@ public class MessagesStorage extends BaseController { return 0; }); - if (lower_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if ((load_type == 3 || load_type == 4 || load_type == 2 && queryFromServer && !unreadCountIsLocal) && !res.messages.isEmpty()) { if (!(minId <= max_id_query && maxId >= max_id_query)) { - replyMessages.clear(); usersToLoad.clear(); chatsToLoad.clear(); res.messages.clear(); @@ -6814,7 +7189,7 @@ public class MessagesStorage extends BaseController { } } if (mentions_unread != 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", dialogId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages_v2 WHERE uid = %d AND mention = 1 AND read_state IN(0, 1)", dialogId)); if (cursor.next()) { if (mentions_unread != cursor.intValue(0)) { mentions_unread *= -1; @@ -6825,12 +7200,8 @@ public class MessagesStorage extends BaseController { cursor.dispose(); } } - if (!replyMessages.isEmpty()) { - if (replyMessageOwners.size() > 0) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages))); - } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessages))); - } + if (!replyMessageRandomOwners.isEmpty()) { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms_v2 as r INNER JOIN messages_v2 as m ON r.mid = m.mid AND r.uid = m.uid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessageRandomIds))); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { @@ -6843,42 +7214,33 @@ public class MessagesStorage extends BaseController { addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - if (replyMessageOwners.size() > 0) { - ArrayList arrayList = replyMessageOwners.get(message.id); - if (arrayList != null) { - for (int a = 0; a < arrayList.size(); a++) { - TLRPC.Message object = arrayList.get(a); - object.replyMessage = message; - } - } - } else { - long value = cursor.longValue(3); - ArrayList arrayList = replyMessageRandomOwners.get(value); - replyMessageRandomOwners.remove(value); - if (arrayList != null) { - for (int a = 0; a < arrayList.size(); a++) { - TLRPC.Message object = arrayList.get(a); - object.replyMessage = message; - if (object.reply_to != null) { - object.reply_to.reply_to_msg_id = message.id; - } + long value = cursor.longValue(3); + ArrayList arrayList = replyMessageRandomOwners.get(value); + replyMessageRandomOwners.remove(value); + if (arrayList != null) { + for (int a = 0; a < arrayList.size(); a++) { + TLRPC.Message object = arrayList.get(a); + object.replyMessage = message; + if (object.reply_to != null) { + object.reply_to.reply_to_msg_id = message.id; } } } } } + cursor.dispose(); - if (replyMessageRandomOwners.size() > 0) { - for (int b = 0; b < replyMessageRandomOwners.size(); b++) { - ArrayList arrayList = replyMessageRandomOwners.valueAt(b); - for (int a = 0; a < arrayList.size(); a++) { - TLRPC.Message message = arrayList.get(a); - if (message.reply_to != null) { - message.reply_to.reply_to_random_id = 0; - } + for (int b = 0, N = replyMessageRandomOwners.size(); b < N; b++) { + ArrayList arrayList = replyMessageRandomOwners.valueAt(b); + for (int a = 0, N2 = arrayList.size(); a < N2; a++) { + TLRPC.Message message = arrayList.get(a); + if (message.reply_to != null) { + message.reply_to.reply_to_random_id = 0; } } } + } else { + loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad); } if (!usersToLoad.isEmpty()) { getUsersInternal(TextUtils.join(",", usersToLoad), res.users); @@ -6912,14 +7274,12 @@ public class MessagesStorage extends BaseController { }; } else {*/ int finalMessagesCount = scheduled ? res.messages.size() : messagesCount; - return () -> getMessagesController().processLoadedMessages(res, finalMessagesCount, dialogId, mergeDialogId, countQueryFinal, maxIdOverrideFinal, offset_date, true, classGuid, minUnreadIdFinal, lastMessageIdFinal, countUnreadFinal, maxUnreadDateFinal, load_type, isChannel, isEndFinal, scheduled ? 1 : 0, replyMessageId, loadIndex, queryFromServerFinal, mentionsUnreadFinal, processMessages); + return () -> getMessagesController().processLoadedMessages(res, finalMessagesCount, dialogId, mergeDialogId, countQueryFinal, maxIdOverrideFinal, offset_date, true, classGuid, minUnreadIdFinal, lastMessageIdFinal, countUnreadFinal, maxUnreadDateFinal, load_type, isEndFinal, scheduled ? 1 : 0, replyMessageId, loadIndex, queryFromServerFinal, mentionsUnreadFinal, processMessages); //} } - public void getMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, int minDate, int classGuid, int load_type, boolean isChannel, boolean scheduled, int replyMessageId, int loadIndex, boolean processMessages) { + public void getMessages(long dialogId, long mergeDialogId, boolean loadInfo, int count, int max_id, int offset_date, int minDate, int classGuid, int load_type, boolean scheduled, int replyMessageId, int loadIndex, boolean processMessages) { storageQueue.postRunnable(() -> { - long mergeDialogIdFinal = mergeDialogId; - int lowerId = (int) dialogId; /*if (loadInfo) { if (lowerId < 0) { TLRPC.ChatFull info = loadChatInfoInternal(-lowerId, true, false, 0); @@ -6928,7 +7288,7 @@ public class MessagesStorage extends BaseController { } } }*/ - Utilities.stageQueue.postRunnable(getMessagesInternal(dialogId, mergeDialogIdFinal, count, max_id, offset_date, minDate, classGuid, load_type, isChannel, scheduled, replyMessageId, loadIndex, processMessages)); + Utilities.stageQueue.postRunnable(getMessagesInternal(dialogId, mergeDialogId, count, max_id, offset_date, minDate, classGuid, load_type, scheduled, replyMessageId, loadIndex, processMessages)); }); } @@ -6942,12 +7302,12 @@ public class MessagesStorage extends BaseController { }); } - public Object[] getSentFile(final String path, final int type) { + public Object[] getSentFile(String path, int type) { if (path == null || path.toLowerCase().endsWith("attheme")) { return null; } - final CountDownLatch countDownLatch = new CountDownLatch(1); - final Object[] result = new Object[2]; + CountDownLatch countDownLatch = new CountDownLatch(1); + Object[] result = new Object[2]; storageQueue.postRunnable(() -> { try { String id = Utilities.MD5(path); @@ -7051,11 +7411,11 @@ public class MessagesStorage extends BaseController { } public void getWidgetDialogIds(int widgetId, int type, ArrayList dids, ArrayList users, ArrayList chats, boolean edit) { - final CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countDownLatch = new CountDownLatch(1); storageQueue.postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did FROM shortcut_widget WHERE id = %d ORDER BY ord ASC", widgetId)); while (cursor.next()) { long id = cursor.longValue(0); @@ -7064,11 +7424,10 @@ public class MessagesStorage extends BaseController { } dids.add(id); if (users != null && chats != null) { - int lowerId = (int) id; - if (lowerId > 0) { - usersToLoad.add(lowerId); + if (DialogObject.isUserDialog(id)) { + usersToLoad.add(id); } else { - chatsToLoad.add(-lowerId); + chatsToLoad.add(-id); } } } @@ -7083,11 +7442,10 @@ public class MessagesStorage extends BaseController { } dids.add(dialogId); if (users != null && chats != null) { - int lowerId = (int) dialogId; - if (lowerId > 0) { - usersToLoad.add(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + usersToLoad.add(dialogId); } else { - chatsToLoad.add(-lowerId); + chatsToLoad.add(-dialogId); } } } @@ -7098,11 +7456,10 @@ public class MessagesStorage extends BaseController { long dialogId = cursor.longValue(0); dids.add(dialogId); if (users != null && chats != null) { - int lowerId = (int) dialogId; - if (lowerId > 0) { - usersToLoad.add(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + usersToLoad.add(dialogId); } else { - chatsToLoad.add(-lowerId); + chatsToLoad.add(-dialogId); } } } @@ -7131,12 +7488,12 @@ public class MessagesStorage extends BaseController { } public void getWidgetDialogs(int widgetId, int type, ArrayList dids, LongSparseArray dialogs, LongSparseArray messages, ArrayList users, ArrayList chats) { - final CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countDownLatch = new CountDownLatch(1); storageQueue.postRunnable(() -> { try { boolean add = false; - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did FROM shortcut_widget WHERE id = %d ORDER BY ord ASC", widgetId)); while (cursor.next()) { long id = cursor.longValue(0); @@ -7144,11 +7501,10 @@ public class MessagesStorage extends BaseController { continue; } dids.add(id); - int lowerId = (int) id; - if (lowerId > 0) { - usersToLoad.add(lowerId); + if (DialogObject.isUserDialog(id)) { + usersToLoad.add(id); } else { - chatsToLoad.add(-lowerId); + chatsToLoad.add(-id); } } cursor.dispose(); @@ -7157,20 +7513,19 @@ public class MessagesStorage extends BaseController { while (cursor.next()) { long dialogId = cursor.longValue(0); dids.add(dialogId); - int lowerId = (int) dialogId; - if (lowerId > 0) { - usersToLoad.add(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + usersToLoad.add(dialogId); } else { - chatsToLoad.add(-lowerId); + chatsToLoad.add(-dialogId); } } cursor.dispose(); } if (dids.isEmpty()) { add = true; - cursor = database.queryFinalized("SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.folder_id = 0 ORDER BY d.pinned DESC, d.date DESC LIMIT 0,10"); + cursor = database.queryFinalized("SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid WHERE d.folder_id = 0 ORDER BY d.pinned DESC, d.date DESC LIMIT 0,10"); } else { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", TextUtils.join(",", dids))); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid WHERE d.did IN(%s)", TextUtils.join(",", dids))); } while (cursor.next()) { long dialogId = cursor.longValue(0); @@ -7214,14 +7569,13 @@ public class MessagesStorage extends BaseController { TLRPC.TL_dialog dialog = new TLRPC.TL_dialog(); dialog.id = did; dialogs.put(dialog.id, dialog); - int lowerId = (int) did; - if (lowerId < 0) { - if (chatsToLoad.contains(-lowerId)) { - chatsToLoad.add(-lowerId); + if (DialogObject.isChatDialog(did)) { + if (chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); } } else { - if (usersToLoad.contains(lowerId)) { - usersToLoad.add(lowerId); + if (usersToLoad.contains(did)) { + usersToLoad.add(did); } } } @@ -7247,7 +7601,7 @@ public class MessagesStorage extends BaseController { } } - public void putSentFile(final String path, final TLObject file, final int type, String parent) { + public void putSentFile(String path, TLObject file, int type, String parent) { if (path == null || file == null || parent == null) { return; } @@ -7290,7 +7644,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateEncryptedChatSeq(final TLRPC.EncryptedChat chat, final boolean cleanup) { + public void updateEncryptedChatSeq(TLRPC.EncryptedChat chat, boolean cleanup) { if (chat == null) { return; } @@ -7306,8 +7660,8 @@ public class MessagesStorage extends BaseController { state.bindInteger(6, chat.id); state.step(); if (cleanup && chat.in_seq_no != 0) { - long did = ((long) chat.id) << 32; - database.executeFast(String.format(Locale.US, "DELETE FROM messages WHERE mid IN (SELECT m.mid FROM messages as m LEFT JOIN messages_seq as s ON m.mid = s.mid WHERE m.uid = %d AND m.date = 0 AND m.mid < 0 AND s.seq_out <= %d)", did, chat.in_seq_no)).stepThis().dispose(); + long did = DialogObject.getEncryptedChatId(chat.id); + database.executeFast(String.format(Locale.US, "DELETE FROM messages_v2 WHERE mid IN (SELECT m.mid FROM messages_v2 as m LEFT JOIN messages_seq as s ON m.mid = s.mid WHERE m.uid = %d AND m.date = 0 AND m.mid < 0 AND s.seq_out <= %d) AND uid = %d", did, chat.in_seq_no, did)).stepThis().dispose(); } } catch (Exception e) { FileLog.e(e); @@ -7319,7 +7673,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateEncryptedChatTTL(final TLRPC.EncryptedChat chat) { + public void updateEncryptedChatTTL(TLRPC.EncryptedChat chat) { if (chat == null) { return; } @@ -7340,7 +7694,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateEncryptedChatLayer(final TLRPC.EncryptedChat chat) { + public void updateEncryptedChatLayer(TLRPC.EncryptedChat chat) { if (chat == null) { return; } @@ -7361,7 +7715,7 @@ public class MessagesStorage extends BaseController { }); } - public void updateEncryptedChat(final TLRPC.EncryptedChat chat) { + public void updateEncryptedChat(TLRPC.EncryptedChat chat) { if (chat == null) { return; } @@ -7405,7 +7759,7 @@ public class MessagesStorage extends BaseController { state.bindByteBuffer(12, data4); state.bindByteBuffer(13, data5); state.bindInteger(14, chat.in_seq_no); - state.bindInteger(15, chat.admin_id); + state.bindLong(15, chat.admin_id); state.bindInteger(16, chat.mtproto_seq); state.bindInteger(17, chat.id); @@ -7443,12 +7797,12 @@ public class MessagesStorage extends BaseController { }); } - public boolean hasAuthMessage(final int date) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final boolean[] result = new boolean[1]; + public boolean hasAuthMessage(int date) { + CountDownLatch countDownLatch = new CountDownLatch(1); + boolean[] result = new boolean[1]; storageQueue.postRunnable(() -> { try { - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages WHERE uid = 777000 AND date = %d AND mid < 0 LIMIT 1", date)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE uid = 777000 AND date = %d AND mid < 0 LIMIT 1", date)); result[0] = cursor.next(); cursor.dispose(); } catch (Exception e) { @@ -7465,15 +7819,15 @@ public class MessagesStorage extends BaseController { return result[0]; } - public void getEncryptedChat(final int chat_id, final CountDownLatch countDownLatch, final ArrayList result) { + public void getEncryptedChat(long chatId, CountDownLatch countDownLatch, ArrayList result) { if (countDownLatch == null || result == null) { return; } storageQueue.postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); - getEncryptedChatsInternal("" + chat_id, encryptedChats, usersToLoad); + getEncryptedChatsInternal("" + chatId, encryptedChats, usersToLoad); if (!encryptedChats.isEmpty() && !usersToLoad.isEmpty()) { ArrayList users = new ArrayList<>(); getUsersInternal(TextUtils.join(",", usersToLoad), users); @@ -7490,7 +7844,7 @@ public class MessagesStorage extends BaseController { }); } - public void putEncryptedChat(final TLRPC.EncryptedChat chat, final TLRPC.User user, final TLRPC.Dialog dialog) { + public void putEncryptedChat(TLRPC.EncryptedChat chat, TLRPC.User user, TLRPC.Dialog dialog) { if (chat == null) { return; } @@ -7508,7 +7862,7 @@ public class MessagesStorage extends BaseController { chat.serializeToStream(data); state.bindInteger(1, chat.id); - state.bindInteger(2, user.id); + state.bindLong(2, user.id); state.bindString(3, formatUserSearchName(user)); state.bindByteBuffer(4, data); if (chat.a_or_b != null) { @@ -7536,7 +7890,7 @@ public class MessagesStorage extends BaseController { state.bindByteBuffer(15, data4); state.bindByteBuffer(16, data5); state.bindInteger(17, chat.in_seq_no); - state.bindInteger(18, chat.admin_id); + state.bindLong(18, chat.admin_id); state.bindInteger(19, chat.mtproto_seq); state.step(); @@ -7633,7 +7987,7 @@ public class MessagesStorage extends BaseController { state.requery(); NativeByteBuffer data = new NativeByteBuffer(user.getObjectSize()); user.serializeToStream(data); - state.bindInteger(1, user.id); + state.bindLong(1, user.id); state.bindString(2, formatUserSearchName(user)); if (user.status != null) { if (user.status instanceof TLRPC.TL_userStatusRecently) { @@ -7654,7 +8008,7 @@ public class MessagesStorage extends BaseController { state.dispose(); } - public void updateChatDefaultBannedRights(int chatId, TLRPC.TL_chatBannedRights rights, int version) { + public void updateChatDefaultBannedRights(long chatId, TLRPC.TL_chatBannedRights rights, int version) { if (rights == null || chatId == 0) { return; } @@ -7681,7 +8035,7 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize()); chat.serializeToStream(data); state.bindByteBuffer(1, data); - state.bindInteger(2, chat.id); + state.bindLong(2, chat.id); state.step(); data.reuse(); state.dispose(); @@ -7746,7 +8100,7 @@ public class MessagesStorage extends BaseController { chat.flags |= 131072; NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize()); chat.serializeToStream(data); - state.bindInteger(1, chat.id); + state.bindLong(1, chat.id); if (chat.title != null) { String name = chat.title.toLowerCase(); state.bindString(2, name); @@ -7807,7 +8161,7 @@ public class MessagesStorage extends BaseController { cursor.dispose(); } - public void getEncryptedChatsInternal(String chatsToLoad, ArrayList result, ArrayList usersToLoad) throws Exception { + public void getEncryptedChatsInternal(String chatsToLoad, ArrayList result, ArrayList usersToLoad) throws Exception { if (chatsToLoad == null || chatsToLoad.length() == 0 || result == null) { return; } @@ -7819,7 +8173,7 @@ public class MessagesStorage extends BaseController { TLRPC.EncryptedChat chat = TLRPC.EncryptedChat.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (chat != null) { - chat.user_id = cursor.intValue(1); + chat.user_id = cursor.longValue(1); if (usersToLoad != null && !usersToLoad.contains(chat.user_id)) { usersToLoad.add(chat.user_id); } @@ -7838,7 +8192,7 @@ public class MessagesStorage extends BaseController { chat.future_auth_key = cursor.byteArrayValue(12); chat.key_hash = cursor.byteArrayValue(13); chat.in_seq_no = cursor.intValue(14); - int admin_id = cursor.intValue(15); + long admin_id = cursor.longValue(15); if (admin_id != 0) { chat.admin_id = admin_id; } @@ -7853,7 +8207,7 @@ public class MessagesStorage extends BaseController { cursor.dispose(); } - private void putUsersAndChatsInternal(final ArrayList users, final ArrayList chats, final boolean withTransaction) { + private void putUsersAndChatsInternal(ArrayList users, ArrayList chats, boolean withTransaction) { try { if (withTransaction) { database.beginTransaction(); @@ -7868,7 +8222,7 @@ public class MessagesStorage extends BaseController { } } - public void putUsersAndChats(final ArrayList users, final ArrayList chats, final boolean withTransaction, boolean useQueue) { + public void putUsersAndChats(ArrayList users, ArrayList chats, boolean withTransaction, boolean useQueue) { if (users != null && users.isEmpty() && chats != null && chats.isEmpty()) { return; } @@ -7879,7 +8233,7 @@ public class MessagesStorage extends BaseController { } } - public void removeFromDownloadQueue(final long id, final int type, final boolean move) { + public void removeFromDownloadQueue(long id, int type, boolean move) { storageQueue.postRunnable(() -> { try { if (move) { @@ -7927,7 +8281,7 @@ public class MessagesStorage extends BaseController { } } - public void clearDownloadQueue(final int type) { + public void clearDownloadQueue(int type) { storageQueue.postRunnable(() -> { try { if (type == 0) { @@ -7941,10 +8295,10 @@ public class MessagesStorage extends BaseController { }); } - public void getDownloadQueue(final int type) { + public void getDownloadQueue(int type) { storageQueue.postRunnable(() -> { try { - final ArrayList objects = new ArrayList<>(); + ArrayList objects = new ArrayList<>(); SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, type, data, parent FROM download_queue WHERE type = %d ORDER BY date DESC LIMIT 3", type)); while (cursor.next()) { DownloadObject downloadObject = new DownloadObject(); @@ -7995,70 +8349,75 @@ public class MessagesStorage extends BaseController { return -1; } - public void putWebPages(final LongSparseArray webPages) { + public void putWebPages(LongSparseArray webPages) { if (isEmpty(webPages)) { return; } storageQueue.postRunnable(() -> { try { - final ArrayList messages = new ArrayList<>(); - for (int a = 0; a < webPages.size(); a++) { - SQLiteCursor cursor = database.queryFinalized("SELECT mid FROM webpage_pending WHERE id = " + webPages.keyAt(a)); - ArrayList mids = new ArrayList<>(); + ArrayList messages = new ArrayList<>(); + for (int a = 0, N = webPages.size(); a < N; a++) { + SQLiteCursor cursor = database.queryFinalized("SELECT mid, uid FROM webpage_pending_v2 WHERE id = " + webPages.keyAt(a)); + LongSparseArray> dialogs = new LongSparseArray<>(); while (cursor.next()) { - mids.add(cursor.longValue(0)); + long dialogId = cursor.longValue(1); + ArrayList mids = dialogs.get(dialogId); + if (mids == null) { + mids = new ArrayList<>(); + dialogs.put(dialogId, mids); + } + mids.add(cursor.intValue(0)); } cursor.dispose(); - if (mids.isEmpty()) { + if (dialogs.isEmpty()) { continue; } - cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data FROM messages WHERE mid IN (%s)", TextUtils.join(",", mids))); - while (cursor.next()) { - int mid = cursor.intValue(0); - NativeByteBuffer data = cursor.byteBufferValue(1); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - if (message.media instanceof TLRPC.TL_messageMediaWebPage) { - message.id = mid; - message.media.webpage = webPages.valueAt(a); - messages.add(message); + for (int b = 0, N2 = dialogs.size(); b < N2; b++) { + long dialogId = dialogs.keyAt(b); + ArrayList mids = dialogs.valueAt(b); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data FROM messages_v2 WHERE mid IN (%s) AND uid = %d", TextUtils.join(",", mids), dialogId)); + while (cursor.next()) { + int mid = cursor.intValue(0); + NativeByteBuffer data = cursor.byteBufferValue(1); + if (data != null) { + TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); + message.readAttachPath(data, getUserConfig().clientUserId); + data.reuse(); + if (message.media instanceof TLRPC.TL_messageMediaWebPage) { + message.id = mid; + message.media.webpage = webPages.valueAt(a); + messages.add(message); + } } } + cursor.dispose(); } - cursor.dispose(); } - //database.executeFast(String.format(Locale.US, "DELETE FROM webpage_pending WHERE id IN (%s)", ids)).stepThis().dispose(); - if (messages.isEmpty()) { return; } database.beginTransaction(); - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET data = ? WHERE mid = ?"); - SQLitePreparedStatement state2 = database.executeFast("UPDATE media_v2 SET data = ? WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET data = ? WHERE mid = ? AND uid = ?"); + SQLitePreparedStatement state2 = database.executeFast("UPDATE media_v3 SET data = ? WHERE mid = ? AND uid = ?"); for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - state.requery(); state.bindByteBuffer(1, data); - state.bindLong(2, messageId); + state.bindInteger(2, message.id); + state.bindLong(3, MessageObject.getDialogId(message)); state.step(); state2.requery(); state2.bindByteBuffer(1, data); - state2.bindLong(2, messageId); + state2.bindInteger(2, message.id); + state2.bindLong(3, MessageObject.getDialogId(message)); state2.step(); data.reuse(); @@ -8075,11 +8434,11 @@ public class MessagesStorage extends BaseController { }); } - public void overwriteChannel(final int channel_id, final TLRPC.TL_updates_channelDifferenceTooLong difference, final int newDialogType) { + public void overwriteChannel(long channelId, TLRPC.TL_updates_channelDifferenceTooLong difference, int newDialogType) { storageQueue.postRunnable(() -> { try { boolean checkInvite = false; - final long did = -channel_id; + long did = -channelId; int pinned = 0; SQLiteCursor cursor = database.queryFinalized("SELECT pinned FROM dialogs WHERE did = " + did); @@ -8094,10 +8453,10 @@ public class MessagesStorage extends BaseController { database.executeFast("DELETE FROM chat_pinned_count WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM chat_pinned_v2 WHERE uid = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose(); database.executeFast("UPDATE media_counts_v2 SET old = 1 WHERE uid = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM media_v2 WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM media_v3 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose(); getMediaDataController().clearBotKeyboard(did, null); @@ -8115,13 +8474,13 @@ public class MessagesStorage extends BaseController { dialogs.dialogs.add(dialog); putDialogsInternal(dialogs, 0); - updateDialogsWithDeletedMessages(new ArrayList<>(), null, false, channel_id); + updateDialogsWithDeletedMessages(-channelId, channelId, new ArrayList<>(), null, false); AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did, true, difference)); if (checkInvite) { if (newDialogType == 1) { - getMessagesController().checkChatInviter(channel_id, true); + getMessagesController().checkChatInviter(channelId, true); } else { - getMessagesController().generateJoinMessage(channel_id, false); + getMessagesController().generateJoinMessage(channelId, false); } } } catch (Exception e) { @@ -8130,7 +8489,7 @@ public class MessagesStorage extends BaseController { }); } - public void putChannelViews(final SparseArray channelViews, final SparseArray channelForwards, final SparseArray> channelReplies, boolean addReply, final boolean isChannel) { + public void putChannelViews(LongSparseArray channelViews, LongSparseArray channelForwards, LongSparseArray> channelReplies, boolean addReply) { if (isEmpty(channelViews) && isEmpty(channelForwards) && isEmpty(channelReplies)) { return; } @@ -8138,20 +8497,19 @@ public class MessagesStorage extends BaseController { try { database.beginTransaction(); if (!isEmpty(channelViews)) { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET media = max((SELECT media FROM messages WHERE mid = ?), ?) WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET media = max((SELECT media FROM messages_v2 WHERE mid = ? AND uid = ?), ?) WHERE mid = ? AND uid = ?"); for (int a = 0; a < channelViews.size(); a++) { - int peer = channelViews.keyAt(a); - SparseIntArray messages = channelViews.get(peer); - for (int b = 0; b < messages.size(); b++) { - int views = messages.get(messages.keyAt(b)); - long messageId = messages.keyAt(b); - if (isChannel) { - messageId |= ((long) -peer) << 32; - } + long peer = channelViews.keyAt(a); + SparseIntArray messages = channelViews.valueAt(a); + for (int b = 0, N = messages.size(); b < N; b++) { + int views = messages.valueAt(b); + int messageId = messages.keyAt(b); state.requery(); - state.bindLong(1, messageId); - state.bindInteger(2, views); - state.bindLong(3, messageId); + state.bindInteger(1, messageId); + state.bindLong(2, peer); + state.bindInteger(3, views); + state.bindInteger(4, messageId); + state.bindLong(5, peer); state.step(); } } @@ -8159,20 +8517,19 @@ public class MessagesStorage extends BaseController { } if (!isEmpty(channelForwards)) { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET forwards = max((SELECT forwards FROM messages WHERE mid = ?), ?) WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET forwards = max((SELECT forwards FROM messages_v2 WHERE mid = ? AND uid = ?), ?) WHERE mid = ? AND uid = ?"); for (int a = 0; a < channelForwards.size(); a++) { - int peer = channelForwards.keyAt(a); - SparseIntArray messages = channelForwards.get(peer); - for (int b = 0; b < messages.size(); b++) { - int forwards = messages.get(messages.keyAt(b)); - long messageId = messages.keyAt(b); - if (isChannel) { - messageId |= ((long) -peer) << 32; - } + long peer = channelForwards.keyAt(a); + SparseIntArray messages = channelForwards.valueAt(a); + for (int b = 0, N = messages.size(); b < N; b++) { + int forwards = messages.valueAt(b); + int messageId = messages.keyAt(b); state.requery(); - state.bindLong(1, messageId); - state.bindInteger(2, forwards); - state.bindLong(3, messageId); + state.bindInteger(1, messageId); + state.bindLong(2, peer); + state.bindInteger(3, forwards); + state.bindInteger(4, messageId); + state.bindLong(5, peer); state.step(); } } @@ -8180,22 +8537,19 @@ public class MessagesStorage extends BaseController { } if (!isEmpty(channelReplies)) { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET replies_data = ? WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET replies_data = ? WHERE mid = ? AND uid = ?"); for (int a = 0; a < channelReplies.size(); a++) { - int peer = channelReplies.keyAt(a); - SparseArray messages = channelReplies.get(peer); - for (int b = 0; b < messages.size(); b++) { - long messageId = messages.keyAt(b); - if (isChannel) { - messageId |= ((long) -peer) << 32; - } + long peer = channelReplies.keyAt(a); + SparseArray messages = channelReplies.valueAt(a); + for (int b = 0, N3 = messages.size(); b < N3; b++) { + int messageId = messages.keyAt(b); boolean messageExists; - TLRPC.TL_messageReplies currentReplies = null; - SQLiteCursor cursor = database.queryFinalized("SELECT replies_data FROM messages WHERE mid = " + messageId); + TLRPC.MessageReplies currentReplies = null; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT replies_data FROM messages_v2 WHERE mid = %d AND uid = %d", messageId, peer)); if (messageExists = cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { - currentReplies = TLRPC.TL_messageReplies.TLdeserialize(data, data.readInt32(false), false); + currentReplies = TLRPC.MessageReplies.TLdeserialize(data, data.readInt32(false), false); data.reuse(); } } @@ -8203,7 +8557,7 @@ public class MessagesStorage extends BaseController { if (!messageExists) { continue; } - TLRPC.TL_messageReplies replies = messages.get(messages.keyAt(b)); + TLRPC.MessageReplies replies = messages.get(messages.keyAt(b)); if (!addReply && currentReplies != null && currentReplies.replies_pts != 0 && replies.replies_pts <= currentReplies.replies_pts && replies.read_max_id <= currentReplies.read_max_id && replies.max_id <= currentReplies.max_id) { continue; } @@ -8214,9 +8568,9 @@ public class MessagesStorage extends BaseController { } currentReplies.replies += replies.replies; for (int c = 0, N = replies.recent_repliers.size(); c < N; c++) { - int id = MessageObject.getPeerId(replies.recent_repliers.get(c)); + long id = MessageObject.getPeerId(replies.recent_repliers.get(c)); for (int d = 0, N2 = currentReplies.recent_repliers.size(); d < N2; d++) { - int id2 = MessageObject.getPeerId(currentReplies.recent_repliers.get(d)); + long id2 = MessageObject.getPeerId(currentReplies.recent_repliers.get(d)); if (id == id2) { currentReplies.recent_repliers.remove(d); d--; @@ -8237,7 +8591,8 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(replies.getObjectSize()); replies.serializeToStream(data); state.bindByteBuffer(1, data); - state.bindLong(2, messageId); + state.bindInteger(2, messageId); + state.bindLong(3, peer); state.step(); data.reuse(); } @@ -8251,16 +8606,16 @@ public class MessagesStorage extends BaseController { }); } - private void updateRepliesMaxReadIdInternal(int chatId, int mid, int readMaxId) { + private void updateRepliesMaxReadIdInternal(long chatId, int mid, int readMaxId) { try { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET replies_data = ? WHERE mid = ?"); - long messageId = mid | ((long) chatId) << 32; - TLRPC.TL_messageReplies currentReplies = null; - SQLiteCursor cursor = database.queryFinalized("SELECT replies_data FROM messages WHERE mid = " + messageId); + long dialogId = -chatId; + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET replies_data = ? WHERE mid = ? AND uid = ?"); + TLRPC.MessageReplies currentReplies = null; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT replies_data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, dialogId)); if (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { - currentReplies = TLRPC.TL_messageReplies.TLdeserialize(data, data.readInt32(false), false); + currentReplies = TLRPC.MessageReplies.TLdeserialize(data, data.readInt32(false), false); data.reuse(); } } @@ -8271,7 +8626,8 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(currentReplies.getObjectSize()); currentReplies.serializeToStream(data); state.bindByteBuffer(1, data); - state.bindLong(2, messageId); + state.bindInteger(2, mid); + state.bindLong(3, dialogId); state.step(); data.reuse(); } @@ -8281,7 +8637,7 @@ public class MessagesStorage extends BaseController { } } - public void updateRepliesMaxReadId(int chatId, int mid, int readMaxId, boolean useQueue) { + public void updateRepliesMaxReadId(long chatId, int mid, int readMaxId, boolean useQueue) { if (useQueue) { storageQueue.postRunnable(() -> updateRepliesMaxReadIdInternal(chatId, mid, readMaxId)); } else { @@ -8289,17 +8645,16 @@ public class MessagesStorage extends BaseController { } } - public void updateRepliesCount(int chatId, int mid, ArrayList repliers, int maxId, int count) { + public void updateRepliesCount(long chatId, int mid, ArrayList repliers, int maxId, int count) { storageQueue.postRunnable(() -> { try { - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET replies_data = ? WHERE mid = ?"); - long messageId = mid | ((long) chatId) << 32; - TLRPC.TL_messageReplies currentReplies = null; - SQLiteCursor cursor = database.queryFinalized("SELECT replies_data FROM messages WHERE mid = " + messageId); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET replies_data = ? WHERE mid = ? AND uid = ?"); + TLRPC.MessageReplies currentReplies = null; + SQLiteCursor cursor = database.queryFinalized(String.format("SELECT replies_data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, -chatId)); if (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(0); if (data != null) { - currentReplies = TLRPC.TL_messageReplies.TLdeserialize(data, data.readInt32(false), false); + currentReplies = TLRPC.MessageReplies.TLdeserialize(data, data.readInt32(false), false); data.reuse(); } } @@ -8320,7 +8675,8 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(currentReplies.getObjectSize()); currentReplies.serializeToStream(data); state.bindByteBuffer(1, data); - state.bindLong(2, messageId); + state.bindInteger(2, mid); + state.bindLong(3, -chatId); state.step(); data.reuse(); } @@ -8339,7 +8695,7 @@ public class MessagesStorage extends BaseController { Utilities.stageQueue.postRunnable(() -> { try { database.beginTransaction(); - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET imp = ? WHERE mid = ?"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET imp = ? WHERE mid = ? AND uid = ?"); for (int a = 0, N = messages.size(); a < N; a++) { TLRPC.Message message = messages.get(a); state.requery(); @@ -8350,7 +8706,8 @@ public class MessagesStorage extends BaseController { flags |= 2; } state.bindInteger(1, flags); - state.bindLong(2, message.id); + state.bindInteger(2, message.id); + state.bindLong(3, MessageObject.getDialogId(message)); state.step(); } state.dispose(); @@ -8362,15 +8719,15 @@ public class MessagesStorage extends BaseController { } - private void putMessagesInternal(final ArrayList messages, final boolean withTransaction, final boolean doNotUpdateDialogDate, final int downloadMask, boolean ifNoLastMessage, boolean scheduled) { + private void putMessagesInternal(ArrayList messages, boolean withTransaction, boolean doNotUpdateDialogDate, int downloadMask, boolean ifNoLastMessage, boolean scheduled) { try { if (scheduled) { if (withTransaction) { database.beginTransaction(); } - SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages VALUES(?, ?, ?, ?, ?, ?, NULL)"); - SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms VALUES(?, ?)"); + SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, NULL)"); + SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)"); ArrayList dialogsToUpdate = new ArrayList<>(); for (int a = 0; a < messages.size(); a++) { @@ -8381,19 +8738,16 @@ public class MessagesStorage extends BaseController { fixUnsupportedMedia(message); state_messages.requery(); - long messageId = message.id; + int messageId = message.id; if (message.local_id != 0) { messageId = message.local_id; } - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); long did = MessageObject.getDialogId(message); - state_messages.bindLong(1, messageId); + state_messages.bindInteger(1, messageId); state_messages.bindLong(2, did); state_messages.bindInteger(3, message.send_state); state_messages.bindInteger(4, message.date); @@ -8404,7 +8758,8 @@ public class MessagesStorage extends BaseController { if (message.random_id != 0) { state_randoms.requery(); state_randoms.bindLong(1, message.random_id); - state_randoms.bindLong(2, messageId); + state_randoms.bindInteger(2, messageId); + state_randoms.bindLong(3, message.dialog_id); state_randoms.step(); } @@ -8443,27 +8798,27 @@ public class MessagesStorage extends BaseController { database.beginTransaction(); } LongSparseArray messagesMap = new LongSparseArray<>(); - LongSparseArray messagesCounts = new LongSparseArray<>(); - LongSparseArray newMessagesCounts = new LongSparseArray<>(); - LongSparseArray newMentionsCounts = new LongSparseArray<>(); - LongSparseArray mentionCounts = new LongSparseArray<>(); - SparseArray> mediaCounts = null; + LongSparseIntArray messagesCounts = new LongSparseIntArray(); + LongSparseIntArray newMessagesCounts = new LongSparseIntArray(); + LongSparseIntArray newMentionsCounts = new LongSparseIntArray(); + LongSparseIntArray mentionCounts = new LongSparseIntArray(); + SparseArray mediaCounts = null; LongSparseArray botKeyboards = new LongSparseArray<>(); - LongSparseArray messagesMediaIdsMap = null; - LongSparseArray mediaTypesChange = null; - StringBuilder messageMediaIds = null; - LongSparseArray mediaTypes = null; - StringBuilder messageIds = new StringBuilder(); - LongSparseArray dialogsReadMax = new LongSparseArray<>(); - LongSparseArray messagesIdsMap = new LongSparseArray<>(); - LongSparseArray mentionsIdsMap = new LongSparseArray<>(); + LongSparseArray> dialogMessagesMediaIdsMap = null; + LongSparseArray dialogsMediaTypesChange = null; + LongSparseArray mediaIdsMap = null; + LongSparseArray dialogMediaTypes = null; + LongSparseArray messageIdsMap = new LongSparseArray<>(); + LongSparseIntArray dialogsReadMax = new LongSparseIntArray(); + LongSparseArray> dialogMessagesIdsMap = new LongSparseArray<>(); + LongSparseArray> dialogMentionsIdsMap = new LongSparseArray<>(); - SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)"); + SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state_media = null; - SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms VALUES(?, ?)"); + SQLitePreparedStatement state_randoms = database.executeFast("REPLACE INTO randoms_v2 VALUES(?, ?, ?)"); SQLitePreparedStatement state_download = database.executeFast("REPLACE INTO download_queue VALUES(?, ?, ?, ?, ?)"); - SQLitePreparedStatement state_webpage = database.executeFast("REPLACE INTO webpage_pending VALUES(?, ?)"); + SQLitePreparedStatement state_webpage = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)"); SQLitePreparedStatement state_polls = null; SQLitePreparedStatement state_tasks = null; int minDeleteTime = Integer.MAX_VALUE; @@ -8471,20 +8826,20 @@ public class MessagesStorage extends BaseController { for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); - long messageId = message.id; - if (message.dialog_id == 0) { - MessageObject.getDialogId(message); - } - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } + int messageId = message.id; + MessageObject.getDialogId(message); if (message.mentioned && message.media_unread) { - mentionsIdsMap.put(messageId, message.dialog_id); + ArrayList ids = dialogMentionsIdsMap.get(message.dialog_id); + if (ids == null) { + ids = new ArrayList<>(); + dialogMentionsIdsMap.put(message.dialog_id, ids); + } + ids.add(messageId); } if (!(message.action instanceof TLRPC.TL_messageActionHistoryClear) && (!MessageObject.isOut(message) || message.from_scheduled) && (message.id > 0 || MessageObject.isUnread(message))) { - Integer currentMaxId = dialogsReadMax.get(message.dialog_id); - if (currentMaxId == null) { + int currentMaxId = dialogsReadMax.get(message.dialog_id, -1); + if (currentMaxId == -1) { SQLiteCursor cursor = database.queryFinalized("SELECT inbox_max FROM dialogs WHERE did = " + message.dialog_id); if (cursor.next()) { currentMaxId = cursor.intValue(0); @@ -8495,24 +8850,52 @@ public class MessagesStorage extends BaseController { dialogsReadMax.put(message.dialog_id, currentMaxId); } if (message.id < 0 || currentMaxId < message.id) { + StringBuilder messageIds = messageIdsMap.get(message.dialog_id); + if (messageIds == null) { + messageIds = new StringBuilder(); + messageIdsMap.put(message.dialog_id, messageIds); + } if (messageIds.length() > 0) { messageIds.append(","); } messageIds.append(messageId); - messagesIdsMap.put(messageId, message.dialog_id); + + ArrayList ids = dialogMessagesIdsMap.get(message.dialog_id); + if (ids == null) { + ids = new ArrayList<>(); + dialogMessagesIdsMap.put(message.dialog_id, ids); + } + ids.add(messageId); } } if (MediaDataController.canAddMessageToMedia(message)) { + if (mediaIdsMap == null) { + mediaIdsMap = new LongSparseArray<>(); + dialogMessagesMediaIdsMap = new LongSparseArray<>(); + dialogMediaTypes = new LongSparseArray<>(); + } + StringBuilder messageMediaIds = mediaIdsMap.get(message.dialog_id); if (messageMediaIds == null) { messageMediaIds = new StringBuilder(); - messagesMediaIdsMap = new LongSparseArray<>(); - mediaTypes = new LongSparseArray<>(); + mediaIdsMap.put(message.dialog_id, messageMediaIds); } if (messageMediaIds.length() > 0) { messageMediaIds.append(","); } messageMediaIds.append(messageId); - messagesMediaIdsMap.put(messageId, message.dialog_id); + + ArrayList ids = dialogMessagesMediaIdsMap.get(message.dialog_id); + if (ids == null) { + ids = new ArrayList<>(); + dialogMessagesMediaIdsMap.put(message.dialog_id, ids); + } + ids.add(messageId); + + SparseIntArray mediaTypes = dialogMediaTypes.get(message.dialog_id); + if (mediaTypes == null) { + mediaTypes = new SparseIntArray(); + dialogMediaTypes.put(message.dialog_id, mediaTypes); + } mediaTypes.put(messageId, MediaDataController.getMediaType(message)); } if (isValidKeyboardToSave(message)) { @@ -8527,86 +8910,112 @@ public class MessagesStorage extends BaseController { getMediaDataController().putBotKeyboard(botKeyboards.keyAt(a), botKeyboards.valueAt(a)); } - if (messageMediaIds != null) { - SQLiteCursor cursor = database.queryFinalized("SELECT mid, type FROM media_v2 WHERE mid IN(" + messageMediaIds.toString() + ")"); - while (cursor.next()) { - long mid = cursor.longValue(0); - int type = cursor.intValue(1); - if (type == mediaTypes.get(mid)) { - messagesMediaIdsMap.remove(mid); - } else { - if (mediaTypesChange == null) { - mediaTypesChange = new LongSparseArray<>(); + if (mediaIdsMap != null) { + for (int b = 0, N2 = mediaIdsMap.size(); b < N2; b++) { + long dialogId = mediaIdsMap.keyAt(b); + StringBuilder messageMediaIds = mediaIdsMap.valueAt(b); + SparseIntArray mediaTypes = dialogMediaTypes.get(dialogId); + ArrayList messagesMediaIdsMap = dialogMessagesMediaIdsMap.get(dialogId); + SparseIntArray mediaTypesChange = null; + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, type FROM media_v3 WHERE mid IN(%s) AND uid = %d", messageMediaIds.toString(), dialogId)); + while (cursor.next()) { + int mid = cursor.intValue(0); + int type = cursor.intValue(1); + if (type == mediaTypes.get(mid)) { + messagesMediaIdsMap.remove((Integer) mid); + } else { + if (mediaTypesChange == null) { + if (dialogsMediaTypesChange == null) { + dialogsMediaTypesChange = new LongSparseArray<>(); + } + mediaTypesChange = dialogsMediaTypesChange.get(dialogId); + if (mediaTypesChange == null) { + mediaTypesChange = new SparseIntArray(); + dialogsMediaTypesChange.put(dialogId, mediaTypesChange); + } + } + mediaTypesChange.put(mid, type); } - mediaTypesChange.put(mid, type); } - } - cursor.dispose(); - mediaCounts = new SparseArray<>(); - for (int a = 0; a < messagesMediaIdsMap.size(); a++) { - long key = messagesMediaIdsMap.keyAt(a); - long value = messagesMediaIdsMap.valueAt(a); - Integer type = mediaTypes.get(key); - LongSparseArray counts = mediaCounts.get(type); - Integer count; - if (counts == null) { - counts = new LongSparseArray<>(); - count = 0; - mediaCounts.put(type, counts); - } else { - count = counts.get(value); + cursor.dispose(); + if (mediaCounts == null) { + mediaCounts = new SparseArray<>(); } - if (count == null) { - count = 0; - } - count++; - counts.put(value, count); - if (mediaTypesChange != null) { - int previousType = mediaTypesChange.get(key, -1); - if (previousType >= 0) { - counts = mediaCounts.get(previousType); - if (counts == null) { - counts = new LongSparseArray<>(); - count = 0; - mediaCounts.put(previousType, counts); - } else { - count = counts.get(value); + + for (int a = 0, N = messagesMediaIdsMap.size(); a < N; a++) { + int key = messagesMediaIdsMap.get(a); + int type = mediaTypes.get(key); + LongSparseIntArray counts = mediaCounts.get(type); + int count; + if (counts == null) { + counts = new LongSparseIntArray(); + mediaCounts.put(type, counts); + count = 0; + } else { + count = counts.get(dialogId, Integer.MIN_VALUE); + } + if (count == Integer.MIN_VALUE) { + count = 0; + } + count++; + counts.put(dialogId, count); + if (mediaTypesChange != null) { + int previousType = mediaTypesChange.get(key, -1); + if (previousType >= 0) { + counts = mediaCounts.get(previousType); + if (counts == null) { + counts = new LongSparseIntArray(); + count = 0; + mediaCounts.put(previousType, counts); + } else { + count = counts.get(dialogId, Integer.MIN_VALUE); + } + if (count == Integer.MIN_VALUE) { + count = 0; + } + count--; + counts.put(dialogId, count); } - if (count == null) { - count = 0; - } - count--; - counts.put(value, count); } } } } - if (messageIds.length() > 0) { - SQLiteCursor cursor = database.queryFinalized("SELECT mid FROM messages WHERE mid IN(" + messageIds.toString() + ")"); - while (cursor.next()) { - long mid = cursor.longValue(0); - messagesIdsMap.remove(mid); - mentionsIdsMap.remove(mid); - } - cursor.dispose(); - for (int a = 0; a < messagesIdsMap.size(); a++) { - long dialog_id = messagesIdsMap.valueAt(a); - Integer count = messagesCounts.get(dialog_id); - if (count == null) { - count = 0; + if (!messageIdsMap.isEmpty()) { + for (int b = 0, N2 = messageIdsMap.size(); b < N2; b++) { + long dialogId = messageIdsMap.keyAt(b); + StringBuilder messageIds = messageIdsMap.valueAt(b); + ArrayList messagesIdsMap = dialogMessagesIdsMap.get(dialogId); + ArrayList mentionsIdsMap = dialogMentionsIdsMap.get(dialogId); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE mid IN(%s) AND uid = %d", messageIds.toString(), dialogId)); + while (cursor.next()) { + Integer mid = cursor.intValue(0); + if (messagesIdsMap != null) { + messagesIdsMap.remove(mid); + } + if (mentionsIdsMap != null) { + mentionsIdsMap.remove(mid); + } } - count++; - messagesCounts.put(dialog_id, count); - } - for (int a = 0; a < mentionsIdsMap.size(); a++) { - long dialog_id = mentionsIdsMap.valueAt(a); - Integer count = mentionCounts.get(dialog_id); - if (count == null) { - count = 0; + cursor.dispose(); + + if (messagesCounts != null) { + int count = messagesCounts.get(dialogId, -1); + if (count < 0) { + count = 0; + } + count += messagesIdsMap.size(); + messagesCounts.put(dialogId, count); + } + + if (mentionsIdsMap != null) { + int count = mentionCounts.get(dialogId, -1); + if (count < 0) { + count = 0; + } + count += mentionsIdsMap.size(); + mentionCounts.put(dialogId, count); } - count++; - mentionCounts.put(dialog_id, count); } } @@ -8616,13 +9025,10 @@ public class MessagesStorage extends BaseController { fixUnsupportedMedia(message); state_messages.requery(); - long messageId = message.id; + int messageId = message.id; if (message.local_id != 0) { messageId = message.local_id; } - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); @@ -8631,7 +9037,7 @@ public class MessagesStorage extends BaseController { if (message.action instanceof TLRPC.TL_messageEncryptedAction && !(message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL || message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages)) { updateDialog = false; } else if (message.out) { - SQLiteCursor cursor = database.queryFinalized("SELECT mid FROM messages WHERE mid = " + messageId); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages_v2 WHERE mid = %d AND uid = %d", messageId, message.dialog_id)); if (cursor.next()) { updateDialog = false; } @@ -8645,7 +9051,7 @@ public class MessagesStorage extends BaseController { } } - state_messages.bindLong(1, messageId); + state_messages.bindInteger(1, messageId); state_messages.bindLong(2, message.dialog_id); state_messages.bindInteger(3, MessageObject.getUnreadFlags(message)); state_messages.bindInteger(4, message.send_state); @@ -8680,21 +9086,23 @@ public class MessagesStorage extends BaseController { } else { state_messages.bindInteger(14, 0); } + state_messages.bindLong(15, MessageObject.getChannelId(message)); state_messages.step(); if (message.random_id != 0) { state_randoms.requery(); state_randoms.bindLong(1, message.random_id); - state_randoms.bindLong(2, messageId); + state_randoms.bindInteger(2, messageId); + state_randoms.bindLong(3, message.dialog_id); state_randoms.step(); } if (MediaDataController.canAddMessageToMedia(message)) { if (state_media == null) { - state_media = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); + state_media = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); } state_media.requery(); - state_media.bindLong(1, messageId); + state_media.bindInteger(1, messageId); state_media.bindLong(2, message.dialog_id); state_media.bindInteger(3, message.date); state_media.bindInteger(4, MediaDataController.getMediaType(message)); @@ -8704,29 +9112,32 @@ public class MessagesStorage extends BaseController { if (message.ttl_period != 0 && message.id > 0) { if (state_tasks == null) { - state_tasks = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)"); + state_tasks = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); } state_tasks.requery(); - state_tasks.bindLong(1, messageId); - state_tasks.bindInteger(2, message.date + message.ttl_period); - state_tasks.bindInteger(3, 0); + state_tasks.bindInteger(1, messageId); + state_tasks.bindLong(2, message.dialog_id); + state_tasks.bindInteger(3, message.date + message.ttl_period); + state_tasks.bindInteger(4, 0); state_tasks.step(); minDeleteTime = Math.min(minDeleteTime, message.date + message.ttl_period); } if (message.media instanceof TLRPC.TL_messageMediaPoll) { if (state_polls == null) { - state_polls = database.executeFast("REPLACE INTO polls VALUES(?, ?)"); + state_polls = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)"); } TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.media; state_polls.requery(); - state_polls.bindLong(1, messageId); - state_polls.bindLong(2, mediaPoll.poll.id); + state_polls.bindInteger(1, messageId); + state_polls.bindLong(2, message.dialog_id); + state_polls.bindLong(3, mediaPoll.poll.id); state_polls.step(); } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { state_webpage.requery(); state_webpage.bindLong(1, message.media.webpage.id); - state_webpage.bindLong(2, messageId); + state_webpage.bindInteger(2, messageId); + state_webpage.bindLong(3, message.dialog_id); state_webpage.step(); } @@ -8805,7 +9216,7 @@ public class MessagesStorage extends BaseController { } if (state_tasks != null) { state_tasks.dispose(); - getMessagesController().didAddedNewTask(minDeleteTime, null); + getMessagesController().didAddedNewTask(minDeleteTime, 0, null); } if (state_polls != null) { state_polls.dispose(); @@ -8825,10 +9236,7 @@ public class MessagesStorage extends BaseController { } TLRPC.Message message = messagesMap.valueAt(a); - int channelId = 0; - if (message != null) { - channelId = message.peer_id.channel_id; - } + long channelId = MessageObject.getChannelId(message); SQLiteCursor cursor = database.queryFinalized("SELECT date, unread_count, last_mid, unread_count_i FROM dialogs WHERE did = " + key); int dialog_date = 0; @@ -8846,28 +9254,24 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); - Integer mentions_count = mentionCounts.get(key); - Integer unread_count = messagesCounts.get(key); - if (unread_count == null) { + int mentions_count = mentionCounts.get(key, -1); + int unread_count = messagesCounts.get(key, -1); + if (unread_count == -1) { unread_count = 0; } else { messagesCounts.put(key, unread_count + old_unread_count); } - if (mentions_count == null) { + if (mentions_count == -1) { mentions_count = 0; } else { mentionCounts.put(key, mentions_count + old_mentions_count); } - long messageId = message != null ? message.id : last_mid; + int messageId = message != null ? message.id : last_mid; if (message != null) { if (message.local_id != 0) { messageId = message.local_id; } } - - if (channelId != 0) { - messageId |= ((long) channelId) << 32; - } if (old_unread_count == 0 && unread_count != 0) { newMessagesCounts.put(key, unread_count); } @@ -8880,7 +9284,7 @@ public class MessagesStorage extends BaseController { state_dialogs_update.requery(); state_dialogs_update.bindInteger(1, message != null && (!doNotUpdateDialogDate || dialog_date == 0) ? message.date : dialog_date); state_dialogs_update.bindInteger(2, old_unread_count + unread_count); - state_dialogs_update.bindLong(3, messageId); + state_dialogs_update.bindInteger(3, messageId); state_dialogs_update.bindInteger(4, old_mentions_count + mentions_count); state_dialogs_update.bindLong(5, key); state_dialogs_update.step(); @@ -8889,7 +9293,7 @@ public class MessagesStorage extends BaseController { state_dialogs_replace.bindLong(1, key); state_dialogs_replace.bindInteger(2, message != null && (!doNotUpdateDialogDate || dialog_date == 0) ? message.date : dialog_date); state_dialogs_replace.bindInteger(3, old_unread_count + unread_count); - state_dialogs_replace.bindLong(4, messageId); + state_dialogs_replace.bindInteger(4, messageId); state_dialogs_replace.bindInteger(5, 0); state_dialogs_replace.bindInteger(6, 0); state_dialogs_replace.bindLong(7, 0); @@ -8909,12 +9313,11 @@ public class MessagesStorage extends BaseController { if (mediaCounts != null) { state_randoms = database.executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?, ?)"); - for (int a = 0; a < mediaCounts.size(); a++) { + for (int a = 0, N = mediaCounts.size(); a < N; a++) { int type = mediaCounts.keyAt(a); - LongSparseArray value = mediaCounts.valueAt(a); - for (int b = 0; b < value.size(); b++) { + LongSparseIntArray value = mediaCounts.valueAt(a); + for (int b = 0, N2 = value.size(); b < N2; b++) { long uid = value.keyAt(b); - int lower_part = (int) uid; int count = -1; int old = 0; SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type)); @@ -8943,7 +9346,7 @@ public class MessagesStorage extends BaseController { getMessagesController().processDialogsUpdateRead(messagesCounts, mentionCounts); if (downloadMediaMask != 0) { - final int downloadMediaMaskFinal = downloadMediaMask; + int downloadMediaMaskFinal = downloadMediaMask; AndroidUtilities.runOnUIThread(() -> getDownloadController().newDownloadObjectsAvailable(downloadMediaMaskFinal)); } updateWidgets(dids); @@ -8953,11 +9356,11 @@ public class MessagesStorage extends BaseController { } } - public void putMessages(final ArrayList messages, final boolean withTransaction, boolean useQueue, final boolean doNotUpdateDialogDate, final int downloadMask, boolean scheduled) { + public void putMessages(ArrayList messages, boolean withTransaction, boolean useQueue, boolean doNotUpdateDialogDate, int downloadMask, boolean scheduled) { putMessages(messages, withTransaction, useQueue, doNotUpdateDialogDate, downloadMask, false, scheduled); } - public void putMessages(final ArrayList messages, final boolean withTransaction, boolean useQueue, final boolean doNotUpdateDialogDate, final int downloadMask, final boolean ifNoLastMessage, boolean scheduled) { + public void putMessages(ArrayList messages, boolean withTransaction, boolean useQueue, boolean doNotUpdateDialogDate, int downloadMask, boolean ifNoLastMessage, boolean scheduled) { if (messages.size() == 0) { return; } @@ -8968,17 +9371,14 @@ public class MessagesStorage extends BaseController { } } - public void markMessageAsSendError(final TLRPC.Message message, boolean scheduled) { + public void markMessageAsSendError(TLRPC.Message message, boolean scheduled) { storageQueue.postRunnable(() -> { try { long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } if (scheduled) { - database.executeFast("UPDATE scheduled_messages SET send_state = 2 WHERE mid = " + messageId).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE scheduled_messages_v2 SET send_state = 2 WHERE mid = %d AND uid = %d", messageId, MessageObject.getDialogId(message))).stepThis().dispose(); } else { - database.executeFast("UPDATE messages SET send_state = 2 WHERE mid = " + messageId).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET send_state = 2 WHERE mid = %d AND uid = %d", messageId, MessageObject.getDialogId(message))).stepThis().dispose(); } } catch (Exception e) { FileLog.e(e); @@ -8986,7 +9386,7 @@ public class MessagesStorage extends BaseController { }); } - public void setMessageSeq(final int mid, final int seq_in, final int seq_out) { + public void setMessageSeq(int mid, int seq_in, int seq_out) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages_seq VALUES(?, ?, ?)"); @@ -9002,16 +9402,16 @@ public class MessagesStorage extends BaseController { }); } - private long[] updateMessageStateAndIdInternal(long random_id, Long _oldId, int newId, int date, int channelId, int scheduled) { + private long[] updateMessageStateAndIdInternal(long randomId, long dialogId, Integer _oldId, int newId, int date, int scheduled) { SQLiteCursor cursor = null; - long oldMessageId; - long newMessageId = newId; + int oldMessageId; if (_oldId == null) { try { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM randoms WHERE random_id = %d LIMIT 1", random_id)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, uid FROM randoms_v2 WHERE random_id = %d LIMIT 1", randomId)); if (cursor.next()) { - _oldId = cursor.longValue(0); + _oldId = cursor.intValue(0); + dialogId = cursor.longValue(1); } } catch (Exception e) { FileLog.e(e); @@ -9023,22 +9423,15 @@ public class MessagesStorage extends BaseController { if (_oldId == null) { return null; } - if (channelId == 0) { - channelId = (int) (_oldId >> 32); - } } oldMessageId = _oldId; - if (channelId != 0) { - oldMessageId |= ((long) channelId) << 32; - newMessageId |= ((long) channelId) << 32; - } if (_oldId < 0 && scheduled == 1) { SQLitePreparedStatement state = null; try { - state = database.executeFast("UPDATE randoms SET mid = ? WHERE random_id = ? and mid = ?"); - state.bindLong(1, newMessageId); - state.bindLong(2, random_id); - state.bindLong(3, oldMessageId); + state = database.executeFast("UPDATE randoms_v2 SET mid = ? WHERE random_id = ? AND mid = ?"); + state.bindInteger(1, newId); + state.bindLong(2, randomId); + state.bindInteger(3, oldMessageId); state.step(); } catch (Exception e) { FileLog.e(e); @@ -9049,18 +9442,19 @@ public class MessagesStorage extends BaseController { } } else if (_oldId > 0) { TLRPC.TL_updateDeleteScheduledMessages update = new TLRPC.TL_updateDeleteScheduledMessages(); - update.messages.add((int) oldMessageId); - if (channelId != 0) { + update.messages.add(oldMessageId); + if (DialogObject.isChatDialog(dialogId)) { update.peer = new TLRPC.TL_peerChannel(); - update.peer.channel_id = channelId; + update.peer.channel_id = -dialogId; } else { update.peer = new TLRPC.TL_peerUser(); + update.peer.user_id = dialogId; } TLRPC.TL_updates updates = new TLRPC.TL_updates(); updates.updates.add(update); Utilities.stageQueue.postRunnable(() -> getMessagesController().processUpdates(updates, false)); try { - database.executeFast(String.format(Locale.US, "DELETE FROM randoms WHERE random_id = %d AND mid = %d", random_id, _oldId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM randoms WHERE random_id = %d AND mid = %d AND uid = %d", randomId, _oldId, dialogId)).stepThis().dispose(); } catch (Exception e) { FileLog.e(e); } @@ -9070,7 +9464,7 @@ public class MessagesStorage extends BaseController { long did = 0; if (scheduled == -1 || scheduled == 0) { try { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM messages WHERE mid = %d LIMIT 1", oldMessageId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM messages_v2 WHERE mid = %d LIMIT 1", oldMessageId)); if (cursor.next()) { did = cursor.longValue(0); scheduled = 0; @@ -9086,7 +9480,7 @@ public class MessagesStorage extends BaseController { if (scheduled == -1 || scheduled == 1) { try { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM scheduled_messages WHERE mid = %d LIMIT 1", oldMessageId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM scheduled_messages_v2 WHERE mid = %d LIMIT 1", oldMessageId)); if (cursor.next()) { did = cursor.longValue(0); scheduled = 1; @@ -9104,15 +9498,16 @@ public class MessagesStorage extends BaseController { return null; } SQLitePreparedStatement state = null; - if (oldMessageId == newMessageId && date != 0) { + if (oldMessageId == newId && date != 0) { try { if (scheduled == 0) { - state = database.executeFast("UPDATE messages SET send_state = 0, date = ? WHERE mid = ?"); + state = database.executeFast("UPDATE messages_v2 SET send_state = 0, date = ? WHERE mid = ? AND uid = ?"); } else { - state = database.executeFast("UPDATE scheduled_messages SET send_state = 0, date = ? WHERE mid = ?"); + state = database.executeFast("UPDATE scheduled_messages_v2 SET send_state = 0, date = ? WHERE mid = ? AND uid = ?"); } state.bindInteger(1, date); - state.bindLong(2, newMessageId); + state.bindInteger(2, newId); + state.bindLong(3, did); state.step(); } catch (Exception e) { FileLog.e(e); @@ -9125,13 +9520,14 @@ public class MessagesStorage extends BaseController { } else { if (scheduled == 0) { try { - state = database.executeFast("UPDATE messages SET mid = ?, send_state = 0 WHERE mid = ?"); - state.bindLong(1, newMessageId); - state.bindLong(2, oldMessageId); + state = database.executeFast("UPDATE messages_v2 SET mid = ?, send_state = 0 WHERE mid = ? AND uid = ?"); + state.bindInteger(1, newId); + state.bindInteger(2, oldMessageId); + state.bindLong(3, did); state.step(); } catch (Exception e) { try { - database.executeFast(String.format(Locale.US, "DELETE FROM messages WHERE mid = %d", oldMessageId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM messages_v2 WHERE mid = %d AND uid = %d", oldMessageId, did)).stepThis().dispose(); database.executeFast(String.format(Locale.US, "DELETE FROM messages_seq WHERE mid = %d", oldMessageId)).stepThis().dispose(); } catch (Exception e2) { FileLog.e(e2); @@ -9144,13 +9540,14 @@ public class MessagesStorage extends BaseController { } try { - state = database.executeFast("UPDATE media_v2 SET mid = ? WHERE mid = ?"); - state.bindLong(1, newMessageId); - state.bindLong(2, oldMessageId); + state = database.executeFast("UPDATE media_v3 SET mid = ? WHERE mid = ? AND uid = ?"); + state.bindInteger(1, newId); + state.bindInteger(2, oldMessageId); + state.bindLong(3, did); state.step(); } catch (Exception e) { try { - database.executeFast(String.format(Locale.US, "DELETE FROM media_v2 WHERE mid = %d", oldMessageId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM media_v3 WHERE mid = %d AND uid = %d", oldMessageId, did)).stepThis().dispose(); } catch (Exception e2) { FileLog.e(e2); } @@ -9163,8 +9560,8 @@ public class MessagesStorage extends BaseController { try { state = database.executeFast("UPDATE dialogs SET last_mid = ? WHERE last_mid = ?"); - state.bindLong(1, newMessageId); - state.bindLong(2, oldMessageId); + state.bindInteger(1, newId); + state.bindInteger(2, oldMessageId); state.step(); } catch (Exception e) { FileLog.e(e); @@ -9173,15 +9570,16 @@ public class MessagesStorage extends BaseController { state.dispose(); } } - } else if (scheduled == 1) { + } else { try { - state = database.executeFast("UPDATE scheduled_messages SET mid = ?, send_state = 0 WHERE mid = ?"); - state.bindLong(1, newMessageId); - state.bindLong(2, oldMessageId); + state = database.executeFast("UPDATE scheduled_messages_v2 SET mid = ?, send_state = 0 WHERE mid = ? AND uid = ?"); + state.bindInteger(1, newId); + state.bindInteger(2, oldMessageId); + state.bindLong(3, did); state.step(); } catch (Exception e) { try { - database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages WHERE mid = %d", oldMessageId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages_v2 WHERE mid = %d AND uid = %d", oldMessageId, did)).stepThis().dispose(); } catch (Exception e2) { FileLog.e(e2); } @@ -9196,16 +9594,16 @@ public class MessagesStorage extends BaseController { } } - public long[] updateMessageStateAndId(final long random_id, final Long _oldId, final int newId, final int date, boolean useQueue, final int channelId, int scheduled) { + public long[] updateMessageStateAndId(long random_id, long dialogId, Integer _oldId, int newId, int date, boolean useQueue, int scheduled) { if (useQueue) { - storageQueue.postRunnable(() -> updateMessageStateAndIdInternal(random_id, _oldId, newId, date, channelId, scheduled)); + storageQueue.postRunnable(() -> updateMessageStateAndIdInternal(random_id, dialogId, _oldId, newId, date, scheduled)); } else { - return updateMessageStateAndIdInternal(random_id, _oldId, newId, date, channelId, scheduled); + return updateMessageStateAndIdInternal(random_id, dialogId, _oldId, newId, date, scheduled); } return null; } - private void updateUsersInternal(final ArrayList users, final boolean onlyStatus, final boolean withTransaction) { + private void updateUsersInternal(ArrayList users, boolean onlyStatus, boolean withTransaction) { try { if (onlyStatus) { if (withTransaction) { @@ -9220,7 +9618,7 @@ public class MessagesStorage extends BaseController { } else { state.bindInteger(1, 0); } - state.bindInteger(2, user.id); + state.bindLong(2, user.id); state.step(); } state.dispose(); @@ -9229,7 +9627,7 @@ public class MessagesStorage extends BaseController { } } else { StringBuilder ids = new StringBuilder(); - SparseArray usersDict = new SparseArray<>(); + LongSparseArray usersDict = new LongSparseArray<>(); for (int a = 0, N = users.size(); a < N; a++) { TLRPC.User user = users.get(a); if (ids.length() != 0) { @@ -9273,7 +9671,7 @@ public class MessagesStorage extends BaseController { } } - public void updateUsers(final ArrayList users, final boolean onlyStatus, final boolean withTransaction, boolean useQueue) { + public void updateUsers(ArrayList users, boolean onlyStatus, boolean withTransaction, boolean useQueue) { if (users == null || users.isEmpty()) { return; } @@ -9284,36 +9682,36 @@ public class MessagesStorage extends BaseController { } } - private void markMessagesAsReadInternal(SparseLongArray inbox, SparseLongArray outbox, SparseIntArray encryptedMessages) { + private void markMessagesAsReadInternal(LongSparseIntArray inbox, LongSparseIntArray outbox, SparseIntArray encryptedMessages) { try { if (!isEmpty(inbox)) { SQLitePreparedStatement state = database.executeFast("DELETE FROM unread_push_messages WHERE uid = ? AND mid <= ?"); for (int b = 0; b < inbox.size(); b++) { - int key = inbox.keyAt(b); - long messageId = inbox.get(key); - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 1 WHERE uid = %d AND mid > 0 AND mid <= %d AND read_state IN(0,2) AND out = 0", key, messageId)).stepThis().dispose(); + long key = inbox.keyAt(b); + int messageId = inbox.get(key); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = read_state | 1 WHERE uid = %d AND mid > 0 AND mid <= %d AND read_state IN(0,2) AND out = 0", key, messageId)).stepThis().dispose(); state.requery(); state.bindLong(1, key); - state.bindLong(2, messageId); + state.bindInteger(2, messageId); state.step(); } state.dispose(); } if (!isEmpty(outbox)) { for (int b = 0; b < outbox.size(); b++) { - int key = outbox.keyAt(b); - long messageId = outbox.get(key); - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 1 WHERE uid = %d AND mid > 0 AND mid <= %d AND read_state IN(0,2) AND out = 1", key, messageId)).stepThis().dispose(); + long key = outbox.keyAt(b); + int messageId = outbox.get(key); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = read_state | 1 WHERE uid = %d AND mid > 0 AND mid <= %d AND read_state IN(0,2) AND out = 1", key, messageId)).stepThis().dispose(); } } if (encryptedMessages != null && !isEmpty(encryptedMessages)) { for (int a = 0; a < encryptedMessages.size(); a++) { - long dialog_id = ((long) encryptedMessages.keyAt(a)) << 32; + long dialogId = DialogObject.makeEncryptedDialogId(encryptedMessages.keyAt(a)); int max_date = encryptedMessages.valueAt(a); - SQLitePreparedStatement state = database.executeFast("UPDATE messages SET read_state = read_state | 1 WHERE uid = ? AND date <= ? AND read_state IN(0,2) AND out = 1"); + SQLitePreparedStatement state = database.executeFast("UPDATE messages_v2 SET read_state = read_state | 1 WHERE uid = ? AND date <= ? AND read_state IN(0,2) AND out = 1"); state.requery(); - state.bindLong(1, dialog_id); + state.bindLong(1, dialogId); state.bindInteger(2, max_date); state.step(); state.dispose(); @@ -9324,35 +9722,61 @@ public class MessagesStorage extends BaseController { } } - public void markMessagesContentAsRead(final ArrayList mids, final int date) { + private void markMessagesContentAsReadInternal(long dialogId, ArrayList mids, int date) { + try { + String midsStr = TextUtils.join(",", mids); + database.executeFast(String.format(Locale.US, "UPDATE messages_v2 SET read_state = read_state | 2 WHERE mid IN (%s) AND uid = %d", midsStr, dialogId)).stepThis().dispose(); + if (date != 0) { + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages_v2 WHERE mid IN (%s) AND uid = %d AND ttl > 0", midsStr, dialogId)); + ArrayList arrayList = null; + while (cursor.next()) { + if (arrayList == null) { + arrayList = new ArrayList<>(); + } + arrayList.add(cursor.intValue(0)); + } + if (arrayList != null) { + emptyMessagesMedia(dialogId, arrayList); + } + cursor.dispose(); + } + } catch (Exception e) { + FileLog.e(e); + } + } + + public void markMessagesContentAsRead(long dialogId, ArrayList mids, int date) { if (isEmpty(mids)) { return; } storageQueue.postRunnable(() -> { - try { - String midsStr = TextUtils.join(",", mids); - database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = read_state | 2 WHERE mid IN (%s)", midsStr)).stepThis().dispose(); - if (date != 0) { - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, ttl FROM messages WHERE mid IN (%s) AND ttl > 0", midsStr)); - ArrayList arrayList = null; + if (dialogId == 0) { + try { + LongSparseArray> sparseArray = new LongSparseArray<>(); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, mid FROM messages_v2 WHERE mid IN (%s) AND is_channel = 0", TextUtils.join(",", mids))); while (cursor.next()) { + long did = cursor.longValue(0); + ArrayList arrayList = sparseArray.get(did); if (arrayList == null) { arrayList = new ArrayList<>(); + sparseArray.put(did, arrayList); } - arrayList.add(cursor.intValue(0)); - } - if (arrayList != null) { - emptyMessagesMedia(arrayList); + arrayList.add(cursor.intValue(1)); } cursor.dispose(); + for (int a = 0, N = sparseArray.size(); a < N; a++) { + markMessagesContentAsReadInternal(sparseArray.keyAt(a), sparseArray.valueAt(a), date); + } + } catch (Exception e) { + FileLog.e(e); } - } catch (Exception e) { - FileLog.e(e); + } else { + markMessagesContentAsReadInternal(dialogId, mids, date); } }); } - public void markMessagesAsRead(final SparseLongArray inbox, final SparseLongArray outbox, final SparseIntArray encryptedMessages, boolean useQueue) { + public void markMessagesAsRead(LongSparseIntArray inbox, LongSparseIntArray outbox, SparseIntArray encryptedMessages, boolean useQueue) { if (useQueue) { storageQueue.postRunnable(() -> markMessagesAsReadInternal(inbox, outbox, encryptedMessages)); } else { @@ -9360,24 +9784,34 @@ public class MessagesStorage extends BaseController { } } - public void markMessagesAsDeletedByRandoms(final ArrayList messages) { + public void markMessagesAsDeletedByRandoms(ArrayList messages) { if (messages.isEmpty()) { return; } storageQueue.postRunnable(() -> { try { String ids = TextUtils.join(",", messages); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM randoms WHERE random_id IN(%s)", ids)); - final ArrayList mids = new ArrayList<>(); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, uid FROM randoms_v2 WHERE random_id IN(%s)", ids)); + LongSparseArray> dialogs = new LongSparseArray<>(); while (cursor.next()) { + long dialogId = cursor.longValue(1); + ArrayList mids = dialogs.get(dialogId); + if (mids == null) { + mids = new ArrayList<>(); + dialogs.put(dialogId, mids); + } mids.add(cursor.intValue(0)); } cursor.dispose(); - if (!mids.isEmpty()) { - AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, mids, 0, false)); - updateDialogsWithReadMessagesInternal(mids, null, null, null); - markMessagesAsDeletedInternal(mids, 0, true, false); - updateDialogsWithDeletedMessagesInternal(mids, null, 0); + if (!dialogs.isEmpty()) { + for (int a = 0, N = dialogs.size(); a < N; a++) { + long dialogId = dialogs.keyAt(a); + ArrayList mids = dialogs.valueAt(a); + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.messagesDeleted, mids, 0L, false)); + updateDialogsWithReadMessagesInternal(mids, null, null, null); + markMessagesAsDeletedInternal(dialogId, mids, true, false); + updateDialogsWithDeletedMessagesInternal(dialogId, 0, mids, null); + } } } catch (Exception e) { FileLog.e(e); @@ -9385,7 +9819,7 @@ public class MessagesStorage extends BaseController { }); } - protected void deletePushMessages(long dialogId, final ArrayList messages) { + protected void deletePushMessages(long dialogId, ArrayList messages) { try { database.executeFast(String.format(Locale.US, "DELETE FROM unread_push_messages WHERE uid = %d AND mid IN(%s)", dialogId, TextUtils.join(",", messages))).stepThis().dispose(); } catch (Exception e) { @@ -9395,7 +9829,7 @@ public class MessagesStorage extends BaseController { private void broadcastScheduledMessagesChange(Long did) { try { - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM scheduled_messages WHERE uid = %d", did)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM scheduled_messages_v2 WHERE uid = %d", did)); int count; if (cursor.next()) { count = cursor.intValue(0); @@ -9409,29 +9843,15 @@ public class MessagesStorage extends BaseController { } } - private ArrayList markMessagesAsDeletedInternal(final ArrayList messages, int channelId, boolean deleteFiles, boolean scheduled) { + private ArrayList markMessagesAsDeletedInternal(long dialogId, ArrayList messages, boolean deleteFiles, boolean scheduled) { try { ArrayList dialogsIds = new ArrayList<>(); if (scheduled) { - String ids; - if (channelId != 0) { - StringBuilder builder = new StringBuilder(messages.size()); - for (int a = 0; a < messages.size(); a++) { - long messageId = messages.get(a); - messageId |= ((long) channelId) << 32; - if (builder.length() > 0) { - builder.append(','); - } - builder.append(messageId); - } - ids = builder.toString(); - } else { - ids = TextUtils.join(",", messages); - } + String ids = TextUtils.join(",", messages); ArrayList dialogsToUpdate = new ArrayList<>(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM scheduled_messages WHERE mid IN(%s)", ids)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid FROM scheduled_messages_v2 WHERE mid IN(%s) AND uid = %d", ids, dialogId)); try { while (cursor.next()) { long did = cursor.longValue(0); @@ -9444,34 +9864,25 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages WHERE mid IN(%s)", ids)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages_v2 WHERE mid IN(%s) AND uid = %d", ids, dialogId)).stepThis().dispose(); for (int a = 0, N = dialogsToUpdate.size(); a < N; a++) { broadcastScheduledMessagesChange(dialogsToUpdate.get(a)); } } else { - String ids; - final ArrayList temp = new ArrayList<>(messages); + ArrayList temp = new ArrayList<>(messages); LongSparseArray dialogsToUpdate = new LongSparseArray<>(); LongSparseArray> messagesByDialogs = new LongSparseArray<>(); - if (channelId != 0) { - StringBuilder builder = new StringBuilder(messages.size()); - for (int a = 0; a < messages.size(); a++) { - long messageId = messages.get(a); - messageId |= ((long) channelId) << 32; - if (builder.length() > 0) { - builder.append(','); - } - builder.append(messageId); - } - ids = builder.toString(); - } else { - ids = TextUtils.join(",", messages); - } + String ids = TextUtils.join(",", messages); ArrayList filesToDelete = new ArrayList<>(); ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); - int currentUser = getUserConfig().getClientUserId(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data, read_state, out, mention, mid FROM messages WHERE mid IN(%s)", ids)); + long currentUser = getUserConfig().getClientUserId(); + SQLiteCursor cursor; + if (dialogId != 0) { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data, read_state, out, mention, mid FROM messages_v2 WHERE mid IN(%s) AND uid = %d", ids, dialogId)); + } else { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data, read_state, out, mention, mid FROM messages_v2 WHERE mid IN(%s) AND is_channel = 0", ids)); + } try { while (cursor.next()) { @@ -9500,7 +9911,7 @@ public class MessagesStorage extends BaseController { } } } - if ((int) did != 0 && !deleteFiles) { + if (!DialogObject.isEncryptedDialog(did) && !deleteFiles) { continue; } NativeByteBuffer data = cursor.byteBufferValue(1); @@ -9545,13 +9956,12 @@ public class MessagesStorage extends BaseController { for (int a = 0, N = messagesByDialogs.size(); a < N; a++) { long did = messagesByDialogs.keyAt(a); ArrayList mids = messagesByDialogs.valueAt(a); - int lowerId = (int) did; String idsStr = TextUtils.join(",", mids); - if (lowerId != 0) { - if (lowerId < 0) { - database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", -lowerId, idsStr)).stepThis().dispose(); + if (!DialogObject.isEncryptedDialog(did)) { + if (DialogObject.isChatDialog(did)) { + database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", -did, idsStr)).stepThis().dispose(); } else { - database.executeFast(String.format(Locale.US, "UPDATE user_settings SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", lowerId, idsStr)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE user_settings SET pinned = 0 WHERE uid = %d AND pinned IN (%s)", did, idsStr)).stepThis().dispose(); } } database.executeFast(String.format(Locale.US, "DELETE FROM chat_pinned_v2 WHERE uid = %d AND mid IN(%s)", did, idsStr)).stepThis().dispose(); @@ -9574,73 +9984,73 @@ public class MessagesStorage extends BaseController { } cursor.dispose(); } - } - database.executeFast(String.format(Locale.US, "DELETE FROM messages WHERE mid IN(%s)", ids)).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM polls WHERE mid IN(%s)", ids)).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM bot_keyboard WHERE mid IN(%s)", ids)).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM messages_seq WHERE mid IN(%s)", ids)).stepThis().dispose(); - if (temp.isEmpty()) { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, type FROM media_v2 WHERE mid IN(%s)", ids)); - SparseArray> mediaCounts = null; - while (cursor.next()) { - long uid = cursor.longValue(0); - int type = cursor.intValue(1); - if (mediaCounts == null) { - mediaCounts = new SparseArray<>(); + database.executeFast(String.format(Locale.US, "DELETE FROM messages_v2 WHERE mid IN(%s) AND uid = %d", ids, did)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM polls_v2 WHERE mid IN(%s) AND uid = %d", ids, did)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM bot_keyboard WHERE mid IN(%s) AND uid = %d", ids, did)).stepThis().dispose(); + if (temp.isEmpty()) { + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, type FROM media_v3 WHERE mid IN(%s) AND uid = %d", ids, did)); + SparseArray> mediaCounts = null; + while (cursor.next()) { + long uid = cursor.longValue(0); + int type = cursor.intValue(1); + if (mediaCounts == null) { + mediaCounts = new SparseArray<>(); + } + LongSparseArray counts = mediaCounts.get(type); + Integer count; + if (counts == null) { + counts = new LongSparseArray<>(); + count = 0; + mediaCounts.put(type, counts); + } else { + count = counts.get(uid); + } + if (count == null) { + count = 0; + } + count++; + counts.put(uid, count); } - LongSparseArray counts = mediaCounts.get(type); - Integer count; - if (counts == null) { - counts = new LongSparseArray<>(); - count = 0; - mediaCounts.put(type, counts); - } else { - count = counts.get(uid); - } - if (count == null) { - count = 0; - } - count++; - counts.put(uid, count); - } - cursor.dispose(); - if (mediaCounts != null) { - SQLitePreparedStatement state = database.executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?, ?)"); - for (int a = 0; a < mediaCounts.size(); a++) { - int type = mediaCounts.keyAt(a); - LongSparseArray value = mediaCounts.valueAt(a); - for (int b = 0; b < value.size(); b++) { - long uid = value.keyAt(b); - int lower_part = (int) uid; - int count = -1; - int old = 0; - cursor = database.queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type)); - if (cursor.next()) { - count = cursor.intValue(0); - old = cursor.intValue(1); - } - cursor.dispose(); - if (count != -1) { - state.requery(); - count = Math.max(0, count - value.valueAt(b)); - state.bindLong(1, uid); - state.bindInteger(2, type); - state.bindInteger(3, count); - state.bindInteger(4, old); - state.step(); + cursor.dispose(); + if (mediaCounts != null) { + SQLitePreparedStatement state = database.executeFast("REPLACE INTO media_counts_v2 VALUES(?, ?, ?, ?)"); + for (int c = 0, N3 = mediaCounts.size(); c < N3; c++) { + int type = mediaCounts.keyAt(c); + LongSparseArray value = mediaCounts.valueAt(c); + for (int b = 0, N2 = value.size(); b < N2; b++) { + long uid = value.keyAt(b); + int count = -1; + int old = 0; + cursor = database.queryFinalized(String.format(Locale.US, "SELECT count, old FROM media_counts_v2 WHERE uid = %d AND type = %d LIMIT 1", uid, type)); + if (cursor.next()) { + count = cursor.intValue(0); + old = cursor.intValue(1); + } + cursor.dispose(); + if (count != -1) { + state.requery(); + count = Math.max(0, count - value.valueAt(b)); + state.bindLong(1, uid); + state.bindInteger(2, type); + state.bindInteger(3, count); + state.bindInteger(4, old); + state.step(); + } } } + state.dispose(); } - state.dispose(); } - } else { - if (channelId == 0) { + database.executeFast(String.format(Locale.US, "DELETE FROM media_v3 WHERE mid IN(%s) AND uid = %d", ids, did)).stepThis().dispose(); + } + database.executeFast(String.format(Locale.US, "DELETE FROM messages_seq WHERE mid IN(%s)", ids)).stepThis().dispose(); + if (!temp.isEmpty()) { + if (dialogId == 0) { database.executeFast("UPDATE media_counts_v2 SET old = 1 WHERE 1").stepThis().dispose(); } else { - database.executeFast(String.format(Locale.US, "UPDATE media_counts_v2 SET old = 1 WHERE uid = %d", -channelId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE media_counts_v2 SET old = 1 WHERE uid = %d", dialogId)).stepThis().dispose(); } } - database.executeFast(String.format(Locale.US, "DELETE FROM media_v2 WHERE mid IN(%s)", ids)).stepThis().dispose(); getMediaDataController().clearBotKeyboard(0, messages); if (dialogsToUpdate.size() != 0) { @@ -9655,23 +10065,26 @@ public class MessagesStorage extends BaseController { return null; } - private void updateDialogsWithDeletedMessagesInternal(final ArrayList messages, ArrayList additionalDialogsToUpdate, int channelId) { + private void updateDialogsWithDeletedMessagesInternal(long originalDialogId, long channelId, ArrayList messages, ArrayList additionalDialogsToUpdate) { try { - String ids; ArrayList dialogsToUpdate = new ArrayList<>(); if (!messages.isEmpty()) { SQLitePreparedStatement state; if (channelId != 0) { - dialogsToUpdate.add((long) -channelId); - state = database.executeFast("UPDATE dialogs SET last_mid = (SELECT mid FROM messages WHERE uid = ? AND date = (SELECT MAX(date) FROM messages WHERE uid = ?)) WHERE did = ?"); + dialogsToUpdate.add(-channelId); + state = database.executeFast("UPDATE dialogs SET last_mid = (SELECT mid FROM messages_v2 WHERE uid = ? AND date = (SELECT MAX(date) FROM messages_v2 WHERE uid = ?)) WHERE did = ?"); } else { - ids = TextUtils.join(",", messages); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did FROM dialogs WHERE last_mid IN(%s)", ids)); - while (cursor.next()) { - dialogsToUpdate.add(cursor.longValue(0)); + if (originalDialogId == 0) { + String ids = TextUtils.join(",", messages); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did FROM dialogs WHERE last_mid IN(%s) AND flags = 0", ids)); + while (cursor.next()) { + dialogsToUpdate.add(cursor.longValue(0)); + } + cursor.dispose(); + } else { + dialogsToUpdate.add(originalDialogId); } - cursor.dispose(); - state = database.executeFast("UPDATE dialogs SET last_mid = (SELECT mid FROM messages WHERE uid = ? AND date = (SELECT MAX(date) FROM messages WHERE uid = ? AND date != 0)) WHERE did = ?"); + state = database.executeFast("UPDATE dialogs SET last_mid = (SELECT mid FROM messages_v2 WHERE uid = ? AND date = (SELECT MAX(date) FROM messages_v2 WHERE uid = ? AND date != 0)) WHERE did = ?"); } database.beginTransaction(); for (int a = 0; a < dialogsToUpdate.size(); a++) { @@ -9685,7 +10098,7 @@ public class MessagesStorage extends BaseController { state.dispose(); database.commitTransaction(); } else { - dialogsToUpdate.add((long) -channelId); + dialogsToUpdate.add(-channelId); } if (additionalDialogsToUpdate != null) { for (int a = 0; a < additionalDialogsToUpdate.size(); a++) { @@ -9695,14 +10108,14 @@ public class MessagesStorage extends BaseController { } } } - ids = TextUtils.join(",", dialogsToUpdate); + String ids = TextUtils.join(",", dialogsToUpdate); TLRPC.messages_Dialogs dialogs = new TLRPC.TL_messages_dialogs(); ArrayList encryptedChats = new ArrayList<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date, d.pts, d.inbox_max, d.outbox_max, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date, d.pts, d.inbox_max, d.outbox_max, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid WHERE d.did IN(%s)", ids)); while (cursor.next()) { long dialogId = cursor.longValue(0); TLRPC.Dialog dialog; @@ -9756,22 +10169,18 @@ public class MessagesStorage extends BaseController { addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); } - - int lower_id = (int) dialog.id; - int high_id = (int) (dialog.id >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } - } else { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); + } + } else if (DialogObject.isUserDialog(dialogId)) { + if (!usersToLoad.contains(dialogId)) { + usersToLoad.add(dialogId); } } else { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + if (!chatsToLoad.contains(-dialogId)) { + chatsToLoad.add(-dialogId); } } } @@ -9797,43 +10206,38 @@ public class MessagesStorage extends BaseController { } } - public void updateDialogsWithDeletedMessages(final ArrayList messages, final ArrayList additionalDialogsToUpdate, boolean useQueue, final int channelId) { - if (messages.isEmpty() && channelId == 0) { - return; - } + public void updateDialogsWithDeletedMessages(long dialogId, long channelId, ArrayList messages, ArrayList additionalDialogsToUpdate, boolean useQueue) { if (useQueue) { - storageQueue.postRunnable(() -> updateDialogsWithDeletedMessagesInternal(messages, additionalDialogsToUpdate, channelId)); + storageQueue.postRunnable(() -> updateDialogsWithDeletedMessagesInternal(dialogId, channelId, messages, additionalDialogsToUpdate)); } else { - updateDialogsWithDeletedMessagesInternal(messages, additionalDialogsToUpdate, channelId); + updateDialogsWithDeletedMessagesInternal(dialogId, channelId, messages, additionalDialogsToUpdate); } } - public ArrayList markMessagesAsDeleted(final ArrayList messages, boolean useQueue, final int channelId, boolean deleteFiles, boolean scheduled) { + public ArrayList markMessagesAsDeleted(long dialogId, ArrayList messages, boolean useQueue, boolean deleteFiles, boolean scheduled) { if (messages.isEmpty()) { return null; } if (useQueue) { - storageQueue.postRunnable(() -> markMessagesAsDeletedInternal(messages, channelId, deleteFiles, scheduled)); + storageQueue.postRunnable(() -> markMessagesAsDeletedInternal(dialogId, messages, deleteFiles, scheduled)); } else { - return markMessagesAsDeletedInternal(messages, channelId, deleteFiles, scheduled); + return markMessagesAsDeletedInternal(dialogId, messages, deleteFiles, scheduled); } return null; } - private ArrayList markMessagesAsDeletedInternal(final int channelId, final int mid, boolean deleteFiles) { + private ArrayList markMessagesAsDeletedInternal(long channelId, int mid, boolean deleteFiles) { try { String ids; ArrayList dialogsIds = new ArrayList<>(); LongSparseArray dialogsToUpdate = new LongSparseArray<>(); - long maxMessageId = mid; - maxMessageId |= ((long) channelId) << 32; ArrayList filesToDelete = new ArrayList<>(); ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); - int currentUser = getUserConfig().getClientUserId(); + long currentUser = getUserConfig().getClientUserId(); - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data, read_state, out, mention FROM messages WHERE uid = %d AND mid <= %d", -channelId, maxMessageId)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data, read_state, out, mention FROM messages_v2 WHERE uid = %d AND mid <= %d", -channelId, mid)); try { while (cursor.next()) { @@ -9854,7 +10258,7 @@ public class MessagesStorage extends BaseController { } } } - if ((int) did != 0 && !deleteFiles) { + if (!DialogObject.isEncryptedDialog(did) && !deleteFiles) { continue; } NativeByteBuffer data = cursor.byteBufferValue(1); @@ -9898,8 +10302,8 @@ public class MessagesStorage extends BaseController { } - database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d AND pinned <= %d", channelId, maxMessageId)).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM chat_pinned_v2 WHERE uid = %d AND mid <= %d", channelId, maxMessageId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "UPDATE chat_settings_v2 SET pinned = 0 WHERE uid = %d AND pinned <= %d", channelId, mid)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM chat_pinned_v2 WHERE uid = %d AND mid <= %d", channelId, mid)).stepThis().dispose(); int updatedCount = 0; cursor = database.queryFinalized("SELECT changes()"); if (cursor.next()) { @@ -9920,8 +10324,8 @@ public class MessagesStorage extends BaseController { cursor.dispose(); } - database.executeFast(String.format(Locale.US, "DELETE FROM messages WHERE uid = %d AND mid <= %d", -channelId, maxMessageId)).stepThis().dispose(); - database.executeFast(String.format(Locale.US, "DELETE FROM media_v2 WHERE uid = %d AND mid <= %d", -channelId, maxMessageId)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM messages_v2 WHERE uid = %d AND mid <= %d", -channelId, mid)).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM media_v3 WHERE uid = %d AND mid <= %d", -channelId, mid)).stepThis().dispose(); database.executeFast(String.format(Locale.US, "UPDATE media_counts_v2 SET old = 1 WHERE uid = %d", -channelId)).stepThis().dispose(); updateWidgets(dialogsIds); return dialogsIds; @@ -9931,7 +10335,7 @@ public class MessagesStorage extends BaseController { return null; } - public ArrayList markMessagesAsDeleted(final int channelId, final int mid, boolean useQueue, boolean deleteFiles) { + public ArrayList markMessagesAsDeleted(long channelId, int mid, boolean useQueue, boolean deleteFiles) { if (useQueue) { storageQueue.postRunnable(() -> markMessagesAsDeletedInternal(channelId, mid, deleteFiles)); } else { @@ -10151,21 +10555,16 @@ public class MessagesStorage extends BaseController { } } - public void replaceMessageIfExists(final TLRPC.Message message, ArrayList users, ArrayList chats, boolean broadcast) { + public void replaceMessageIfExists(TLRPC.Message message, ArrayList users, ArrayList chats, boolean broadcast) { if (message == null) { return; } storageQueue.postRunnable(() -> { try { - long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - SQLiteCursor cursor = null; int readState = 0; try { - cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state FROM messages WHERE mid = %d LIMIT 1", messageId)); + cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state FROM messages_v2 WHERE mid = %d AND uid = %d LIMIT 1", message.id, MessageObject.getDialogId(message))); if (!cursor.next()) { return; } @@ -10180,8 +10579,8 @@ public class MessagesStorage extends BaseController { database.beginTransaction(); - SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)"); - SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); + SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)"); + SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); if (message.dialog_id == 0) { MessageObject.getDialogId(message); } @@ -10190,7 +10589,7 @@ public class MessagesStorage extends BaseController { state.requery(); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - state.bindLong(1, messageId); + state.bindInteger(1, message.id); state.bindLong(2, message.dialog_id); state.bindInteger(3, readState); state.bindInteger(4, message.send_state); @@ -10225,11 +10624,12 @@ public class MessagesStorage extends BaseController { } else { state.bindInteger(14, 0); } + state.bindLong(15, MessageObject.getChannelId(message)); state.step(); if (MediaDataController.canAddMessageToMedia(message)) { state2.requery(); - state2.bindLong(1, messageId); + state2.bindInteger(1, message.id); state2.bindLong(2, message.dialog_id); state2.bindInteger(3, message.date); state2.bindInteger(4, MediaDataController.getMediaType(message)); @@ -10246,8 +10646,8 @@ public class MessagesStorage extends BaseController { database.commitTransaction(); if (broadcast) { - HashMap userHashMap = new HashMap<>(); - HashMap chatHashMap = new HashMap<>(); + HashMap userHashMap = new HashMap<>(); + HashMap chatHashMap = new HashMap<>(); for (int a = 0; a < users.size(); a++) { TLRPC.User user = users.get(a); userHashMap.put(user.id, user); @@ -10267,13 +10667,12 @@ public class MessagesStorage extends BaseController { }); } - public void putMessages(final TLRPC.messages_Messages messages, final long dialog_id, final int load_type, final int max_id, final boolean createDialog, final boolean scheduled) { + public void putMessages(TLRPC.messages_Messages messages, long dialogId, int load_type, int max_id, boolean createDialog, boolean scheduled) { storageQueue.postRunnable(() -> { try { if (scheduled) { - database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages WHERE uid = %d AND mid > 0", dialog_id)).stepThis().dispose(); - SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages VALUES(?, ?, ?, ?, ?, ?, NULL)"); - int channelId = 0; + database.executeFast(String.format(Locale.US, "DELETE FROM scheduled_messages_v2 WHERE uid = %d AND mid > 0", dialogId)).stepThis().dispose(); + SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO scheduled_messages_v2 VALUES(?, ?, ?, ?, ?, ?, NULL)"); int count = messages.messages.size(); for (int a = 0; a < count; a++) { TLRPC.Message message = messages.messages.get(a); @@ -10281,20 +10680,12 @@ public class MessagesStorage extends BaseController { continue; } - long messageId = message.id; - if (channelId == 0) { - channelId = message.peer_id.channel_id; - } - if (message.peer_id.channel_id != 0) { - messageId |= ((long) channelId) << 32; - } - fixUnsupportedMedia(message); state_messages.requery(); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - state_messages.bindLong(1, messageId); - state_messages.bindLong(2, dialog_id); + state_messages.bindInteger(1, message.id); + state_messages.bindLong(2, dialogId); state_messages.bindInteger(3, message.send_state); state_messages.bindInteger(4, message.date); state_messages.bindByteBuffer(5, data); @@ -10309,13 +10700,13 @@ public class MessagesStorage extends BaseController { putChatsInternal(messages.chats); database.commitTransaction(); - broadcastScheduledMessagesChange(dialog_id); + broadcastScheduledMessagesChange(dialogId); } else { int mentionCountUpdate = Integer.MAX_VALUE; if (messages.messages.isEmpty()) { if (load_type == 0) { - doneHolesInTable("messages_holes", dialog_id, max_id); - doneHolesInMedia(dialog_id, max_id, -1); + doneHolesInTable("messages_holes", dialogId, max_id); + doneHolesInMedia(dialogId, max_id, -1); } return; } @@ -10323,17 +10714,17 @@ public class MessagesStorage extends BaseController { if (load_type == 0) { int minId = messages.messages.get(messages.messages.size() - 1).id; - closeHolesInTable("messages_holes", dialog_id, minId, max_id); - closeHolesInMedia(dialog_id, minId, max_id, -1); + closeHolesInTable("messages_holes", dialogId, minId, max_id); + closeHolesInMedia(dialogId, minId, max_id, -1); } else if (load_type == 1) { int maxId = messages.messages.get(0).id; - closeHolesInTable("messages_holes", dialog_id, max_id, maxId); - closeHolesInMedia(dialog_id, max_id, maxId, -1); + closeHolesInTable("messages_holes", dialogId, max_id, maxId); + closeHolesInMedia(dialogId, max_id, maxId, -1); } else if (load_type == 3 || load_type == 2 || load_type == 4) { int maxId = max_id == 0 && load_type != 4 ? Integer.MAX_VALUE : messages.messages.get(0).id; int minId = messages.messages.get(messages.messages.size() - 1).id; - closeHolesInTable("messages_holes", dialog_id, minId, maxId); - closeHolesInMedia(dialog_id, minId, maxId, -1); + closeHolesInTable("messages_holes", dialogId, minId, maxId); + closeHolesInMedia(dialogId, minId, maxId, -1); } int count = messages.messages.size(); @@ -10346,27 +10737,23 @@ public class MessagesStorage extends BaseController { ArrayList namesToDelete = new ArrayList<>(); ArrayList> idsToDelete = new ArrayList<>(); - SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)"); - SQLitePreparedStatement state_media = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); + SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)"); + SQLitePreparedStatement state_media = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); SQLitePreparedStatement state_polls = null; SQLitePreparedStatement state_webpage = null; SQLitePreparedStatement state_tasks = null; int minDeleteTime = Integer.MAX_VALUE; TLRPC.Message botKeyboard = null; - int channelId = 0; + long channelId = 0; for (int a = 0; a < count; a++) { TLRPC.Message message = messages.messages.get(a); - long messageId = message.id; if (channelId == 0) { channelId = message.peer_id.channel_id; } - if (message.peer_id.channel_id != 0) { - messageId |= ((long) channelId) << 32; - } if (load_type == -2) { - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data, ttl, mention, read_state, send_state FROM messages WHERE mid = %d", messageId)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data, ttl, mention, read_state, send_state FROM messages_v2 WHERE mid = %d AND uid = %d", message.id, MessageObject.getDialogId(message))); boolean exist; if (exist = cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(1); @@ -10395,7 +10782,7 @@ public class MessagesStorage extends BaseController { int readState = cursor.intValue(4); if (oldMention != message.mentioned) { if (mentionCountUpdate == Integer.MAX_VALUE) { - SQLiteCursor cursor2 = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + dialog_id); + SQLiteCursor cursor2 = database.queryFinalized("SELECT unread_count_i FROM dialogs WHERE did = " + dialogId); if (cursor2.next()) { mentionCountUpdate = cursor2.intValue(0); } @@ -10422,7 +10809,7 @@ public class MessagesStorage extends BaseController { int pinned = 0; int mentions = 0; int flags = 0; - SQLiteCursor cursor = database.queryFinalized("SELECT pinned, unread_count_i, flags FROM dialogs WHERE did = " + dialog_id); + SQLiteCursor cursor = database.queryFinalized("SELECT pinned, unread_count_i, flags FROM dialogs WHERE did = " + dialogId); boolean exist; if (exist = cursor.next()) { pinned = cursor.intValue(0); @@ -10435,21 +10822,21 @@ public class MessagesStorage extends BaseController { if (exist) { state3 = database.executeFast("UPDATE dialogs SET date = ?, last_mid = ?, inbox_max = ?, last_mid_i = ?, pts = ?, date_i = ? WHERE did = ?"); state3.bindInteger(1, message.date); - state3.bindLong(2, messageId); + state3.bindInteger(2, message.id); state3.bindInteger(3, message.id); - state3.bindLong(4, messageId); + state3.bindInteger(4, message.id); state3.bindInteger(5, messages.pts); state3.bindInteger(6, message.date); - state3.bindLong(7, dialog_id); + state3.bindLong(7, dialogId); } else { state3 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - state3.bindLong(1, dialog_id); + state3.bindLong(1, dialogId); state3.bindInteger(2, message.date); state3.bindInteger(3, 0); - state3.bindLong(4, messageId); + state3.bindInteger(4, message.id); state3.bindInteger(5, message.id); state3.bindInteger(6, 0); - state3.bindLong(7, messageId); + state3.bindInteger(7, message.id); state3.bindInteger(8, mentions); state3.bindInteger(9, messages.pts); state3.bindInteger(10, message.date); @@ -10457,7 +10844,7 @@ public class MessagesStorage extends BaseController { state3.bindInteger(12, flags); state3.bindInteger(13, -1); state3.bindNull(14); - unknownDialogsIds.put(dialog_id, true); + unknownDialogsIds.put(dialogId, true); } state3.step(); state3.dispose(); @@ -10467,8 +10854,8 @@ public class MessagesStorage extends BaseController { state_messages.requery(); NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - state_messages.bindLong(1, messageId); - state_messages.bindLong(2, dialog_id); + state_messages.bindInteger(1, message.id); + state_messages.bindLong(2, dialogId); state_messages.bindInteger(3, MessageObject.getUnreadFlags(message)); state_messages.bindInteger(4, message.send_state); state_messages.bindInteger(5, message.date); @@ -10502,20 +10889,21 @@ public class MessagesStorage extends BaseController { } else { state_messages.bindInteger(14, 0); } + state_messages.bindLong(15, MessageObject.getChannelId(message)); state_messages.step(); if (MediaDataController.canAddMessageToMedia(message)) { state_media.requery(); - state_media.bindLong(1, messageId); - state_media.bindLong(2, dialog_id); + state_media.bindInteger(1, message.id); + state_media.bindLong(2, dialogId); state_media.bindInteger(3, message.date); state_media.bindInteger(4, MediaDataController.getMediaType(message)); state_media.bindByteBuffer(5, data); state_media.step(); } else if (message instanceof TLRPC.TL_messageService && message.action instanceof TLRPC.TL_messageActionHistoryClear) { try { - database.executeFast(String.format(Locale.US, "DELETE FROM media_v2 WHERE mid = %d", message.id)).stepThis().dispose(); - database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + dialog_id).stepThis().dispose(); + database.executeFast(String.format(Locale.US, "DELETE FROM media_v3 WHERE mid = %d AND uid = %d", message.id, dialogId)).stepThis().dispose(); + database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + dialogId).stepThis().dispose(); } catch (Exception e2) { FileLog.e(e2); } @@ -10527,32 +10915,35 @@ public class MessagesStorage extends BaseController { if (message.ttl_period != 0 && message.id > 0) { if (state_tasks == null) { - state_tasks = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)"); + state_tasks = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); } state_tasks.requery(); - state_tasks.bindLong(1, messageId); - state_tasks.bindInteger(2, message.date + message.ttl_period); - state_tasks.bindInteger(3, 0); + state_tasks.bindInteger(1, message.id); + state_tasks.bindLong(2, message.dialog_id); + state_tasks.bindInteger(3, message.date + message.ttl_period); + state_tasks.bindInteger(4, 0); state_tasks.step(); minDeleteTime = Math.min(minDeleteTime, message.date + message.ttl_period); } if (message.media instanceof TLRPC.TL_messageMediaPoll) { if (state_polls == null) { - state_polls = database.executeFast("REPLACE INTO polls VALUES(?, ?)"); + state_polls = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)"); } TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.media; state_polls.requery(); - state_polls.bindLong(1, messageId); - state_polls.bindLong(2, mediaPoll.poll.id); + state_polls.bindInteger(1, message.id); + state_polls.bindLong(2, message.dialog_id); + state_polls.bindLong(3, mediaPoll.poll.id); state_polls.step(); } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { if (state_webpage == null) { - state_webpage = database.executeFast("REPLACE INTO webpage_pending VALUES(?, ?)"); + state_webpage = database.executeFast("REPLACE INTO webpage_pending_v2 VALUES(?, ?, ?)"); } state_webpage.requery(); state_webpage.bindLong(1, message.media.webpage.id); - state_webpage.bindLong(2, messageId); + state_webpage.bindInteger(2, message.id); + state_webpage.bindLong(3, message.dialog_id); state_webpage.step(); } @@ -10569,13 +10960,13 @@ public class MessagesStorage extends BaseController { } if (state_tasks != null) { state_tasks.dispose(); - getMessagesController().didAddedNewTask(minDeleteTime, null); + getMessagesController().didAddedNewTask(minDeleteTime, 0, null); } if (state_polls != null) { state_polls.dispose(); } if (botKeyboard != null) { - getMediaDataController().putBotKeyboard(dialog_id, botKeyboard); + getMediaDataController().putBotKeyboard(dialogId, botKeyboard); } deleteFromDownloadQueue(idsToDelete, false); AndroidUtilities.runOnUIThread(() -> getFileLoader().cancelLoadFiles(namesToDelete)); @@ -10584,16 +10975,16 @@ public class MessagesStorage extends BaseController { putChatsInternal(messages.chats); if (mentionCountUpdate != Integer.MAX_VALUE) { - database.executeFast(String.format(Locale.US, "UPDATE dialogs SET unread_count_i = %d WHERE did = %d", mentionCountUpdate, dialog_id)).stepThis().dispose(); - LongSparseArray sparseArray = new LongSparseArray<>(1); - sparseArray.put(dialog_id, mentionCountUpdate); + database.executeFast(String.format(Locale.US, "UPDATE dialogs SET unread_count_i = %d WHERE did = %d", mentionCountUpdate, dialogId)).stepThis().dispose(); + LongSparseIntArray sparseArray = new LongSparseIntArray(1); + sparseArray.put(dialogId, mentionCountUpdate); getMessagesController().processDialogsUpdateRead(null, sparseArray); } database.commitTransaction(); if (createDialog) { - updateDialogsWithDeletedMessages(new ArrayList<>(), null, false, channelId); + updateDialogsWithDeletedMessages(dialogId, channelId, new ArrayList<>(), null, false); } } } catch (Exception e) { @@ -10602,13 +10993,13 @@ public class MessagesStorage extends BaseController { }); } - public static void addUsersAndChatsFromMessage(TLRPC.Message message, ArrayList usersToLoad, ArrayList chatsToLoad) { - int fromId = MessageObject.getFromChatId(message); - if (fromId > 0) { + public static void addUsersAndChatsFromMessage(TLRPC.Message message, ArrayList usersToLoad, ArrayList chatsToLoad) { + long fromId = MessageObject.getFromChatId(message); + if (DialogObject.isUserDialog(fromId)) { if (!usersToLoad.contains(fromId)) { usersToLoad.add(fromId); } - } else if (fromId < 0) { + } else if (DialogObject.isChatDialog(fromId)) { if (!chatsToLoad.contains(-fromId)) { chatsToLoad.add(-fromId); } @@ -10628,8 +11019,8 @@ public class MessagesStorage extends BaseController { } if (message.action instanceof TLRPC.TL_messageActionGeoProximityReached) { TLRPC.TL_messageActionGeoProximityReached action = (TLRPC.TL_messageActionGeoProximityReached) message.action; - Integer id = MessageObject.getPeerId(action.from_id); - if (id > 0) { + long id = MessageObject.getPeerId(action.from_id); + if (DialogObject.isUserDialog(id)) { if (!usersToLoad.contains(id)) { usersToLoad.add(id); } @@ -10647,7 +11038,7 @@ public class MessagesStorage extends BaseController { } if (!message.action.users.isEmpty()) { for (int a = 0; a < message.action.users.size(); a++) { - Integer uid = message.action.users.get(a); + Long uid = message.action.users.get(a); if (!usersToLoad.contains(uid)) { usersToLoad.add(uid); } @@ -10677,12 +11068,12 @@ public class MessagesStorage extends BaseController { } if (message.replies != null) { for (int a = 0, N = message.replies.recent_repliers.size(); a < N; a++) { - int id = MessageObject.getPeerId(message.replies.recent_repliers.get(a)); - if (id > 0) { + long id = MessageObject.getPeerId(message.replies.recent_repliers.get(a)); + if (DialogObject.isUserDialog(id)) { if (!usersToLoad.contains(id)) { usersToLoad.add(id); } - } else if (id < 0) { + } else if (DialogObject.isChatDialog(id)) { if (!chatsToLoad.contains(-id)) { chatsToLoad.add(-id); } @@ -10690,12 +11081,12 @@ public class MessagesStorage extends BaseController { } } if (message.reply_to != null && message.reply_to.reply_to_peer_id != null) { - int id = MessageObject.getPeerId(message.reply_to.reply_to_peer_id); - if (id > 0) { + long id = MessageObject.getPeerId(message.reply_to.reply_to_peer_id); + if (DialogObject.isUserDialog(id)) { if (!usersToLoad.contains(id)) { usersToLoad.add(id); } - } else if (id < 0) { + } else if (DialogObject.isChatDialog(id)) { if (!chatsToLoad.contains(-id)) { chatsToLoad.add(-id); } @@ -10731,27 +11122,24 @@ public class MessagesStorage extends BaseController { } } } - if (message.ttl < 0) { - if (!chatsToLoad.contains(-message.ttl)) { - chatsToLoad.add(-message.ttl); - } - } if (message.params != null) { String peerIdStr = message.params.get("fwd_peer"); if (peerIdStr != null) { - int peerId = Utilities.parseInt(peerIdStr); + long peerId = Utilities.parseLong(peerIdStr); if (peerId < 0) { - chatsToLoad.add(-peerId); + if (!chatsToLoad.contains(-peerId)) { + chatsToLoad.add(-peerId); + } } } } } - public void getDialogs(final int folderId, final int offset, final int count, final boolean loadDraftsPeersAndFolders) { - final long[] draftsDialogIds; + public void getDialogs(int folderId, int offset, int count, boolean loadDraftsPeersAndFolders) { + long[] draftsDialogIds; if (loadDraftsPeersAndFolders) { - final LongSparseArray> drafts = getMediaDataController().getDrafts(); - final int draftsCount = drafts.size(); + LongSparseArray> drafts = getMediaDataController().getDrafts(); + int draftsCount = drafts.size(); if (draftsCount > 0) { draftsDialogIds = new long[draftsCount]; for (int i = 0; i < draftsCount; i++) { @@ -10771,13 +11159,13 @@ public class MessagesStorage extends BaseController { TLRPC.messages_Dialogs dialogs = new TLRPC.TL_messages_dialogs(); ArrayList encryptedChats = new ArrayList<>(); try { - ArrayList usersToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); usersToLoad.add(getUserConfig().getClientUserId()); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); ArrayList loadedDialogs = new ArrayList<>(); - ArrayList replyMessages = new ArrayList<>(); - LongSparseArray replyMessageOwners = new LongSparseArray<>(); + LongSparseArray>> replyMessageOwners = new LongSparseArray<>(); + LongSparseArray> dialogReplyMessagesIds = new LongSparseArray<>(); ArrayList foldersToLoad = new ArrayList<>(2); foldersToLoad.add(folderId); for (int a = 0; a < foldersToLoad.size(); a++) { @@ -10792,7 +11180,7 @@ public class MessagesStorage extends BaseController { cnt = 100; } - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date, d.pts, d.inbox_max, d.outbox_max, m.replydata, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.folder_id = %d ORDER BY d.pinned DESC, d.date DESC LIMIT %d,%d", fid, off, cnt)); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date, d.pts, d.inbox_max, d.outbox_max, m.replydata, d.pinned, d.unread_count_i, d.flags, d.folder_id, d.data FROM dialogs as d LEFT JOIN messages_v2 as m ON d.last_mid = m.mid AND d.did = m.uid LEFT JOIN dialog_settings as s ON d.did = s.did WHERE d.folder_id = %d ORDER BY d.pinned DESC, d.date DESC LIMIT %d,%d", fid, off, cnt)); while (cursor.next()) { long dialogId = cursor.longValue(0); TLRPC.Dialog dialog; @@ -10805,7 +11193,7 @@ public class MessagesStorage extends BaseController { data.reuse(); } else { dialogFolder.folder = new TLRPC.TL_folder(); - dialogFolder.folder.id = (int) dialogId; + dialogFolder.folder.id = DialogObject.getFolderId(dialogId); } } dialog = dialogFolder; @@ -10820,7 +11208,7 @@ public class MessagesStorage extends BaseController { dialog.unread_count = cursor.intValue(2); dialog.last_message_date = cursor.intValue(3); dialog.pts = cursor.intValue(10); - dialog.flags = dialog.pts == 0 || (int) dialog.id > 0 ? 0 : 1; + dialog.flags = dialog.pts == 0 || DialogObject.isUserDialog(dialog.id) ? 0 : 1; dialog.read_inbox_max_id = cursor.intValue(11); dialog.read_outbox_max_id = cursor.intValue(12); dialog.pinnedNum = cursor.intValue(14); @@ -10879,18 +11267,7 @@ public class MessagesStorage extends BaseController { } } if (message.replyMessage == null) { - long messageId = message.reply_to.reply_to_msg_id; - if (message.reply_to.reply_to_peer_id != null) { - if (message.reply_to.reply_to_peer_id.channel_id != 0) { - messageId |= ((long) message.reply_to.reply_to_peer_id.channel_id) << 32; - } - } else if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - if (!replyMessages.contains(messageId)) { - replyMessages.add(messageId); - } - replyMessageOwners.put(dialog.id, message); + addReplyMessages(message, replyMessageOwners, dialogReplyMessagesIds); } } } catch (Exception e) { @@ -10901,57 +11278,32 @@ public class MessagesStorage extends BaseController { } } - int lower_id = (int) dialog.id; - int high_id = (int) (dialog.id >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } - } else { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); } - } else { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + } else if (DialogObject.isUserDialog(dialogId)) { + if (!usersToLoad.contains(dialogId)) { + usersToLoad.add(dialogId); + } + } else if (DialogObject.isChatDialog(dialogId)) { + if (!chatsToLoad.contains(-dialogId)) { + chatsToLoad.add(-dialogId); } } } cursor.dispose(); } - if (!replyMessages.isEmpty()) { - SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date, uid FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages))); - while (cursor.next()) { - NativeByteBuffer data = cursor.byteBufferValue(0); - if (data != null) { - TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, getUserConfig().clientUserId); - data.reuse(); - message.id = cursor.intValue(1); - message.date = cursor.intValue(2); - message.dialog_id = cursor.longValue(3); - - addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); - - TLRPC.Message owner = replyMessageOwners.get(message.dialog_id); - if (owner != null) { - owner.replyMessage = message; - message.dialog_id = owner.dialog_id; - } - } - } - cursor.dispose(); - } + loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad); if (draftsDialogIds != null) { - final ArrayList unloadedDialogs = new ArrayList<>(); + ArrayList unloadedDialogs = new ArrayList<>(); for (int i = 0; i < draftsDialogIds.length; i++) { - final int dialogId = (int) draftsDialogIds[i]; - if (dialogId == 0) { + long dialogId = draftsDialogIds[i]; + if (DialogObject.isEncryptedDialog(dialogId)) { continue; } if (dialogId > 0) { @@ -10968,11 +11320,11 @@ public class MessagesStorage extends BaseController { } } - final LongSparseArray folderIds; + LongSparseArray folderIds; if (!unloadedDialogs.isEmpty()) { folderIds = new LongSparseArray<>(unloadedDialogs.size()); - final SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, folder_id FROM dialogs WHERE did IN(%s)", TextUtils.join(",", unloadedDialogs))); + SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, folder_id FROM dialogs WHERE did IN(%s)", TextUtils.join(",", unloadedDialogs))); while (cursor.next()) { folderIds.put(cursor.longValue(0), cursor.intValue(1)); } @@ -10982,7 +11334,7 @@ public class MessagesStorage extends BaseController { } AndroidUtilities.runOnUIThread(() -> { - final MediaDataController mediaDataController = getMediaDataController(); + MediaDataController mediaDataController = getMediaDataController(); mediaDataController.clearDraftsFolderIds(); if (folderIds != null) { for (int i = 0, size = folderIds.size(); i < size; i++) { @@ -11030,19 +11382,19 @@ public class MessagesStorage extends BaseController { } } - private void putDialogsInternal(final TLRPC.messages_Dialogs dialogs, int check) { + private void putDialogsInternal(TLRPC.messages_Dialogs dialogs, int check) { try { database.beginTransaction(); - final LongSparseArray new_dialogMessage = new LongSparseArray<>(dialogs.messages.size()); + LongSparseArray new_dialogMessage = new LongSparseArray<>(dialogs.messages.size()); for (int a = 0; a < dialogs.messages.size(); a++) { TLRPC.Message message = dialogs.messages.get(a); new_dialogMessage.put(MessageObject.getDialogId(message), message); } if (!dialogs.dialogs.isEmpty()) { - SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?)"); + SQLitePreparedStatement state_messages = database.executeFast("REPLACE INTO messages_v2 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state_dialogs = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - SQLitePreparedStatement state_media = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)"); + SQLitePreparedStatement state_media = database.executeFast("REPLACE INTO media_v3 VALUES(?, ?, ?, ?, ?)"); SQLitePreparedStatement state_settings = database.executeFast("REPLACE INTO dialog_settings VALUES(?, ?)"); SQLitePreparedStatement state_holes = database.executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)"); SQLitePreparedStatement state_media_holes = database.executeFast("REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)"); @@ -11097,13 +11449,8 @@ public class MessagesStorage extends BaseController { NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize()); message.serializeToStream(data); - long messageId = message.id; - if (message.peer_id.channel_id != 0) { - messageId |= ((long) message.peer_id.channel_id) << 32; - } - state_messages.requery(); - state_messages.bindLong(1, messageId); + state_messages.bindInteger(1, message.id); state_messages.bindLong(2, dialog.id); state_messages.bindInteger(3, MessageObject.getUnreadFlags(message)); state_messages.bindInteger(4, message.send_state); @@ -11134,11 +11481,12 @@ public class MessagesStorage extends BaseController { } else { state_messages.bindInteger(14, 0); } + state_messages.bindLong(15, MessageObject.getChannelId(message)); state_messages.step(); if (MediaDataController.canAddMessageToMedia(message)) { state_media.requery(); - state_media.bindLong(1, messageId); + state_media.bindInteger(1, message.id); state_media.bindLong(2, dialog.id); state_media.bindInteger(3, message.date); state_media.bindInteger(4, MediaDataController.getMediaType(message)); @@ -11152,24 +11500,26 @@ public class MessagesStorage extends BaseController { if (message.ttl_period != 0 && message.id > 0) { if (state_tasks == null) { - state_tasks = database.executeFast("REPLACE INTO enc_tasks_v3 VALUES(?, ?, ?)"); + state_tasks = database.executeFast("REPLACE INTO enc_tasks_v4 VALUES(?, ?, ?, ?)"); } state_tasks.requery(); - state_tasks.bindLong(1, messageId); - state_tasks.bindInteger(2, message.date + message.ttl_period); - state_tasks.bindInteger(3, 0); + state_tasks.bindInteger(1, message.id); + state_tasks.bindLong(2, message.dialog_id); + state_tasks.bindInteger(3, message.date + message.ttl_period); + state_tasks.bindInteger(4, 0); state_tasks.step(); minDeleteTime = Math.min(minDeleteTime, message.date + message.ttl_period); } if (message.media instanceof TLRPC.TL_messageMediaPoll) { if (state_polls == null) { - state_polls = database.executeFast("REPLACE INTO polls VALUES(?, ?)"); + state_polls = database.executeFast("REPLACE INTO polls_v2 VALUES(?, ?, ?)"); } TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) message.media; state_polls.requery(); - state_polls.bindLong(1, messageId); - state_polls.bindLong(2, mediaPoll.poll.id); + state_polls.bindInteger(1, message.id); + state_polls.bindLong(2, message.dialog_id); + state_polls.bindLong(3, mediaPoll.poll.id); state_polls.step(); } @@ -11181,16 +11531,11 @@ public class MessagesStorage extends BaseController { } } - long topMessage = dialog.top_message; - if (dialog.peer != null && dialog.peer.channel_id != 0) { - topMessage |= ((long) dialog.peer.channel_id) << 32; - } - state_dialogs.requery(); state_dialogs.bindLong(1, dialog.id); state_dialogs.bindInteger(2, messageDate); state_dialogs.bindInteger(3, dialog.unread_count); - state_dialogs.bindLong(4, topMessage); + state_dialogs.bindInteger(4, dialog.top_message); state_dialogs.bindInteger(5, dialog.read_inbox_max_id); state_dialogs.bindInteger(6, dialog.read_outbox_max_id); state_dialogs.bindLong(7, 0); @@ -11234,7 +11579,7 @@ public class MessagesStorage extends BaseController { state_media_holes.dispose(); if (state_tasks != null) { state_tasks.dispose(); - getMessagesController().didAddedNewTask(minDeleteTime, null); + getMessagesController().didAddedNewTask(minDeleteTime, 0, null); } if (state_polls != null) { state_polls.dispose(); @@ -11273,7 +11618,7 @@ public class MessagesStorage extends BaseController { }); } - public void setDialogsFolderId(final ArrayList peers, ArrayList inputPeers, long dialogId, int folderId) { + public void setDialogsFolderId(ArrayList peers, ArrayList inputPeers, long dialogId, int folderId) { if (peers == null && inputPeers == null && dialogId == 0) { return; } @@ -11326,13 +11671,11 @@ public class MessagesStorage extends BaseController { boolean isEmpty = true; while (cursor.next()) { long did = cursor.longValue(0); - int lowerId = (int) did; - int highId = (int) (did >> 32); - if (lowerId > 0 || highId != 0 && lowerId == 0) { + if (DialogObject.isUserDialog(did) || DialogObject.isEncryptedDialog(did)) { isEmpty = false; break; } else { - TLRPC.Chat chat = getChat(-lowerId); + TLRPC.Chat chat = getChat(-did); if (!ChatObject.isNotInChat(chat) && chat.migrated_to == null) { isEmpty = false; break; @@ -11353,7 +11696,7 @@ public class MessagesStorage extends BaseController { storageQueue.postRunnable(() -> checkIfFolderEmptyInternal(folderId)); } - public void unpinAllDialogsExceptNew(final ArrayList dids, int folderId) { + public void unpinAllDialogsExceptNew(ArrayList dids, int folderId) { storageQueue.postRunnable(() -> { try { ArrayList unpinnedDialogs = new ArrayList<>(); @@ -11361,7 +11704,7 @@ public class MessagesStorage extends BaseController { while (cursor.next()) { long did = cursor.longValue(0); int fid = cursor.intValue(1); - if (fid == folderId && (int) did != 0 && !DialogObject.isFolderDialogId(did)) { + if (fid == folderId && !DialogObject.isEncryptedDialog(did) && !DialogObject.isFolderDialogId(did)) { unpinnedDialogs.add(cursor.longValue(0)); } } @@ -11383,7 +11726,7 @@ public class MessagesStorage extends BaseController { }); } - public void setDialogUnread(final long did, final boolean unread) { + public void setDialogUnread(long did, boolean unread) { storageQueue.postRunnable(() -> { try { int flags = 0; @@ -11442,7 +11785,7 @@ public class MessagesStorage extends BaseController { }); } - public void setDialogPinned(final long did, final int pinned) { + public void setDialogPinned(long did, int pinned) { storageQueue.postRunnable(() -> { try { SQLitePreparedStatement state = database.executeFast("UPDATE dialogs SET pinned = ? WHERE did = ?"); @@ -11473,7 +11816,7 @@ public class MessagesStorage extends BaseController { }); } - public void putDialogs(final TLRPC.messages_Dialogs dialogs, final int check) { + public void putDialogs(TLRPC.messages_Dialogs dialogs, int check) { if (dialogs.dialogs.isEmpty()) { return; } @@ -11487,12 +11830,12 @@ public class MessagesStorage extends BaseController { }); } - public void getDialogMaxMessageId(final long dialog_id, IntCallback callback) { + public void getDialogMaxMessageId(long dialog_id, IntCallback callback) { storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; int[] max = new int[1]; try { - cursor = database.queryFinalized("SELECT MAX(mid) FROM messages WHERE uid = " + dialog_id); + cursor = database.queryFinalized("SELECT MAX(mid) FROM messages_v2 WHERE uid = " + dialog_id); if (cursor.next()) { max[0] = cursor.intValue(0); } @@ -11507,9 +11850,9 @@ public class MessagesStorage extends BaseController { }); } - public int getDialogReadMax(final boolean outbox, final long dialog_id) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final Integer[] max = new Integer[]{0}; + public int getDialogReadMax(boolean outbox, long dialog_id) { + CountDownLatch countDownLatch = new CountDownLatch(1); + Integer[] max = new Integer[]{0}; storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; try { @@ -11538,9 +11881,9 @@ public class MessagesStorage extends BaseController { return max[0]; } - public int getChannelPtsSync(final int channelId) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final Integer[] pts = new Integer[]{0}; + public int getChannelPtsSync(long channelId) { + CountDownLatch countDownLatch = new CountDownLatch(1); + Integer[] pts = new Integer[]{0}; storageQueue.postRunnable(() -> { SQLiteCursor cursor = null; try { @@ -11569,11 +11912,11 @@ public class MessagesStorage extends BaseController { return pts[0]; } - public TLRPC.User getUserSync(final int user_id) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final TLRPC.User[] user = new TLRPC.User[1]; + public TLRPC.User getUserSync(long userId) { + CountDownLatch countDownLatch = new CountDownLatch(1); + TLRPC.User[] user = new TLRPC.User[1]; storageQueue.postRunnable(() -> { - user[0] = getUser(user_id); + user[0] = getUser(userId); countDownLatch.countDown(); }); try { @@ -11584,11 +11927,11 @@ public class MessagesStorage extends BaseController { return user[0]; } - public TLRPC.Chat getChatSync(final int chat_id) { - final CountDownLatch countDownLatch = new CountDownLatch(1); - final TLRPC.Chat[] chat = new TLRPC.Chat[1]; + public TLRPC.Chat getChatSync(long chatId) { + CountDownLatch countDownLatch = new CountDownLatch(1); + TLRPC.Chat[] chat = new TLRPC.Chat[1]; storageQueue.postRunnable(() -> { - chat[0] = getChat(chat_id); + chat[0] = getChat(chatId); countDownLatch.countDown(); }); try { @@ -11599,11 +11942,11 @@ public class MessagesStorage extends BaseController { return chat[0]; } - public TLRPC.User getUser(final int user_id) { + public TLRPC.User getUser(long userId) { TLRPC.User user = null; try { ArrayList users = new ArrayList<>(); - getUsersInternal("" + user_id, users); + getUsersInternal("" + userId, users); if (!users.isEmpty()) { user = users.get(0); } @@ -11613,7 +11956,7 @@ public class MessagesStorage extends BaseController { return user; } - public ArrayList getUsers(final ArrayList uids) { + public ArrayList getUsers(ArrayList uids) { ArrayList users = new ArrayList<>(); try { getUsersInternal(TextUtils.join(",", uids), users); @@ -11624,11 +11967,11 @@ public class MessagesStorage extends BaseController { return users; } - public TLRPC.Chat getChat(final int chat_id) { + public TLRPC.Chat getChat(long chatId) { TLRPC.Chat chat = null; try { ArrayList chats = new ArrayList<>(); - getChatsInternal("" + chat_id, chats); + getChatsInternal("" + chatId, chats); if (!chats.isEmpty()) { chat = chats.get(0); } @@ -11638,11 +11981,11 @@ public class MessagesStorage extends BaseController { return chat; } - public TLRPC.EncryptedChat getEncryptedChat(final int chat_id) { + public TLRPC.EncryptedChat getEncryptedChat(long chatId) { TLRPC.EncryptedChat chat = null; try { ArrayList encryptedChats = new ArrayList<>(); - getEncryptedChatsInternal("" + chat_id, encryptedChats, null); + getEncryptedChatsInternal("" + chatId, encryptedChats, null); if (!encryptedChats.isEmpty()) { chat = encryptedChats.get(0); } @@ -11654,7 +11997,7 @@ public class MessagesStorage extends BaseController { public void localSearch(int dialogsType, String query, ArrayList resultArray, ArrayList resultArrayNames, ArrayList encUsers, int folderId) { - int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); try { String search1 = query.trim().toLowerCase(); if (TextUtils.isEmpty(search1)) { @@ -11672,8 +12015,8 @@ public class MessagesStorage extends BaseController { search[1] = search2; } - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); int resultCount = 0; @@ -11690,27 +12033,26 @@ public class MessagesStorage extends BaseController { dialogSearchResult.date = cursor.intValue(1); dialogsResult.put(id, dialogSearchResult); - int lower_id = (int) id; - int high_id = (int) (id >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - if (dialogsType == 4 && lower_id == selfUserId) { + if (!DialogObject.isEncryptedDialog(id)) { + if (DialogObject.isUserDialog(id)) { + if (dialogsType == 4 && id == selfUserId) { continue; } - if (dialogsType != 2 && !usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); + if (dialogsType != 2 && !usersToLoad.contains(id)) { + usersToLoad.add(id); } } else { if (dialogsType == 4) { continue; } - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); + if (!chatsToLoad.contains(-id)) { + chatsToLoad.add(-id); } } } else if (dialogsType == 0 || dialogsType == 3) { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + int encryptedChatId = DialogObject.getEncryptedChatId(id); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); } } } @@ -11836,8 +12178,8 @@ public class MessagesStorage extends BaseController { data.reuse(); } if (chat != null && user != null) { - DialogsSearchAdapter.DialogSearchResult dialogSearchResult = dialogsResult.get((long) chat.id << 32); - chat.user_id = cursor.intValue(2); + DialogsSearchAdapter.DialogSearchResult dialogSearchResult = dialogsResult.get(DialogObject.makeEncryptedDialogId(chat.id)); + chat.user_id = cursor.longValue(2); chat.a_or_b = cursor.byteArrayValue(3); chat.auth_key = cursor.byteArrayValue(4); chat.ttl = cursor.intValue(5); @@ -11853,7 +12195,7 @@ public class MessagesStorage extends BaseController { chat.future_auth_key = cursor.byteArrayValue(15); chat.key_hash = cursor.byteArrayValue(16); chat.in_seq_no = cursor.intValue(17); - int admin_id = cursor.intValue(18); + long admin_id = cursor.longValue(18); if (admin_id != 0) { chat.admin_id = admin_id; } @@ -11905,7 +12247,7 @@ public class MessagesStorage extends BaseController { if (dialogsType != 2) { cursor = getDatabase().queryFinalized("SELECT u.data, u.status, u.name, u.uid FROM users as u INNER JOIN contacts as c ON u.uid = c.uid"); while (cursor.next()) { - int uid = cursor.intValue(3); + long uid = cursor.longValue(3); if (dialogsResult.indexOfKey(uid) >= 0) { continue; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java b/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java index e30501e83..0f746636e 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java @@ -34,7 +34,6 @@ import android.os.Process; import android.os.SystemClock; import android.service.media.MediaBrowserService; import android.text.TextUtils; -import android.util.SparseArray; import org.telegram.SQLite.SQLiteCursor; import org.telegram.messenger.audioinfo.AudioInfo; @@ -48,6 +47,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import androidx.collection.LongSparseArray; + @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class MusicBrowserService extends MediaBrowserService implements NotificationCenter.NotificationCenterDelegate { @@ -61,11 +62,11 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica private int currentAccount = UserConfig.selectedAccount; private boolean chatsLoaded; private boolean loadingChats; - private ArrayList dialogs = new ArrayList<>(); - private SparseArray users = new SparseArray<>(); - private SparseArray chats = new SparseArray<>(); - private SparseArray> musicObjects = new SparseArray<>(); - private SparseArray> musicQueues = new SparseArray<>(); + private ArrayList dialogs = new ArrayList<>(); + private LongSparseArray users = new LongSparseArray<>(); + private LongSparseArray chats = new LongSparseArray<>(); + private LongSparseArray> musicObjects = new LongSparseArray<>(); + private LongSparseArray> musicQueues = new LongSparseArray<>(); public static final String ACTION_CMD = "com.example.android.mediabrowserservice.ACTION_CMD"; public static final String CMD_NAME = "CMD_NAME"; @@ -76,7 +77,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica private boolean serviceStarted; - private int lastSelectedDialog; + private long lastSelectedDialog; private static final int STOP_DELAY = 30000; @@ -87,7 +88,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica super.onCreate(); ApplicationLoader.postInitApplication(); - lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0); + lastSelectedDialog = AndroidUtilities.getPrefIntOrLong(MessagesController.getNotificationsSettings(currentAccount), "auto_lastSelectedDialog", 0); mediaSession = new MediaSession(this, "MusicService"); setSessionToken(mediaSession.getSessionToken()); @@ -145,35 +146,35 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica } @Override - public void onLoadChildren(final String parentMediaId, final Result> result) { + public void onLoadChildren(String parentMediaId, Result> result) { if (!chatsLoaded) { result.detach(); if (loadingChats) { return; } loadingChats = true; - final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); + MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); messagesStorage.getStorageQueue().postRunnable(() -> { try { - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); - SQLiteCursor cursor = messagesStorage.getDatabase().queryFinalized(String.format(Locale.US, "SELECT DISTINCT uid FROM media_v2 WHERE uid != 0 AND mid > 0 AND type = %d", MediaDataController.MEDIA_MUSIC)); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); + SQLiteCursor cursor = messagesStorage.getDatabase().queryFinalized(String.format(Locale.US, "SELECT DISTINCT uid FROM media_v3 WHERE uid != 0 AND mid > 0 AND type = %d", MediaDataController.MEDIA_MUSIC)); while (cursor.next()) { - int lower_part = (int) cursor.longValue(0); - if (lower_part == 0) { + long dialogId = cursor.longValue(0); + if (DialogObject.isEncryptedDialog(dialogId)) { continue; } - dialogs.add(lower_part); - if (lower_part > 0) { - usersToLoad.add(lower_part); + dialogs.add(dialogId); + if (DialogObject.isUserDialog(dialogId)) { + usersToLoad.add(dialogId); } else { - chatsToLoad.add(-lower_part); + chatsToLoad.add(-dialogId); } } cursor.dispose(); if (!dialogs.isEmpty()) { String ids = TextUtils.join(",", dialogs); - cursor = messagesStorage.getDatabase().queryFinalized(String.format(Locale.US, "SELECT uid, data, mid FROM media_v2 WHERE uid IN (%s) AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC", ids, MediaDataController.MEDIA_MUSIC)); + cursor = messagesStorage.getDatabase().queryFinalized(String.format(Locale.US, "SELECT uid, data, mid FROM media_v3 WHERE uid IN (%s) AND mid > 0 AND type = %d ORDER BY date DESC, mid DESC", ids, MediaDataController.MEDIA_MUSIC)); while (cursor.next()) { NativeByteBuffer data = cursor.byteBufferValue(1); if (data != null) { @@ -181,7 +182,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId); data.reuse(); if (MessageObject.isMusicMessage(message)) { - int did = cursor.intValue(0); + long did = cursor.longValue(0); message.id = cursor.intValue(2); message.dialog_id = did; ArrayList arrayList = musicObjects.get(did); @@ -265,16 +266,16 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica } } - private void loadChildrenImpl(final String parentMediaId, final Result> result) { + private void loadChildrenImpl(String parentMediaId, Result> result) { List mediaItems = new ArrayList<>(); if (MEDIA_ID_ROOT.equals(parentMediaId)) { for (int a = 0; a < dialogs.size(); a++) { - int did = dialogs.get(a); - MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId("__CHAT_" + did); + long dialogId = dialogs.get(a); + MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId("__CHAT_" + dialogId); TLRPC.FileLocation avatar = null; - if (did > 0) { - TLRPC.User user = users.get(did); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = users.get(dialogId); if (user != null) { builder.setTitle(ContactsController.formatName(user.first_name, user.last_name)); if (user.photo != null && !(user.photo.photo_small instanceof TLRPC.TL_fileLocationUnavailable)) { @@ -284,7 +285,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica builder.setTitle("DELETED USER"); } } else { - TLRPC.Chat chat = chats.get(-did); + TLRPC.Chat chat = chats.get(-dialogId); if (chat != null) { builder.setTitle(chat.title); if (chat.photo != null && !(chat.photo.photo_small instanceof TLRPC.TL_fileLocationUnavailable)) { @@ -384,7 +385,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica return; } try { - int did = Integer.parseInt(args[0]); + long did = Long.parseLong(args[0]); int id = Integer.parseInt(args[1]); ArrayList arrayList = musicObjects.get(did); ArrayList arrayList1 = musicQueues.get(did); @@ -392,7 +393,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica return; } lastSelectedDialog = did; - MessagesController.getNotificationsSettings(currentAccount).edit().putInt("auto_lastSelectedDialog", did).commit(); + MessagesController.getNotificationsSettings(currentAccount).edit().putLong("auto_lastSelectedDialog", did).commit(); MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), 0, false, null); mediaSession.setQueue(arrayList1); if (did > 0) { @@ -443,8 +444,8 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica } query = query.toLowerCase(); for (int a = 0; a < dialogs.size(); a++) { - int did = dialogs.get(a); - if (did > 0) { + long did = dialogs.get(a); + if (DialogObject.isUserDialog(did)) { TLRPC.User user = users.get(did); if (user == null) { continue; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MusicPlayerReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/MusicPlayerReceiver.java index ed9f4b44f..854b42a55 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MusicPlayerReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MusicPlayerReceiver.java @@ -53,16 +53,23 @@ public class MusicPlayerReceiver extends BroadcastReceiver { break; } } else { - if (intent.getAction().equals(MusicPlayerService.NOTIFY_PLAY)) { - MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject()); - } else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PAUSE) || intent.getAction().equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { - MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject()); - } else if (intent.getAction().equals(MusicPlayerService.NOTIFY_NEXT)) { - MediaController.getInstance().playNextMessage(); - } else if (intent.getAction().equals(MusicPlayerService.NOTIFY_CLOSE)) { - MediaController.getInstance().cleanupPlayer(true, true); - } else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PREVIOUS)) { - MediaController.getInstance().playPreviousMessage(); + switch (intent.getAction()) { + case MusicPlayerService.NOTIFY_PLAY: + MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject()); + break; + case MusicPlayerService.NOTIFY_PAUSE: + case android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY: + MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject()); + break; + case MusicPlayerService.NOTIFY_NEXT: + MediaController.getInstance().playNextMessage(); + break; + case MusicPlayerService.NOTIFY_CLOSE: + MediaController.getInstance().cleanupPlayer(true, true); + break; + case MusicPlayerService.NOTIFY_PREVIOUS: + MediaController.getInstance().playPreviousMessage(); + break; } } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationBadge.java b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationBadge.java index 02a27c02c..48df3e34a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationBadge.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationBadge.java @@ -55,12 +55,7 @@ public class NotificationBadge { intent.putExtra(CLASSNAME, componentName.getClassName()); intent.putExtra(COUNT, badgeCount); if (canResolveBroadcast(intent)) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - ApplicationLoader.applicationContext.sendBroadcast(intent); - } - }); + AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent)); } } @@ -88,12 +83,7 @@ public class NotificationBadge { intent.putExtra(COUNT, badgeCount); intent.putExtra(CLASS, componentName.getClassName()); if (canResolveBroadcast(intent)) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - ApplicationLoader.applicationContext.sendBroadcast(intent); - } - }); + AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent)); } } @@ -118,12 +108,7 @@ public class NotificationBadge { intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName()); intent.putExtra("badge_vip_count", 0); if (canResolveBroadcast(intent)) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - ApplicationLoader.applicationContext.sendBroadcast(intent); - } - }); + AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent)); } } @@ -145,14 +130,11 @@ public class NotificationBadge { intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount); intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName()); intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName()); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - ApplicationLoader.applicationContext.sendBroadcast(intent); - } catch (Exception ignore) { + AndroidUtilities.runOnUIThread(() -> { + try { + ApplicationLoader.applicationContext.sendBroadcast(intent); + } catch (Exception ignore) { - } } }); } @@ -175,14 +157,11 @@ public class NotificationBadge { localBundle.putString("package", ApplicationLoader.applicationContext.getPackageName()); localBundle.putString("class", componentName.getClassName()); localBundle.putInt("badgenumber", badgeCount); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - ApplicationLoader.applicationContext.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle); - } catch (Exception e) { - FileLog.e(e); - } + AndroidUtilities.runOnUIThread(() -> { + try { + ApplicationLoader.applicationContext.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle); + } catch (Exception e) { + FileLog.e(e); } }); } @@ -216,12 +195,9 @@ public class NotificationBadge { intent.putExtra(COUNT, badgeCount); if (canResolveBroadcast(intent1) || canResolveBroadcast(intent)) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - ApplicationLoader.applicationContext.sendBroadcast(intent1); - ApplicationLoader.applicationContext.sendBroadcast(intent); - } + AndroidUtilities.runOnUIThread(() -> { + ApplicationLoader.applicationContext.sendBroadcast(intent1); + ApplicationLoader.applicationContext.sendBroadcast(intent); }); } } @@ -390,12 +366,7 @@ public class NotificationBadge { intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName()); intent.putExtra(INTENT_EXTRA_MESSAGE, String.valueOf(badgeCount)); intent.putExtra(INTENT_EXTRA_SHOW_MESSAGE, badgeCount > 0); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - ApplicationLoader.applicationContext.sendBroadcast(intent); - } - }); + AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent)); } private void executeBadgeByContentProvider(int badgeCount) { @@ -488,14 +459,11 @@ public class NotificationBadge { public void executeBadge(int badgeCount) { final Bundle extra = new Bundle(); extra.putInt("app_badge_count", badgeCount); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - ApplicationLoader.applicationContext.getContentResolver().call(CONTENT_URI, "setAppBadgeCount", null, extra); - } catch (Exception e) { - FileLog.e(e); - } + AndroidUtilities.runOnUIThread(() -> { + try { + ApplicationLoader.applicationContext.getContentResolver().call(CONTENT_URI, "setAppBadgeCount", null, extra); + } catch (Exception e) { + FileLog.e(e); } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java index 057b417a5..d6f1d40c4 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java @@ -221,6 +221,8 @@ public class NotificationCenter { public static final int webRtcSpeakerAmplitudeEvent = totalEvents++; public static final int showBulletin = totalEvents++; public static final int appUpdateAvailable = totalEvents++; + public static final int onDatabaseMigration = totalEvents++; + public static final int onEmojiInteractionsReceived = totalEvents++; private SparseArray> observers = new SparseArray<>(); private SparseArray> removeAfterBroadcast = new SparseArray<>(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java index 4015d4bcb..c0073b707 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java @@ -42,6 +42,8 @@ import android.os.Build; import android.os.PowerManager; import android.os.SystemClock; import android.provider.Settings; + +import androidx.collection.LongSparseArray; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.app.Person; @@ -52,14 +54,9 @@ import androidx.core.content.pm.ShortcutInfoCompat; import androidx.core.content.pm.ShortcutManagerCompat; import androidx.core.graphics.drawable.IconCompat; import android.text.TextUtils; -import android.util.LongSparseArray; import android.util.SparseArray; -import android.util.SparseIntArray; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.telegram.messenger.support.SparseLongArray; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.BubbleActivity; @@ -82,7 +79,7 @@ public class NotificationsController extends BaseController { private static DispatchQueue notificationsQueue = new DispatchQueue("notificationsQueue"); private ArrayList pushMessages = new ArrayList<>(); private ArrayList delayedPushMessages = new ArrayList<>(); - private LongSparseArray pushMessagesDict = new LongSparseArray<>(); + private LongSparseArray> pushMessagesDict = new LongSparseArray<>(); private LongSparseArray fcmRandomMessagesDict = new LongSparseArray<>(); private LongSparseArray smartNotificationsDialogs = new LongSparseArray<>(); private static NotificationManagerCompat notificationManager = null; @@ -94,10 +91,10 @@ public class NotificationsController extends BaseController { public ArrayList popupMessages = new ArrayList<>(); public ArrayList popupReplyMessages = new ArrayList<>(); private HashSet openedInBubbleDialogs = new HashSet<>(); - private long opened_dialog_id = 0; + private long openedDialogId = 0; private int lastButtonId = 5000; private int total_unread_count = 0; - private int personal_count = 0; + private int personalCount = 0; private boolean notifyCheck = false; private int lastOnlineFromOtherDevice = 0; private boolean inChatSoundEnabled; @@ -109,7 +106,7 @@ public class NotificationsController extends BaseController { private Boolean groupsCreated; private boolean channelGroupsCreated; - public static long globalSecretChatId = -(1L << 32); + public static long globalSecretChatId = DialogObject.makeEncryptedDialogId(1); public boolean showBadgeNumber; public boolean showBadgeMuted; @@ -133,6 +130,8 @@ public class NotificationsController extends BaseController { private int notificationId; private String notificationGroup; + private int lastInternalNotificationId; + static { if (Build.VERSION.SDK_INT >= 26 && ApplicationLoader.applicationContext != null) { notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext); @@ -159,7 +158,8 @@ public class NotificationsController extends BaseController { public NotificationsController(int instance) { super(instance); - + + lastInternalNotificationId = instance * 1000000 + 5000; notificationId = currentAccount + 1; notificationGroup = "messages" + (currentAccount == 0 ? "" : currentAccount); SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); @@ -248,9 +248,9 @@ public class NotificationsController extends BaseController { popupReplyMessages.clear(); channelGroupsCreated = false; notificationsQueue.postRunnable(() -> { - opened_dialog_id = 0; + openedDialogId = 0; total_unread_count = 0; - personal_count = 0; + personalCount = 0; pushMessages.clear(); pushMessagesDict.clear(); fcmRandomMessagesDict.clear(); @@ -310,21 +310,21 @@ public class NotificationsController extends BaseController { inChatSoundEnabled = value; } - public void setOpenedDialogId(final long dialog_id) { - notificationsQueue.postRunnable(() -> opened_dialog_id = dialog_id); + public void setOpenedDialogId(long dialog_id) { + notificationsQueue.postRunnable(() -> openedDialogId = dialog_id); } - public void setOpenedInBubble(final long dialog_id, boolean opened) { + public void setOpenedInBubble(long dialogId, boolean opened) { notificationsQueue.postRunnable(() -> { if (opened) { - openedInBubbleDialogs.add(dialog_id); + openedInBubbleDialogs.add(dialogId); } else { - openedInBubbleDialogs.remove(dialog_id); + openedInBubbleDialogs.remove(dialogId); } }); } - public void setLastOnlineFromOtherDevice(final int time) { + public void setLastOnlineFromOtherDevice(int time) { notificationsQueue.postRunnable(() -> { if (BuildVars.LOGS_ENABLED) { FileLog.d("set last online from other device = " + time); @@ -335,7 +335,7 @@ public class NotificationsController extends BaseController { public void removeNotificationsForDialog(long did) { processReadMessages(null, did, 0, Integer.MAX_VALUE, false); - LongSparseArray dialogsToUpdate = new LongSparseArray<>(); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(); dialogsToUpdate.put(did, 0); processDialogsUpdateRead(dialogsToUpdate); } @@ -345,7 +345,7 @@ public class NotificationsController extends BaseController { MessageObject messageObject = pushMessages.get(a); long dialog_id = messageObject.getDialogId(); if (messageObject.messageOwner.mentioned && messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage || - (int) dialog_id == 0 || messageObject.messageOwner.peer_id.channel_id != 0 && !messageObject.isSupergroup()) { + DialogObject.isEncryptedDialog(dialog_id) || messageObject.messageOwner.peer_id.channel_id != 0 && !messageObject.isSupergroup()) { continue; } return true; @@ -355,12 +355,12 @@ public class NotificationsController extends BaseController { protected void forceShowPopupForReply() { notificationsQueue.postRunnable(() -> { - final ArrayList popupArray = new ArrayList<>(); + ArrayList popupArray = new ArrayList<>(); for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); long dialog_id = messageObject.getDialogId(); if (messageObject.messageOwner.mentioned && messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage || - (int) dialog_id == 0 || messageObject.messageOwner.peer_id.channel_id != 0 && !messageObject.isSupergroup()) { + DialogObject.isEncryptedDialog(dialog_id) || messageObject.messageOwner.peer_id.channel_id != 0 && !messageObject.isSupergroup()) { continue; } popupArray.add(0, messageObject); @@ -380,20 +380,21 @@ public class NotificationsController extends BaseController { }); } - public void removeDeletedMessagesFromNotifications(final SparseArray> deletedMessages) { - final ArrayList popupArrayRemove = new ArrayList<>(0); + public void removeDeletedMessagesFromNotifications(LongSparseArray> deletedMessages) { + ArrayList popupArrayRemove = new ArrayList<>(0); notificationsQueue.postRunnable(() -> { int old_unread_count = total_unread_count; SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); for (int a = 0; a < deletedMessages.size(); a++) { - int key = deletedMessages.keyAt(a); + long key = deletedMessages.keyAt(a); + SparseArray sparseArray = pushMessagesDict.get(key); + if (sparseArray == null) { + continue; + } ArrayList mids = deletedMessages.get(key); - for (int b = 0; b < mids.size(); b++) { - long mid = mids.get(b); - if (key != 0) { - mid |= ((long) key) << 32; - } - MessageObject messageObject = pushMessagesDict.get(mid); + for (int b = 0, N = mids.size(); b < N; b++) { + int mid = mids.get(b); + MessageObject messageObject = sparseArray.get(mid); if (messageObject != null) { long dialogId = messageObject.getDialogId(); Integer currentCount = pushDialogs.get(dialogId); @@ -415,15 +416,18 @@ public class NotificationsController extends BaseController { pushDialogsOverrideMention.remove(dialogId); } - pushMessagesDict.remove(mid); + sparseArray.remove(mid); delayedPushMessages.remove(messageObject); pushMessages.remove(messageObject); if (isPersonalMessage(messageObject)) { - personal_count--; + personalCount--; } popupArrayRemove.add(messageObject); } } + if (sparseArray.size() == 0) { + pushMessagesDict.remove(key); + } } if (!popupArrayRemove.isEmpty()) { AndroidUtilities.runOnUIThread(() -> { @@ -440,7 +444,7 @@ public class NotificationsController extends BaseController { } else { scheduleNotificationDelay(lastOnlineFromOtherDevice > getConnectionsManager().getCurrentTime()); } - final int pushDialogsCount = pushDialogs.size(); + int pushDialogsCount = pushDialogs.size(); AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.notificationsCountUpdated, currentAccount); getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadCounterChanged, pushDialogsCount); @@ -453,17 +457,17 @@ public class NotificationsController extends BaseController { }); } - public void removeDeletedHisoryFromNotifications(final SparseIntArray deletedMessages) { - final ArrayList popupArrayRemove = new ArrayList<>(0); + public void removeDeletedHisoryFromNotifications(LongSparseIntArray deletedMessages) { + ArrayList popupArrayRemove = new ArrayList<>(0); notificationsQueue.postRunnable(() -> { int old_unread_count = total_unread_count; SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); for (int a = 0; a < deletedMessages.size(); a++) { - int key = deletedMessages.keyAt(a); - long dialog_id = -key; - int id = deletedMessages.get(key); - Integer currentCount = pushDialogs.get(dialog_id); + long key = deletedMessages.keyAt(a); + long dialogId = -key; + long id = deletedMessages.get(key); + Integer currentCount = pushDialogs.get(dialogId); if (currentCount == null) { currentCount = 0; } @@ -471,13 +475,19 @@ public class NotificationsController extends BaseController { for (int c = 0; c < pushMessages.size(); c++) { MessageObject messageObject = pushMessages.get(c); - if (messageObject.getDialogId() == dialog_id && messageObject.getId() <= id) { - pushMessagesDict.remove(messageObject.getIdWithChannel()); + if (messageObject.getDialogId() == dialogId && messageObject.getId() <= id) { + SparseArray sparseArray = pushMessagesDict.get(dialogId); + if (sparseArray != null) { + sparseArray.remove(messageObject.getId()); + if (sparseArray.size() == 0) { + pushMessagesDict.remove(dialogId); + } + } delayedPushMessages.remove(messageObject); pushMessages.remove(messageObject); c--; if (isPersonalMessage(messageObject)) { - personal_count--; + personalCount--; } popupArrayRemove.add(messageObject); newCount--; @@ -486,16 +496,16 @@ public class NotificationsController extends BaseController { if (newCount <= 0) { newCount = 0; - smartNotificationsDialogs.remove(dialog_id); + smartNotificationsDialogs.remove(dialogId); } if (!newCount.equals(currentCount)) { total_unread_count -= currentCount; total_unread_count += newCount; - pushDialogs.put(dialog_id, newCount); + pushDialogs.put(dialogId, newCount); } if (newCount == 0) { - pushDialogs.remove(dialog_id); - pushDialogsOverrideMention.remove(dialog_id); + pushDialogs.remove(dialogId); + pushDialogsOverrideMention.remove(dialogId); } } if (popupArrayRemove.isEmpty()) { @@ -513,7 +523,7 @@ public class NotificationsController extends BaseController { } else { scheduleNotificationDelay(lastOnlineFromOtherDevice > getConnectionsManager().getCurrentTime()); } - final int pushDialogsCount = pushDialogs.size(); + int pushDialogsCount = pushDialogs.size(); AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.notificationsCountUpdated, currentAccount); getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadCounterChanged, pushDialogsCount); @@ -526,25 +536,33 @@ public class NotificationsController extends BaseController { }); } - public void processReadMessages(final SparseLongArray inbox, final long dialog_id, final int max_date, final int max_id, final boolean isPopup) { - final ArrayList popupArrayRemove = new ArrayList<>(0); + public void processReadMessages(LongSparseIntArray inbox, long dialogId, int maxDate, int maxId, boolean isPopup) { + ArrayList popupArrayRemove = new ArrayList<>(0); notificationsQueue.postRunnable(() -> { if (inbox != null) { for (int b = 0; b < inbox.size(); b++) { - int key = inbox.keyAt(b); - long messageId = inbox.get(key); + long key = inbox.keyAt(b); + int messageId = inbox.get(key); for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); - if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == key && messageObject.getId() <= (int) messageId) { + if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == key && messageObject.getId() <= messageId) { if (isPersonalMessage(messageObject)) { - personal_count--; + personalCount--; } popupArrayRemove.add(messageObject); - long mid = messageObject.getId(); + long did; if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; + } + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray != null) { + sparseArray.remove(messageObject.getId()); + if (sparseArray.size() == 0) { + pushMessagesDict.remove(did); + } } - pushMessagesDict.remove(mid); delayedPushMessages.remove(messageObject); pushMessages.remove(a); a--; @@ -552,38 +570,46 @@ public class NotificationsController extends BaseController { } } } - if (dialog_id != 0 && (max_id != 0 || max_date != 0)) { + if (dialogId != 0 && (maxId != 0 || maxDate != 0)) { for (int a = 0; a < pushMessages.size(); a++) { MessageObject messageObject = pushMessages.get(a); - if (messageObject.getDialogId() == dialog_id) { + if (messageObject.getDialogId() == dialogId) { boolean remove = false; - if (max_date != 0) { - if (messageObject.messageOwner.date <= max_date) { + if (maxDate != 0) { + if (messageObject.messageOwner.date <= maxDate) { remove = true; } } else { if (!isPopup) { - if (messageObject.getId() <= max_id || max_id < 0) { + if (messageObject.getId() <= maxId || maxId < 0) { remove = true; } } else { - if (messageObject.getId() == max_id || max_id < 0) { + if (messageObject.getId() == maxId || maxId < 0) { remove = true; } } } if (remove) { if (isPersonalMessage(messageObject)) { - personal_count--; + personalCount--; + } + long did; + if (messageObject.messageOwner.peer_id.channel_id != 0) { + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; + } + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray != null) { + sparseArray.remove(messageObject.getId()); + if (sparseArray.size() == 0) { + pushMessagesDict.remove(did); + } } pushMessages.remove(a); delayedPushMessages.remove(messageObject); popupArrayRemove.add(messageObject); - long mid = messageObject.getId(); - if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; - } - pushMessagesDict.remove(mid); a--; } } @@ -600,17 +626,17 @@ public class NotificationsController extends BaseController { }); } - private int addToPopupMessages(final ArrayList popupArrayAdd, MessageObject messageObject, int lower_id, long dialog_id, boolean isChannel, SharedPreferences preferences) { + private int addToPopupMessages(ArrayList popupArrayAdd, MessageObject messageObject, long dialogId, boolean isChannel, SharedPreferences preferences) { int popup = 0; - if (lower_id != 0) { - if (preferences.getBoolean("custom_" + dialog_id, false)) { - popup = preferences.getInt("popup_" + dialog_id, 0); + if (!DialogObject.isEncryptedDialog(dialogId)) { + if (preferences.getBoolean("custom_" + dialogId, false)) { + popup = preferences.getInt("popup_" + dialogId, 0); } if (popup == 0) { if (isChannel) { popup = preferences.getInt("popupChannel", 0); } else { - popup = preferences.getInt((int) dialog_id < 0 ? "popupGroup" : "popupAll", 0); + popup = preferences.getInt(DialogObject.isChatDialog(dialogId) ? "popupGroup" : "popupAll", 0); } } else if (popup == 1) { popup = 3; @@ -627,29 +653,35 @@ public class NotificationsController extends BaseController { return popup; } - public void processEditedMessages(final LongSparseArray> editedMessages) { + public void processEditedMessages(LongSparseArray> editedMessages) { if (editedMessages.size() == 0) { return; } - final ArrayList popupArrayAdd = new ArrayList<>(0); + ArrayList popupArrayAdd = new ArrayList<>(0); notificationsQueue.postRunnable(() -> { boolean updated = false; for (int a = 0, N = editedMessages.size(); a < N; a++) { - long did = editedMessages.keyAt(a); - if (pushDialogs.indexOfKey(did) < 0) { + long dialogId = editedMessages.keyAt(a); + if (pushDialogs.indexOfKey(dialogId) < 0) { continue; } ArrayList messages = editedMessages.valueAt(a); for (int b = 0, N2 = messages.size(); b < N2; b++) { MessageObject messageObject = messages.get(b); - long mid = messageObject.getId(); + long did; if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; } - MessageObject oldMessage = pushMessagesDict.get(mid); + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray == null) { + break; + } + MessageObject oldMessage = sparseArray.get(messageObject.getId()); if (oldMessage != null) { updated = true; - pushMessagesDict.put(mid, messageObject); + sparseArray.put(messageObject.getId(), messageObject); int idx = pushMessages.indexOf(oldMessage); if (idx >= 0) { pushMessages.set(idx, messageObject); @@ -667,14 +699,14 @@ public class NotificationsController extends BaseController { }); } - public void processNewMessages(final ArrayList messageObjects, final boolean isLast, final boolean isFcm, CountDownLatch countDownLatch) { + public void processNewMessages(ArrayList messageObjects, boolean isLast, boolean isFcm, CountDownLatch countDownLatch) { if (messageObjects.isEmpty()) { if (countDownLatch != null) { countDownLatch.countDown(); } return; } - final ArrayList popupArrayAdd = new ArrayList<>(0); + ArrayList popupArrayAdd = new ArrayList<>(0); notificationsQueue.postRunnable(() -> { boolean added = false; boolean edited = false; @@ -692,24 +724,26 @@ public class NotificationsController extends BaseController { messageObject.messageOwner.silent && (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionContactSignUp || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined))) { continue; } - long mid = messageObject.getId(); - long random_id = messageObject.isFcmMessage() ? messageObject.messageOwner.random_id : 0; - long dialog_id = messageObject.getDialogId(); - int lower_id = (int) dialog_id; + int mid = messageObject.getId(); + long randomId = messageObject.isFcmMessage() ? messageObject.messageOwner.random_id : 0; + long dialogId = messageObject.getDialogId(); boolean isChannel; if (messageObject.isFcmMessage()) { isChannel = messageObject.localChannel; - } else if (lower_id < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); + } else if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); isChannel = ChatObject.isChannel(chat) && !chat.megagroup; } else { isChannel = false; } + long did; if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; } - - MessageObject oldMessageObject = pushMessagesDict.get(mid); + SparseArray sparseArray = pushMessagesDict.get(did); + MessageObject oldMessageObject = sparseArray != null ? sparseArray.get(mid) : null; if (oldMessageObject == null && messageObject.messageOwner.random_id != 0) { oldMessageObject = fcmRandomMessagesDict.get(messageObject.messageOwner.random_id); if (oldMessageObject != null) { @@ -718,11 +752,15 @@ public class NotificationsController extends BaseController { } if (oldMessageObject != null) { if (oldMessageObject.isFcmMessage()) { - pushMessagesDict.put(mid, messageObject); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + pushMessagesDict.put(did, sparseArray); + } + sparseArray.put(mid, messageObject); int idxOld = pushMessages.indexOf(oldMessageObject); if (idxOld >= 0) { pushMessages.set(idxOld, messageObject); - popup = addToPopupMessages(popupArrayAdd, messageObject, lower_id, dialog_id, isChannel, preferences); + popup = addToPopupMessages(popupArrayAdd, messageObject, dialogId, isChannel, preferences); } if (isFcm && (edited = messageObject.localEdit)) { getMessagesStorage().putPushMessage(messageObject); @@ -737,8 +775,8 @@ public class NotificationsController extends BaseController { getMessagesStorage().putPushMessage(messageObject); } - long original_dialog_id = dialog_id; - if (dialog_id == opened_dialog_id && ApplicationLoader.isScreenOn) { + long originalDialogId = dialogId; + if (dialogId == openedDialogId && ApplicationLoader.isScreenOn) { if (!isFcm) { playInChatSound(); } @@ -748,22 +786,22 @@ public class NotificationsController extends BaseController { if (!allowPinned && messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) { continue; } - dialog_id = messageObject.getFromChatId(); + dialogId = messageObject.getFromChatId(); } if (isPersonalMessage(messageObject)) { - personal_count++; + personalCount++; } added = true; - boolean isChat = lower_id < 0; - int index = settingsCache.indexOfKey(dialog_id); + boolean isChat = DialogObject.isChatDialog(dialogId); + int index = settingsCache.indexOfKey(dialogId); boolean value; if (index >= 0) { value = settingsCache.valueAt(index); } else { - int notifyOverride = getNotifyOverride(preferences, dialog_id); + int notifyOverride = getNotifyOverride(preferences, dialogId); if (notifyOverride == -1) { - value = isGlobalNotificationsEnabled(dialog_id, isChannel); + value = isGlobalNotificationsEnabled(dialogId, isChannel); /*if (BuildVars.DEBUG_PRIVATE_VERSION && BuildVars.LOGS_ENABLED) { FileLog.d("global notify settings for " + dialog_id + " = " + value); }*/ @@ -771,12 +809,12 @@ public class NotificationsController extends BaseController { value = notifyOverride != 2; } - settingsCache.put(dialog_id, value); + settingsCache.put(dialogId, value); } if (value) { if (!isFcm) { - popup = addToPopupMessages(popupArrayAdd, messageObject, lower_id, dialog_id, isChannel, preferences); + popup = addToPopupMessages(popupArrayAdd, messageObject, dialogId, isChannel, preferences); } if (!hasScheduled) { hasScheduled = messageObject.messageOwner.from_scheduled; @@ -784,13 +822,17 @@ public class NotificationsController extends BaseController { delayedPushMessages.add(messageObject); pushMessages.add(0, messageObject); if (mid != 0) { - pushMessagesDict.put(mid, messageObject); - } else if (random_id != 0) { - fcmRandomMessagesDict.put(random_id, messageObject); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + pushMessagesDict.put(did, sparseArray); + } + sparseArray.put(mid, messageObject); + } else if (randomId != 0) { + fcmRandomMessagesDict.put(randomId, messageObject); } - if (original_dialog_id != dialog_id) { - Integer current = pushDialogsOverrideMention.get(original_dialog_id); - pushDialogsOverrideMention.put(original_dialog_id, current == null ? 1 : current + 1); + if (originalDialogId != dialogId) { + Integer current = pushDialogsOverrideMention.get(originalDialogId); + pushDialogsOverrideMention.put(originalDialogId, current == null ? 1 : current + 1); } } } @@ -800,7 +842,7 @@ public class NotificationsController extends BaseController { } if (!popupArrayAdd.isEmpty() && !AndroidUtilities.needShowPasscode() && !SharedConfig.isWaitingForPasscodeEnter) { - final int popupFinal = popup; + int popupFinal = popup; AndroidUtilities.runOnUIThread(() -> { popupMessages.addAll(0, popupArrayAdd); if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) { @@ -863,7 +905,7 @@ public class NotificationsController extends BaseController { if (old_unread_count != total_unread_count) { delayedPushMessages.clear(); showOrUpdateNotification(notifyCheck); - final int pushDialogsCount = pushDialogs.size(); + int pushDialogsCount = pushDialogs.size(); AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.notificationsCountUpdated, currentAccount); getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadCounterChanged, pushDialogsCount); @@ -885,19 +927,18 @@ public class NotificationsController extends BaseController { return total_unread_count; } - public void processDialogsUpdateRead(final LongSparseArray dialogsToUpdate) { - final ArrayList popupArrayToRemove = new ArrayList<>(); + public void processDialogsUpdateRead(LongSparseIntArray dialogsToUpdate) { + ArrayList popupArrayToRemove = new ArrayList<>(); notificationsQueue.postRunnable(() -> { int old_unread_count = total_unread_count; SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); for (int b = 0; b < dialogsToUpdate.size(); b++) { long dialogId = dialogsToUpdate.keyAt(b); Integer currentCount = pushDialogs.get(dialogId); - Integer newCount = dialogsToUpdate.get(dialogId); + int newCount = dialogsToUpdate.get(dialogId); - int lowerId = (int) dialogId; - if (lowerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (chat == null || chat.min || ChatObject.isNotInChat(chat)) { newCount = 0; } @@ -941,16 +982,24 @@ public class NotificationsController extends BaseController { MessageObject messageObject = pushMessages.get(a); if (!messageObject.messageOwner.from_scheduled && messageObject.getDialogId() == dialogId) { if (isPersonalMessage(messageObject)) { - personal_count--; + personalCount--; } pushMessages.remove(a); a--; delayedPushMessages.remove(messageObject); - long mid = messageObject.getId(); + long did; if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; + } + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray != null) { + sparseArray.remove(messageObject.getId()); + if (sparseArray.size() == 0) { + pushMessagesDict.remove(did); + } } - pushMessagesDict.remove(mid); popupArrayToRemove.add(messageObject); } } @@ -974,7 +1023,7 @@ public class NotificationsController extends BaseController { } else { scheduleNotificationDelay(lastOnlineFromOtherDevice > getConnectionsManager().getCurrentTime()); } - final int pushDialogsCount = pushDialogs.size(); + int pushDialogsCount = pushDialogs.size(); AndroidUtilities.runOnUIThread(() -> { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.notificationsCountUpdated, currentAccount); getNotificationCenter().postNotificationName(NotificationCenter.dialogsUnreadCounterChanged, pushDialogsCount); @@ -987,7 +1036,7 @@ public class NotificationsController extends BaseController { }); } - public void processLoadedUnreadMessages(final LongSparseArray dialogs, final ArrayList messages, ArrayList push, final ArrayList users, final ArrayList chats, final ArrayList encryptedChats) { + public void processLoadedUnreadMessages(LongSparseArray dialogs, ArrayList messages, ArrayList push, ArrayList users, ArrayList chats, ArrayList encryptedChats) { getMessagesController().putUsers(users, true); getMessagesController().putChats(chats, true); getMessagesController().putEncryptedChats(encryptedChats, true); @@ -997,28 +1046,34 @@ public class NotificationsController extends BaseController { pushMessages.clear(); pushMessagesDict.clear(); total_unread_count = 0; - personal_count = 0; + personalCount = 0; SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); LongSparseArray settingsCache = new LongSparseArray<>(); if (messages != null) { for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); - if (message != null && (message.fwd_from != null && message.fwd_from.imported || - message.action instanceof TLRPC.TL_messageActionSetMessagesTTL || - message.silent && (message.action instanceof TLRPC.TL_messageActionContactSignUp || message.action instanceof TLRPC.TL_messageActionUserJoined))) { + if (message == null) { continue; } - long mid = message.id; - if (message.peer_id.channel_id != 0) { - mid |= ((long) message.peer_id.channel_id) << 32; + if (message.fwd_from != null && message.fwd_from.imported || + message.action instanceof TLRPC.TL_messageActionSetMessagesTTL || + message.silent && (message.action instanceof TLRPC.TL_messageActionContactSignUp || message.action instanceof TLRPC.TL_messageActionUserJoined)) { + continue; } - if (pushMessagesDict.indexOfKey(mid) >= 0) { + long did; + if (message.peer_id.channel_id != 0) { + did = -message.peer_id.channel_id; + } else { + did = 0; + } + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray != null && sparseArray.indexOfKey(message.id) >= 0) { continue; } MessageObject messageObject = new MessageObject(currentAccount, message, false, false); if (isPersonalMessage(messageObject)) { - personal_count++; + personalCount++; } long dialog_id = messageObject.getDialogId(); long original_dialog_id = dialog_id; @@ -1038,10 +1093,14 @@ public class NotificationsController extends BaseController { } settingsCache.put(dialog_id, value); } - if (!value || dialog_id == opened_dialog_id && ApplicationLoader.isScreenOn) { + if (!value || dialog_id == openedDialogId && ApplicationLoader.isScreenOn) { continue; } - pushMessagesDict.put(mid, messageObject); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + pushMessagesDict.put(did, sparseArray); + } + sparseArray.put(message.id, messageObject); pushMessages.add(0, messageObject); if (original_dialog_id != dialog_id) { Integer current = pushDialogsOverrideMention.get(original_dialog_id); @@ -1063,14 +1122,6 @@ public class NotificationsController extends BaseController { value = notifyOverride != 2; } - /*if (!value) { - Integer override = pushDialogsOverrideMention.get(dialog_id); - if (override != null && override != 0) { - value = true; - newCount = override; - } - }*/ - settingsCache.put(dialog_id, value); } if (!value) { @@ -1084,61 +1135,69 @@ public class NotificationsController extends BaseController { if (push != null) { for (int a = 0; a < push.size(); a++) { MessageObject messageObject = push.get(a); - long mid = messageObject.getId(); - if (messageObject.messageOwner.peer_id.channel_id != 0) { - mid |= ((long) messageObject.messageOwner.peer_id.channel_id) << 32; - } + int mid = messageObject.getId(); if (pushMessagesDict.indexOfKey(mid) >= 0) { continue; } if (isPersonalMessage(messageObject)) { - personal_count++; + personalCount++; } - long dialog_id = messageObject.getDialogId(); - long original_dialog_id = dialog_id; - long random_id = messageObject.messageOwner.random_id; + long dialogId = messageObject.getDialogId(); + long originalDialogId = dialogId; + long randomId = messageObject.messageOwner.random_id; if (messageObject.messageOwner.mentioned) { - dialog_id = messageObject.getFromChatId(); + dialogId = messageObject.getFromChatId(); } - int index = settingsCache.indexOfKey(dialog_id); + int index = settingsCache.indexOfKey(dialogId); boolean value; if (index >= 0) { value = settingsCache.valueAt(index); } else { - int notifyOverride = getNotifyOverride(preferences, dialog_id); + int notifyOverride = getNotifyOverride(preferences, dialogId); if (notifyOverride == -1) { - value = isGlobalNotificationsEnabled(dialog_id); + value = isGlobalNotificationsEnabled(dialogId); } else { value = notifyOverride != 2; } - settingsCache.put(dialog_id, value); + settingsCache.put(dialogId, value); } - if (!value || dialog_id == opened_dialog_id && ApplicationLoader.isScreenOn) { + if (!value || dialogId == openedDialogId && ApplicationLoader.isScreenOn) { continue; } if (mid != 0) { - pushMessagesDict.put(mid, messageObject); - } else if (random_id != 0) { - fcmRandomMessagesDict.put(random_id, messageObject); + long did; + if (messageObject.messageOwner.peer_id.channel_id != 0) { + did = -messageObject.messageOwner.peer_id.channel_id; + } else { + did = 0; + } + SparseArray sparseArray = pushMessagesDict.get(did); + if (sparseArray == null) { + sparseArray = new SparseArray<>(); + pushMessagesDict.put(did, sparseArray); + } + sparseArray.put(mid, messageObject); + } else if (randomId != 0) { + fcmRandomMessagesDict.put(randomId, messageObject); } pushMessages.add(0, messageObject); - if (original_dialog_id != dialog_id) { - Integer current = pushDialogsOverrideMention.get(original_dialog_id); - pushDialogsOverrideMention.put(original_dialog_id, current == null ? 1 : current + 1); + if (originalDialogId != dialogId) { + Integer current = pushDialogsOverrideMention.get(originalDialogId); + pushDialogsOverrideMention.put(originalDialogId, current == null ? 1 : current + 1); } - Integer currentCount = pushDialogs.get(dialog_id); + Integer currentCount = pushDialogs.get(dialogId); int newCount = currentCount != null ? currentCount + 1 : 1; if (currentCount != null) { total_unread_count -= currentCount; } total_unread_count += newCount; - pushDialogs.put(dialog_id, newCount); + pushDialogs.put(dialogId, newCount); } } - final int pushDialogsCount = pushDialogs.size(); + int pushDialogsCount = pushDialogs.size(); AndroidUtilities.runOnUIThread(() -> { if (total_unread_count == 0) { popupMessages.clear(); @@ -1166,9 +1225,8 @@ public class NotificationsController extends BaseController { try { for (int i = 0, N = MessagesController.getInstance(a).allDialogs.size(); i < N; i++) { TLRPC.Dialog dialog = MessagesController.getInstance(a).allDialogs.get(i); - int lowerId = (int) dialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + if (DialogObject.isChatDialog(dialog.id)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialog.id); if (ChatObject.isNotInChat(chat)) { continue; } @@ -1188,9 +1246,8 @@ public class NotificationsController extends BaseController { try { for (int i = 0, N = MessagesController.getInstance(a).allDialogs.size(); i < N; i++) { TLRPC.Dialog dialog = MessagesController.getInstance(a).allDialogs.get(i); - int lowerId = (int) dialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + if (DialogObject.isChatDialog(dialog.id)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialog.id); if (ChatObject.isNotInChat(chat)) { continue; } @@ -1216,7 +1273,7 @@ public class NotificationsController extends BaseController { notificationsQueue.postRunnable(() -> setBadge(getTotalAllUnreadCount())); } - private void setBadge(final int count) { + private void setBadge(int count) { if (lastBadgeCount == count) { return; } @@ -1229,8 +1286,8 @@ public class NotificationsController extends BaseController { return LocaleController.getString("NotificationHiddenMessage", R.string.NotificationHiddenMessage); } long dialogId = messageObject.messageOwner.dialog_id; - int chat_id = messageObject.messageOwner.peer_id.chat_id != 0 ? messageObject.messageOwner.peer_id.chat_id : messageObject.messageOwner.peer_id.channel_id; - int fromId = messageObject.messageOwner.peer_id.user_id; + long chat_id = messageObject.messageOwner.peer_id.chat_id != 0 ? messageObject.messageOwner.peer_id.chat_id : messageObject.messageOwner.peer_id.channel_id; + long fromId = messageObject.messageOwner.peer_id.user_id; if (preview != null) { preview[0] = true; } @@ -1266,7 +1323,7 @@ public class NotificationsController extends BaseController { } return messageObject.messageOwner.message; } - int selfUsedId = getUserConfig().getClientUserId(); + long selfUsedId = getUserConfig().getClientUserId(); if (fromId == 0) { fromId = messageObject.getFromChatId(); if (fromId == 0) { @@ -1310,8 +1367,8 @@ public class NotificationsController extends BaseController { } } if (name != null && fromId > 0 && UserObject.isReplyUser(dialogId) && messageObject.messageOwner.fwd_from != null && messageObject.messageOwner.fwd_from.saved_from_peer != null) { - int id = MessageObject.getPeerId(messageObject.messageOwner.fwd_from.saved_from_peer); - if (id < 0) { + long id = MessageObject.getPeerId(messageObject.messageOwner.fwd_from.saved_from_peer); + if (DialogObject.isChatDialog(id)) { TLRPC.Chat chat = getMessagesController().getChat(-id); if (chat != null) { name += " @ " + chat.title; @@ -1338,7 +1395,7 @@ public class NotificationsController extends BaseController { } String msg = null; - if ((int) dialogId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { userName[0] = null; return LocaleController.getString("NotificationHiddenMessage", R.string.NotificationHiddenMessage); } else { @@ -1364,7 +1421,7 @@ public class NotificationsController extends BaseController { return LocaleController.getString("CallMessageIncomingMissed", R.string.CallMessageIncomingMissed); } } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { - int singleUserId = messageObject.messageOwner.action.user_id; + long singleUserId = messageObject.messageOwner.action.user_id; if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) { singleUserId = messageObject.messageOwner.action.users.get(0); } @@ -1409,7 +1466,7 @@ public class NotificationsController extends BaseController { } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGroupCallScheduled) { return messageObject.messageText.toString(); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionInviteToGroupCall) { - int singleUserId = messageObject.messageOwner.action.user_id; + long singleUserId = messageObject.messageOwner.action.user_id; if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) { singleUserId = messageObject.messageOwner.action.users.get(0); } @@ -1695,6 +1752,18 @@ public class NotificationsController extends BaseController { } } } + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + String emoticon = ((TLRPC.TL_messageActionSetChatTheme) messageObject.messageOwner.action).emoticon; + if (TextUtils.isEmpty(emoticon)) { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChatThemeDisabledYou", R.string.ChatThemeDisabledYou) + : LocaleController.formatString("ChatThemeDisabled", R.string.ChatThemeDisabled, name, emoticon); + } else { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChangedChatThemeYou", R.string.ChatThemeChangedYou, emoticon) + : LocaleController.formatString("ChangedChatThemeTo", R.string.ChatThemeChangedTo, name, emoticon); + } + return msg; } } else { if (messageObject.isMediaEmpty()) { @@ -1780,23 +1849,23 @@ public class NotificationsController extends BaseController { if (AndroidUtilities.needShowPasscode() || SharedConfig.isWaitingForPasscodeEnter) { return LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage); } - long dialog_id = messageObject.messageOwner.dialog_id; - int chat_id = messageObject.messageOwner.peer_id.chat_id != 0 ? messageObject.messageOwner.peer_id.chat_id : messageObject.messageOwner.peer_id.channel_id; - int from_id = messageObject.messageOwner.peer_id.user_id; + long dialogId = messageObject.messageOwner.dialog_id; + long chatId = messageObject.messageOwner.peer_id.chat_id != 0 ? messageObject.messageOwner.peer_id.chat_id : messageObject.messageOwner.peer_id.channel_id; + long fromId = messageObject.messageOwner.peer_id.user_id; if (preview != null) { preview[0] = true; } SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); - boolean dialogPreviewEnabled = preferences.getBoolean("content_preview_" + dialog_id, true); + boolean dialogPreviewEnabled = preferences.getBoolean("content_preview_" + dialogId, true); if (messageObject.isFcmMessage()) { - if (chat_id == 0 && from_id != 0) { + if (chatId == 0 && fromId != 0) { if (!dialogPreviewEnabled || !preferences.getBoolean("EnablePreviewAll", true)) { if (preview != null) { preview[0] = false; } return LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, messageObject.localName); } - } else if (chat_id != 0) { + } else if (chatId != 0) { if (!dialogPreviewEnabled || !messageObject.localChannel && !preferences.getBoolean("EnablePreviewGroup", true) || messageObject.localChannel && !preferences.getBoolean("EnablePreviewChannel", true)) { if (preview != null) { preview[0] = false; @@ -1811,40 +1880,40 @@ public class NotificationsController extends BaseController { text[0] = true; return (String) messageObject.messageText; } - int selfUsedId = getUserConfig().getClientUserId(); - if (from_id == 0) { - from_id = messageObject.getFromChatId(); - if (from_id == 0) { - from_id = -chat_id; + long selfUsedId = getUserConfig().getClientUserId(); + if (fromId == 0) { + fromId = messageObject.getFromChatId(); + if (fromId == 0) { + fromId = -chatId; } - } else if (from_id == selfUsedId) { - from_id = messageObject.getFromChatId(); + } else if (fromId == selfUsedId) { + fromId = messageObject.getFromChatId(); } - if (dialog_id == 0) { - if (chat_id != 0) { - dialog_id = -chat_id; - } else if (from_id != 0) { - dialog_id = from_id; + if (dialogId == 0) { + if (chatId != 0) { + dialogId = -chatId; + } else if (fromId != 0) { + dialogId = fromId; } } String name = null; - if (from_id > 0) { + if (fromId > 0) { if (messageObject.messageOwner.from_scheduled) { - if (dialog_id == selfUsedId) { + if (dialogId == selfUsedId) { name = LocaleController.getString("MessageScheduledReminderNotification", R.string.MessageScheduledReminderNotification); } else { name = LocaleController.getString("NotificationMessageScheduledName", R.string.NotificationMessageScheduledName); } } else { - TLRPC.User user = getMessagesController().getUser(from_id); + TLRPC.User user = getMessagesController().getUser(fromId); if (user != null) { name = UserObject.getUserName(user); } } } else { - TLRPC.Chat chat = getMessagesController().getChat(-from_id); + TLRPC.Chat chat = getMessagesController().getChat(-fromId); if (chat != null) { name = chat.title; } @@ -1854,18 +1923,18 @@ public class NotificationsController extends BaseController { return null; } TLRPC.Chat chat = null; - if (chat_id != 0) { - chat = getMessagesController().getChat(chat_id); + if (chatId != 0) { + chat = getMessagesController().getChat(chatId); if (chat == null) { return null; } } String msg = null; - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage); } else { - if (chat_id == 0 && from_id != 0) { + if (chatId == 0 && fromId != 0) { if (dialogPreviewEnabled && preferences.getBoolean("EnablePreviewAll", true)) { if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { @@ -1885,6 +1954,18 @@ public class NotificationsController extends BaseController { } else { msg = LocaleController.getString("CallMessageIncomingMissed", R.string.CallMessageIncomingMissed); } + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + String emoticon = ((TLRPC.TL_messageActionSetChatTheme) messageObject.messageOwner.action).emoticon; + if (TextUtils.isEmpty(emoticon)) { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChatThemeDisabledYou", R.string.ChatThemeDisabledYou) + : LocaleController.formatString("ChatThemeDisabled", R.string.ChatThemeDisabled, name, emoticon); + } else { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChangedChatThemeYou", R.string.ChatThemeChangedYou, emoticon) + : LocaleController.formatString("ChangedChatThemeTo", R.string.ChatThemeChangedTo, name, emoticon); + } + text[0] = true; } } else { if (messageObject.isMediaEmpty()) { @@ -1980,12 +2061,12 @@ public class NotificationsController extends BaseController { } msg = LocaleController.formatString("NotificationMessageNoText", R.string.NotificationMessageNoText, name); } - } else if (chat_id != 0) { + } else if (chatId != 0) { boolean isChannel = ChatObject.isChannel(chat) && !chat.megagroup; if (dialogPreviewEnabled && (!isChannel && preferences.getBoolean("EnablePreviewGroup", true) || isChannel && preferences.getBoolean("EnablePreviewChannel", true))) { if (messageObject.messageOwner instanceof TLRPC.TL_messageService) { if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { - int singleUserId = messageObject.messageOwner.action.user_id; + long singleUserId = messageObject.messageOwner.action.user_id; if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) { singleUserId = messageObject.messageOwner.action.users.get(0); } @@ -2000,7 +2081,7 @@ public class NotificationsController extends BaseController { if (u2 == null) { return null; } - if (from_id == u2.id) { + if (fromId == u2.id) { if (chat.megagroup) { msg = LocaleController.formatString("NotificationGroupAddSelfMega", R.string.NotificationGroupAddSelfMega, name, chat.title); } else { @@ -2030,7 +2111,7 @@ public class NotificationsController extends BaseController { } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGroupCallScheduled) { msg = messageObject.messageText.toString(); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionInviteToGroupCall) { - int singleUserId = messageObject.messageOwner.action.user_id; + long singleUserId = messageObject.messageOwner.action.user_id; if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) { singleUserId = messageObject.messageOwner.action.users.get(0); } @@ -2079,7 +2160,7 @@ public class NotificationsController extends BaseController { } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) { if (messageObject.messageOwner.action.user_id == selfUsedId) { msg = LocaleController.formatString("NotificationGroupKickYou", R.string.NotificationGroupKickYou, name, chat.title); - } else if (messageObject.messageOwner.action.user_id == from_id) { + } else if (messageObject.messageOwner.action.user_id == fromId) { msg = LocaleController.formatString("NotificationGroupLeftMember", R.string.NotificationGroupLeftMember, name, chat.title); } else { TLRPC.User u2 = getMessagesController().getUser(messageObject.messageOwner.action.user_id); @@ -2246,6 +2327,17 @@ public class NotificationsController extends BaseController { } } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) { msg = messageObject.messageText.toString(); + } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + String emoticon = ((TLRPC.TL_messageActionSetChatTheme) messageObject.messageOwner.action).emoticon; + if (TextUtils.isEmpty(emoticon)) { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChatThemeDisabledYou", R.string.ChatThemeDisabledYou) + : LocaleController.formatString("ChatThemeDisabled", R.string.ChatThemeDisabled, name, emoticon); + } else { + msg = dialogId == selfUsedId + ? LocaleController.formatString("ChangedChatThemeYou", R.string.ChatThemeChangedYou, emoticon) + : LocaleController.formatString("ChangedChatThemeTo", R.string.ChatThemeChangedTo, name, emoticon); + } } } else if (ChatObject.isChannel(chat) && !chat.megagroup) { if (messageObject.isMediaEmpty()) { @@ -2412,7 +2504,7 @@ public class NotificationsController extends BaseController { PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, intent, 0); SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); int minutes = preferences.getInt("repeat_messages", 60); - if (minutes > 0 && personal_count > 0) { + if (minutes > 0 && personalCount > 0) { alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + minutes * 60 * 1000, pintent); } else { alarmManager.cancel(pintent); @@ -2471,15 +2563,6 @@ public class NotificationsController extends BaseController { } wearNotificationsIds.clear(); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.pushMessagesUpdated)); - if (WearDataLayerListenerService.isWatchConnected()) { - try { - JSONObject o = new JSONObject(); - o.put("id", getUserConfig().getClientUserId()); - o.put("cancel_all", true); - WearDataLayerListenerService.sendMessageToWatch("/notify", o.toString().getBytes(), "remote_notifications"); - } catch (JSONException ignore) { - } - } } catch (Exception e) { FileLog.e(e); } @@ -2499,7 +2582,7 @@ public class NotificationsController extends BaseController { try { SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); - int notifyOverride = getNotifyOverride(preferences, opened_dialog_id); + int notifyOverride = getNotifyOverride(preferences, openedDialogId); if (notifyOverride == 2) { return; } @@ -2744,7 +2827,7 @@ public class NotificationsController extends BaseController { } @SuppressLint("RestrictedApi") - private String createNotificationShortcut(NotificationCompat.Builder builder, int did, String name, TLRPC.User user, TLRPC.Chat chat, Person person) { + private String createNotificationShortcut(NotificationCompat.Builder builder, long did, String name, TLRPC.User user, TLRPC.Chat chat, Person person) { if (unsupportedNotificationShortcut() || ChatObject.isChannel(chat) && !chat.megagroup) { return null; } @@ -2780,12 +2863,13 @@ public class NotificationsController extends BaseController { builder.setShortcutInfo(shortcut); Intent intent = new Intent(ApplicationLoader.applicationContext, BubbleActivity.class); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); - if (did > 0) { + if (DialogObject.isUserDialog(did)) { intent.putExtra("userId", did); } else { intent.putExtra("chatId", -did); } intent.putExtra("currentAccount", currentAccount); + IconCompat icon; if (avatar != null) { icon = IconCompat.createWithAdaptiveBitmap(avatar); @@ -2798,7 +2882,7 @@ public class NotificationsController extends BaseController { new NotificationCompat.BubbleMetadata.Builder( PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT), icon); - bubbleBuilder.setSuppressNotification(opened_dialog_id == did); + bubbleBuilder.setSuppressNotification(openedDialogId == did); bubbleBuilder.setAutoExpandBubble(false); bubbleBuilder.setDesiredHeight(AndroidUtilities.dp(640)); builder.setBubbleMetadata(bubbleBuilder.build()); @@ -2947,7 +3031,7 @@ public class NotificationsController extends BaseController { } } - boolean secretChat = !isDefault && (int) dialogId == 0; + boolean secretChat = !isDefault && DialogObject.isEncryptedDialog(dialogId); boolean shouldOverwrite = !isInApp && overwriteKey != null && preferences.getBoolean(overwriteKey, false); if (isSilent) { @@ -3257,16 +3341,16 @@ public class NotificationsController extends BaseController { override_dialog_id = lastMessageObject.getFromChatId(); } int mid = lastMessageObject.getId(); - int chat_id = lastMessageObject.messageOwner.peer_id.chat_id != 0 ? lastMessageObject.messageOwner.peer_id.chat_id : lastMessageObject.messageOwner.peer_id.channel_id; - int user_id = lastMessageObject.messageOwner.peer_id.user_id; - if (lastMessageObject.isFromUser() && (user_id == 0 || user_id == getUserConfig().getClientUserId())) { - user_id = lastMessageObject.messageOwner.from_id.user_id; + long chatId = lastMessageObject.messageOwner.peer_id.chat_id != 0 ? lastMessageObject.messageOwner.peer_id.chat_id : lastMessageObject.messageOwner.peer_id.channel_id; + long userId = lastMessageObject.messageOwner.peer_id.user_id; + if (lastMessageObject.isFromUser() && (userId == 0 || userId == getUserConfig().getClientUserId())) { + userId = lastMessageObject.messageOwner.from_id.user_id; } - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); TLRPC.Chat chat = null; - if (chat_id != 0) { - chat = getMessagesController().getChat(chat_id); + if (chatId != 0) { + chat = getMessagesController().getChat(chatId); if (chat == null && lastMessageObject.isFcmMessage()) { isChannel = lastMessageObject.localChannel; } else { @@ -3292,7 +3376,7 @@ public class NotificationsController extends BaseController { String name; String chatName; boolean replace = true; - if (((chat_id != 0 && chat == null) || user == null) && lastMessageObject.isFcmMessage()) { + if (((chatId != 0 && chat == null) || user == null) && lastMessageObject.isFcmMessage()) { chatName = lastMessageObject.localName; } else if (chat != null) { chatName = chat.title; @@ -3300,9 +3384,9 @@ public class NotificationsController extends BaseController { chatName = UserObject.getUserName(user); } boolean passcode = AndroidUtilities.needShowPasscode() || SharedConfig.isWaitingForPasscodeEnter; - if ((int) dialog_id == 0 || pushDialogs.size() > 1 || passcode) { + if (DialogObject.isEncryptedDialog(dialog_id) || pushDialogs.size() > 1 || passcode) { if (passcode) { - if (chat_id != 0) { + if (chatId != 0) { name = LocaleController.getString("NotificationHiddenChatName", R.string.NotificationHiddenChatName); } else { name = LocaleController.getString("NotificationHiddenName", R.string.NotificationHiddenName); @@ -3456,7 +3540,7 @@ public class NotificationsController extends BaseController { } boolean vibrateOnlyIfSilent = false; - if (chat_id != 0) { + if (chatId != 0) { if (isChannel) { soundPath = preferences.getString("ChannelSoundPath", defaultPath); vibrate = preferences.getInt("vibrate_channel", 0); @@ -3470,7 +3554,7 @@ public class NotificationsController extends BaseController { ledColor = preferences.getInt("GroupLed", 0xff0000ff); chatType = TYPE_GROUP; } - } else if (user_id != 0) { + } else if (userId != 0) { soundPath = preferences.getString("GlobalSoundPath", defaultPath); vibrate = preferences.getInt("vibrate_messages", 0); importance = preferences.getInt("priority_messages", 1); @@ -3532,12 +3616,12 @@ public class NotificationsController extends BaseController { intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialog_id)) { if (pushDialogs.size() == 1) { - if (chat_id != 0) { - intent.putExtra("chatId", chat_id); - } else if (user_id != 0) { - intent.putExtra("userId", user_id); + if (chatId != 0) { + intent.putExtra("chatId", chatId); + } else if (userId != 0) { + intent.putExtra("userId", userId); } } if (AndroidUtilities.needShowPasscode() || SharedConfig.isWaitingForPasscodeEnter) { @@ -3557,7 +3641,7 @@ public class NotificationsController extends BaseController { } } else { if (pushDialogs.size() == 1 && dialog_id != globalSecretChatId) { - intent.putExtra("encId", (int) (dialog_id >> 32)); + intent.putExtra("encId", DialogObject.getEncryptedChatId(dialog_id)); } } intent.putExtra("currentAccount", currentAccount); @@ -3774,9 +3858,9 @@ public class NotificationsController extends BaseController { } @SuppressLint("InlinedApi") - private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, String summary, long dialogId, String chatName, long[] vibrationPattern, int ledColor, Uri sound, int importance, boolean isDefault, boolean isInApp, boolean isSilent, int chatType) { + private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, String summary, long lastDialogId, String chatName, long[] vibrationPattern, int ledColor, Uri sound, int importance, boolean isDefault, boolean isInApp, boolean isSilent, int chatType) { if (Build.VERSION.SDK_INT >= 26) { - notificationBuilder.setChannelId(validateChannelId(dialogId, chatName, vibrationPattern, ledColor, sound, importance, isDefault, isInApp, isSilent, chatType)); + notificationBuilder.setChannelId(validateChannelId(lastDialogId, chatName, vibrationPattern, ledColor, sound, importance, isDefault, isInApp, isSilent, chatType)); } Notification mainNotification = notificationBuilder.build(); if (Build.VERSION.SDK_INT < 18) { @@ -3813,19 +3897,19 @@ public class NotificationsController extends BaseController { class NotificationHolder { int id; - int lowerId; + long dialogId; String name; TLRPC.User user; TLRPC.Chat chat; NotificationCompat.Builder notification; - NotificationHolder(int i, int li, String n, TLRPC.User u, TLRPC.Chat c, NotificationCompat.Builder builder) { + NotificationHolder(int i, long li, String n, TLRPC.User u, TLRPC.Chat c, NotificationCompat.Builder builder) { id = i; name = n; user = u; chat = c; notification = builder; - lowerId = li; + dialogId = li; } void call() { @@ -3842,17 +3926,13 @@ public class NotificationsController extends BaseController { } ArrayList holders = new ArrayList<>(); - JSONArray serializedNotifications = null; - if (WearDataLayerListenerService.isWatchConnected()) { - serializedNotifications = new JSONArray(); - } boolean useSummaryNotification = Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1 || sortedDialogs.size() > 1; if (useSummaryNotification && Build.VERSION.SDK_INT >= 26) { checkOtherNotificationsChannel(); } - int selfUserId = getUserConfig().getClientUserId(); + long selfUserId = getUserConfig().getClientUserId(); boolean waitingForPasscode = AndroidUtilities.needShowPasscode() || SharedConfig.isWaitingForPasscodeEnter; int maxCount = 7; @@ -3861,34 +3941,19 @@ public class NotificationsController extends BaseController { if (holders.size() >= maxCount) { break; } - long dialog_id = sortedDialogs.get(b); - ArrayList messageObjects = messagesByDialogs.get(dialog_id); - int max_id = messageObjects.get(0).getId(); - int lowerId = (int) dialog_id; - int highId = (int) (dialog_id >> 32); + long dialogId = sortedDialogs.get(b); + ArrayList messageObjects = messagesByDialogs.get(dialogId); + int maxId = messageObjects.get(0).getId(); - Integer internalId = oldIdsWear.get(dialog_id); + Integer internalId = oldIdsWear.get(dialogId); if (internalId == null) { - if (lowerId != 0) { - internalId = lowerId; - } else { - internalId = highId; - } + internalId = lastInternalNotificationId++; } else { - oldIdsWear.remove(dialog_id); + oldIdsWear.remove(dialogId); } - JSONObject serializedChat = null; - if (serializedNotifications != null) { - serializedChat = new JSONObject(); - } - - /*if (lastWearNotifiedMessageId.get(dialog_id, 0) == max_id) { - continue; - } - lastWearNotifiedMessageId.put(dialog_id, max_id);*/ MessageObject lastMessageObject = messageObjects.get(0); - int max_date = lastMessageObject.messageOwner.date; + int maxDate = lastMessageObject.messageOwner.date; TLRPC.Chat chat = null; TLRPC.User user = null; boolean isChannel = false; @@ -3899,16 +3964,16 @@ public class NotificationsController extends BaseController { File avatalFile = null; boolean canReply; - if (lowerId != 0) { - canReply = lowerId != 777000; - if (lowerId > 0) { - user = getMessagesController().getUser(lowerId); + if (!DialogObject.isEncryptedDialog(dialogId)) { + canReply = dialogId != 777000; + if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); if (user == null) { if (lastMessageObject.isFcmMessage()) { name = lastMessageObject.localName; } else { if (BuildVars.LOGS_ENABLED) { - FileLog.w("not found user to show dialog notification " + lowerId); + FileLog.w("not found user to show dialog notification " + dialogId); } continue; } @@ -3918,13 +3983,13 @@ public class NotificationsController extends BaseController { photoPath = user.photo.photo_small; } } - if (UserObject.isReplyUser(lowerId)) { + if (UserObject.isReplyUser(dialogId)) { name = LocaleController.getString("RepliesTitle", R.string.RepliesTitle); - } else if (lowerId == selfUserId) { + } else if (dialogId == selfUserId) { name = LocaleController.getString("MessageScheduledReminderNotification", R.string.MessageScheduledReminderNotification); } } else { - chat = getMessagesController().getChat(-lowerId); + chat = getMessagesController().getChat(-dialogId); if (chat == null) { if (lastMessageObject.isFcmMessage()) { isSupergroup = lastMessageObject.isSupergroup(); @@ -3932,7 +3997,7 @@ public class NotificationsController extends BaseController { isChannel = lastMessageObject.localChannel; } else { if (BuildVars.LOGS_ENABLED) { - FileLog.w("not found chat to show dialog notification " + lowerId); + FileLog.w("not found chat to show dialog notification " + dialogId); } continue; } @@ -3947,11 +4012,12 @@ public class NotificationsController extends BaseController { } } else { canReply = false; - if (dialog_id != globalSecretChatId) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(highId); + if (dialogId != globalSecretChatId) { + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { if (BuildVars.LOGS_ENABLED) { - FileLog.w("not found secret chat to show dialog notification " + highId); + FileLog.w("not found secret chat to show dialog notification " + encryptedChatId); } continue; } @@ -3965,11 +4031,10 @@ public class NotificationsController extends BaseController { } name = LocaleController.getString("SecretChatName", R.string.SecretChatName); photoPath = null; - serializedChat = null; } if (waitingForPasscode) { - if (lowerId < 0) { + if (DialogObject.isChatDialog(dialogId)) { name = LocaleController.getString("NotificationHiddenChatName", R.string.NotificationHiddenChatName); } else { name = LocaleController.getString("NotificationHiddenName", R.string.NotificationHiddenName); @@ -4009,15 +4074,15 @@ public class NotificationsController extends BaseController { NotificationCompat.Action wearReplyAction = null; - if ((!isChannel || isSupergroup) && canReply && !SharedConfig.isWaitingForPasscodeEnter && selfUserId != lowerId && !UserObject.isReplyUser(lowerId)) { + if ((!isChannel || isSupergroup) && canReply && !SharedConfig.isWaitingForPasscodeEnter && selfUserId != dialogId && !UserObject.isReplyUser(dialogId)) { Intent replyIntent = new Intent(ApplicationLoader.applicationContext, WearReplyReceiver.class); - replyIntent.putExtra("dialog_id", dialog_id); - replyIntent.putExtra("max_id", max_id); + replyIntent.putExtra("dialog_id", dialogId); + replyIntent.putExtra("max_id", maxId); replyIntent.putExtra("currentAccount", currentAccount); PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(LocaleController.getString("Reply", R.string.Reply)).build(); String replyToString; - if (lowerId < 0) { + if (DialogObject.isChatDialog(dialogId)) { replyToString = LocaleController.formatString("ReplyToGroup", R.string.ReplyToGroup, name); } else { replyToString = LocaleController.formatString("ReplyToUser", R.string.ReplyToUser, name); @@ -4030,7 +4095,7 @@ public class NotificationsController extends BaseController { .build(); } - Integer count = pushDialogs.get(dialog_id); + Integer count = pushDialogs.get(dialogId); if (count == null) { count = 0; } @@ -4067,26 +4132,22 @@ public class NotificationsController extends BaseController { } else { messagingStyle = new NotificationCompat.MessagingStyle(""); } - if (Build.VERSION.SDK_INT < 28 || lowerId < 0 && !isChannel || UserObject.isReplyUser(lowerId)) { + if (Build.VERSION.SDK_INT < 28 || DialogObject.isChatDialog(dialogId) && !isChannel || UserObject.isReplyUser(dialogId)) { messagingStyle.setConversationTitle(conversationName); } - messagingStyle.setGroupConversation(Build.VERSION.SDK_INT < 28 || !isChannel && lowerId < 0 || UserObject.isReplyUser(lowerId)); + messagingStyle.setGroupConversation(Build.VERSION.SDK_INT < 28 || !isChannel && DialogObject.isChatDialog(dialogId) || UserObject.isReplyUser(dialogId)); StringBuilder text = new StringBuilder(); String[] senderName = new String[1]; boolean[] preview = new boolean[1]; ArrayList rows = null; int rowsMid = 0; - JSONArray serializedMsgs = null; - if (serializedChat != null) { - serializedMsgs = new JSONArray(); - } for (int a = messageObjects.size() - 1; a >= 0; a--) { MessageObject messageObject = messageObjects.get(a); String message = getShortStringForMessage(messageObject, senderName, preview); - if (dialog_id == selfUserId) { + if (dialogId == selfUserId) { senderName[0] = name; - } else if (lowerId < 0 && messageObject.messageOwner.from_scheduled) { + } else if (DialogObject.isChatDialog(dialogId) && messageObject.messageOwner.from_scheduled) { senderName[0] = LocaleController.getString("NotificationMessageScheduledName", R.string.NotificationMessageScheduledName); } if (message == null) { @@ -4098,7 +4159,7 @@ public class NotificationsController extends BaseController { if (text.length() > 0) { text.append("\n\n"); } - if (dialog_id != selfUserId && messageObject.messageOwner.from_scheduled && lowerId > 0) { + if (dialogId != selfUserId && messageObject.messageOwner.from_scheduled && DialogObject.isUserDialog(dialogId)) { message = String.format("%1$s: %2$s", LocaleController.getString("NotificationMessageScheduledName", R.string.NotificationMessageScheduledName), message); text.append(message); } else { @@ -4110,20 +4171,20 @@ public class NotificationsController extends BaseController { } long uid; - if (lowerId > 0) { - uid = lowerId; + if (DialogObject.isUserDialog(dialogId)) { + uid = dialogId; } else if (isChannel) { - uid = -lowerId; - } else if (lowerId < 0) { + uid = -dialogId; + } else if (DialogObject.isChatDialog(dialogId)) { uid = messageObject.getSenderId(); } else { - uid = dialog_id; + uid = dialogId; } Person person = personCache.get(uid); String personName = ""; if (senderName[0] == null) { if (waitingForPasscode) { - if (lowerId < 0) { + if (DialogObject.isChatDialog(dialogId)) { if (isChannel) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1) { personName = LocaleController.getString("NotificationHiddenChatName", R.string.NotificationHiddenChatName); @@ -4140,12 +4201,12 @@ public class NotificationsController extends BaseController { } if (person == null || !TextUtils.equals(person.getName(), personName)) { Person.Builder personBuilder = new Person.Builder().setName(personName); - if (preview[0] && lowerId != 0 && Build.VERSION.SDK_INT >= 28) { + if (preview[0] && !DialogObject.isEncryptedDialog(dialogId) && Build.VERSION.SDK_INT >= 28) { File avatar = null; - if (lowerId > 0 || isChannel) { + if (DialogObject.isUserDialog(dialogId) || isChannel) { avatar = avatalFile; } else { - int fromId = messageObject.getSenderId(); + long fromId = messageObject.getSenderId(); TLRPC.User sender = getMessagesController().getUser(fromId); if (sender == null) { sender = getMessagesStorage().getUserSync(fromId); @@ -4163,7 +4224,7 @@ public class NotificationsController extends BaseController { personCache.put(uid, person); } - if (lowerId != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { boolean setPhoto = false; if (preview[0] && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && !((ActivityManager) ApplicationLoader.applicationContext.getSystemService(Context.ACTIVITY_SERVICE)).isLowRamDevice()) { if (!waitingForPasscode && !messageObject.isSecretMedia() && (messageObject.type == 1 || messageObject.isSticker())) { @@ -4193,7 +4254,7 @@ public class NotificationsController extends BaseController { if (uri != null) { msg.setData(mimeType, uri); messagingStyle.addMessage(msg); - final Uri uriFinal = uri; + Uri uriFinal = uri; ApplicationLoader.applicationContext.grantUriPermission("com.android.systemui", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION); AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.revokeUriPermission(uriFinal, Intent.FLAG_GRANT_READ_URI_PERMISSION), 20000); @@ -4231,24 +4292,7 @@ public class NotificationsController extends BaseController { messagingStyle.addMessage(message, ((long) messageObject.messageOwner.date) * 1000, person); } - if (serializedMsgs != null) { - try { - JSONObject jmsg = new JSONObject(); - jmsg.put("text", message); - jmsg.put("date", messageObject.messageOwner.date); - if (messageObject.isFromUser() && lowerId < 0) { - TLRPC.User sender = getMessagesController().getUser(messageObject.getSenderId()); - if (sender != null) { - jmsg.put("fname", sender.first_name); - jmsg.put("lname", sender.last_name); - } - } - serializedMsgs.put(jmsg); - } catch (JSONException ignore) { - } - } - - if (dialog_id == 777000 && messageObject.messageOwner.reply_markup != null) { + if (dialogId == 777000 && messageObject.messageOwner.reply_markup != null) { rows = messageObject.messageOwner.reply_markup.rows; rowsMid = messageObject.getId(); } @@ -4258,14 +4302,12 @@ public class NotificationsController extends BaseController { intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addCategory(Intent.CATEGORY_LAUNCHER); - if (lowerId != 0) { - if (lowerId > 0) { - intent.putExtra("userId", lowerId); - } else { - intent.putExtra("chatId", -lowerId); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + intent.putExtra("encId", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + intent.putExtra("userId", dialogId); } else { - intent.putExtra("encId", highId); + intent.putExtra("chatId", -dialogId); } intent.putExtra("currentAccount", currentAccount); PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); @@ -4277,8 +4319,8 @@ public class NotificationsController extends BaseController { Intent msgHeardIntent = new Intent(ApplicationLoader.applicationContext, AutoMessageHeardReceiver.class); msgHeardIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgHeardIntent.setAction("org.telegram.messenger.ACTION_MESSAGE_HEARD"); - msgHeardIntent.putExtra("dialog_id", dialog_id); - msgHeardIntent.putExtra("max_id", max_id); + msgHeardIntent.putExtra("dialog_id", dialogId); + msgHeardIntent.putExtra("max_id", maxId); msgHeardIntent.putExtra("currentAccount", currentAccount); PendingIntent readPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Action readAction = new NotificationCompat.Action.Builder(R.drawable.menu_read, LocaleController.getString("MarkAsRead", R.string.MarkAsRead), readPendingIntent) @@ -4287,14 +4329,14 @@ public class NotificationsController extends BaseController { .build(); String dismissalID; - if (lowerId != 0) { - if (lowerId > 0) { - dismissalID = "tguser" + lowerId + "_" + max_id; + if (!DialogObject.isEncryptedDialog(dialogId)) { + if (DialogObject.isUserDialog(dialogId)) { + dismissalID = "tguser" + dialogId + "_" + maxId; } else { - dismissalID = "tgchat" + (-lowerId) + "_" + max_id; + dismissalID = "tgchat" + (-dialogId) + "_" + maxId; } - } else if (dialog_id != globalSecretChatId) { - dismissalID = "tgenc" + highId + "_" + max_id; + } else if (dialogId != globalSecretChatId) { + dismissalID = "tgenc" + DialogObject.getEncryptedChatId(dialogId) + "_" + maxId; } else { dismissalID = null; } @@ -4326,8 +4368,8 @@ public class NotificationsController extends BaseController { .setCategory(NotificationCompat.CATEGORY_MESSAGE); Intent dismissIntent = new Intent(ApplicationLoader.applicationContext, NotificationDismissReceiver.class); - dismissIntent.putExtra("messageDate", max_date); - dismissIntent.putExtra("dialogId", dialog_id); + dismissIntent.putExtra("messageDate", maxDate); + dismissIntent.putExtra("dialogId", dialogId); dismissIntent.putExtra("currentAccount", currentAccount); builder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT)); @@ -4345,7 +4387,7 @@ public class NotificationsController extends BaseController { if (sortedDialogs.size() == 1 && !TextUtils.isEmpty(summary)) { builder.setSubText(summary); } - if (lowerId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { builder.setLocalOnly(true); } if (avatarBitmap != null) { @@ -4361,7 +4403,7 @@ public class NotificationsController extends BaseController { if (button instanceof TLRPC.TL_keyboardButtonCallback) { Intent callbackIntent = new Intent(ApplicationLoader.applicationContext, NotificationCallbackReceiver.class); callbackIntent.putExtra("currentAccount", currentAccount); - callbackIntent.putExtra("did", dialog_id); + callbackIntent.putExtra("did", dialogId); if (button.data != null) { callbackIntent.putExtra("data", button.data); } @@ -4380,37 +4422,8 @@ public class NotificationsController extends BaseController { if (Build.VERSION.SDK_INT >= 26) { setNotificationChannel(mainNotification, builder, useSummaryNotification); } - holders.add(new NotificationHolder(internalId, lowerId, name, user, chat, builder)); - wearNotificationsIds.put(dialog_id, internalId); - - if (lowerId != 0) { - try { - if (serializedChat != null) { - serializedChat.put("reply", canReply); - serializedChat.put("name", name); - serializedChat.put("max_id", max_id); - serializedChat.put("max_date", max_date); - serializedChat.put("id", Math.abs(lowerId)); - if (photoPath != null) { - serializedChat.put("photo", photoPath.dc_id + "_" + photoPath.volume_id + "_" + photoPath.secret); - } - if (serializedMsgs != null) { - serializedChat.put("msgs", serializedMsgs); - } - if (lowerId > 0) { - serializedChat.put("type", "user"); - } else { - if (isChannel || isSupergroup) { - serializedChat.put("type", "channel"); - } else { - serializedChat.put("type", "group"); - } - } - serializedNotifications.put(serializedChat); - } - } catch (JSONException ignore) { - } - } + holders.add(new NotificationHolder(internalId, dialogId, name, user, chat, builder)); + wearNotificationsIds.put(dialogId, internalId); } if (useSummaryNotification) { @@ -4421,7 +4434,7 @@ public class NotificationsController extends BaseController { notificationManager.notify(notificationId, mainNotification); } catch (SecurityException e) { FileLog.e(e); - resetNotificationSound(notificationBuilder, dialogId, chatName, vibrationPattern, ledColor, sound, importance, isDefault, isInApp, isSilent, chatType); + resetNotificationSound(notificationBuilder, lastDialogId, chatName, vibrationPattern, ledColor, sound, importance, isDefault, isInApp, isSilent, chatType); } } else { if (openedInBubbleDialogs.isEmpty()) { @@ -4445,8 +4458,8 @@ public class NotificationsController extends BaseController { for (int a = 0, size = holders.size(); a < size; a++) { NotificationHolder holder = holders.get(a); ids.clear(); - if (Build.VERSION.SDK_INT >= 29 && holder.lowerId != 0) { - String shortcutId = createNotificationShortcut(holder.notification, holder.lowerId, holder.name, holder.user, holder.chat, personCache.get(holder.lowerId)); + if (Build.VERSION.SDK_INT >= 29 && !DialogObject.isEncryptedDialog(holder.dialogId)) { + String shortcutId = createNotificationShortcut(holder.notification, holder.dialogId, holder.name, holder.user, holder.chat, personCache.get(holder.dialogId)); if (shortcutId != null) { ids.add(shortcutId); } @@ -4456,16 +4469,6 @@ public class NotificationsController extends BaseController { ShortcutManagerCompat.removeDynamicShortcuts(ApplicationLoader.applicationContext, ids); } } - - if (serializedNotifications != null) { - try { - JSONObject s = new JSONObject(); - s.put("id", selfUserId); - s.put("n", serializedNotifications); - WearDataLayerListenerService.sendMessageToWatch("/notify", s.toString().getBytes(), "remote_notifications"); - } catch (Exception ignore) { - } - } } @TargetApi(Build.VERSION_CODES.P) @@ -4608,11 +4611,11 @@ public class NotificationsController extends BaseController { updateServerNotificationsSettings(dialog_id, true); } - public void updateServerNotificationsSettings(long dialog_id, boolean post) { + public void updateServerNotificationsSettings(long dialogId, boolean post) { if (post) { getNotificationCenter().postNotificationName(NotificationCenter.notificationsSettingsUpdated); } - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { return; } SharedPreferences preferences = getAccountInstance().getNotificationsSettings(); @@ -4620,23 +4623,23 @@ public class NotificationsController extends BaseController { req.settings = new TLRPC.TL_inputPeerNotifySettings(); req.settings.flags |= 1; - req.settings.show_previews = preferences.getBoolean("content_preview_" + dialog_id, true); + req.settings.show_previews = preferences.getBoolean("content_preview_" + dialogId, true); req.settings.flags |= 2; - req.settings.silent = preferences.getBoolean("silent_" + dialog_id, false); + req.settings.silent = preferences.getBoolean("silent_" + dialogId, false); - int mute_type = preferences.getInt("notify2_" + dialog_id, -1); + int mute_type = preferences.getInt("notify2_" + dialogId, -1); if (mute_type != -1) { req.settings.flags |= 4; if (mute_type == 3) { - req.settings.mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0); + req.settings.mute_until = preferences.getInt("notifyuntil_" + dialogId, 0); } else { req.settings.mute_until = mute_type != 2 ? 0 : Integer.MAX_VALUE; } } req.peer = new TLRPC.TL_inputNotifyPeer(); - ((TLRPC.TL_inputNotifyPeer) req.peer).peer = getMessagesController().getInputPeer((int) dialog_id); + ((TLRPC.TL_inputNotifyPeer) req.peer).peer = getMessagesController().getInputPeer(dialogId); getConnectionsManager().sendRequest(req, (response, error) -> { }); @@ -4669,14 +4672,13 @@ public class NotificationsController extends BaseController { }); } - public boolean isGlobalNotificationsEnabled(long did) { - return isGlobalNotificationsEnabled(did, null); + public boolean isGlobalNotificationsEnabled(long dialogId) { + return isGlobalNotificationsEnabled(dialogId, null); } - public boolean isGlobalNotificationsEnabled(long did, Boolean forceChannel) { + public boolean isGlobalNotificationsEnabled(long dialogId, Boolean forceChannel) { int type; - int lower_id = (int) did; - if (lower_id < 0) { + if (DialogObject.isChatDialog(dialogId)) { if (forceChannel != null) { if (forceChannel) { type = TYPE_CHANNEL; @@ -4684,7 +4686,7 @@ public class NotificationsController extends BaseController { type = TYPE_GROUP; } } else { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (ChatObject.isChannel(chat) && !chat.megagroup) { type = TYPE_CHANNEL; } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/OpenChatReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/OpenChatReceiver.java index 510617598..a85575515 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/OpenChatReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/OpenChatReceiver.java @@ -22,14 +22,15 @@ public class OpenChatReceiver extends Activity { Intent intent = getIntent(); if (intent == null) { finish(); + return; } if (intent.getAction() == null || !intent.getAction().startsWith("com.tmessages.openchat")) { finish(); return; } try { - int chatId = intent.getIntExtra("chatId", 0); - int userId = intent.getIntExtra("userId", 0); + long chatId = intent.getLongExtra("chatId", 0); + long userId = intent.getLongExtra("userId", 0); int encId = intent.getIntExtra("encId", 0); if (chatId == 0 && userId == 0 && encId == 0) { return; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SecretChatHelper.java b/TMessagesProj/src/main/java/org/telegram/messenger/SecretChatHelper.java index 1dd756f61..d25e8e7b4 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SecretChatHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SecretChatHelper.java @@ -12,11 +12,11 @@ import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; -import android.util.LongSparseArray; import android.util.SparseArray; import android.util.SparseIntArray; import org.telegram.SQLite.SQLiteCursor; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.NativeByteBuffer; @@ -66,7 +66,7 @@ public class SecretChatHelper extends BaseController { } } - public static final int CURRENT_SECRET_CHAT_LAYER = 101; + public static int CURRENT_SECRET_CHAT_LAYER = 101; private ArrayList sendingNotifyLayer = new ArrayList<>(); private SparseArray> secretHolesQueue = new SparseArray<>(); @@ -110,7 +110,7 @@ public class SecretChatHelper extends BaseController { protected void processPendingEncMessages() { if (!pendingEncMessagesToDelete.isEmpty()) { - final ArrayList pendingEncMessagesToDeleteCopy = new ArrayList<>(pendingEncMessagesToDelete); + ArrayList pendingEncMessagesToDeleteCopy = new ArrayList<>(pendingEncMessagesToDelete); AndroidUtilities.runOnUIThread(() -> { for (int a = 0; a < pendingEncMessagesToDeleteCopy.size(); a++) { MessageObject messageObject = getMessagesController().dialogMessagesByRandomIds.get(pendingEncMessagesToDeleteCopy.get(a)); @@ -125,7 +125,7 @@ public class SecretChatHelper extends BaseController { } } - private TLRPC.TL_messageService createServiceSecretMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.DecryptedMessageAction decryptedMessage) { + private TLRPC.TL_messageService createServiceSecretMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.DecryptedMessageAction decryptedMessage) { TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService(); newMsg.action = new TLRPC.TL_messageEncryptedAction(); @@ -136,7 +136,7 @@ public class SecretChatHelper extends BaseController { newMsg.unread = true; newMsg.out = true; newMsg.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; - newMsg.dialog_id = ((long) encryptedChat.id) << 32; + newMsg.dialog_id = DialogObject.makeEncryptedDialogId(encryptedChat.id); newMsg.peer_id = new TLRPC.TL_peerUser(); newMsg.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; if (encryptedChat.participant_id == getUserConfig().getClientUserId()) { @@ -179,22 +179,22 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap usersDict) { - final TLRPC.EncryptedChat newChat = update.chat; - long dialog_id = ((long) newChat.id) << 32; + protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap usersDict) { + TLRPC.EncryptedChat newChat = update.chat; + long dialog_id = DialogObject.makeEncryptedDialogId(newChat.id); TLRPC.EncryptedChat existingChat = getMessagesController().getEncryptedChatDB(newChat.id, false); if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) { - int user_id = newChat.participant_id; - if (user_id == getUserConfig().getClientUserId()) { - user_id = newChat.admin_id; + long userId = newChat.participant_id; + if (userId == getUserConfig().getClientUserId()) { + userId = newChat.admin_id; } - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { - user = usersDict.get(user_id); + user = usersDict.get(userId); } - newChat.user_id = user_id; - final TLRPC.Dialog dialog = new TLRPC.TL_dialog(); + newChat.user_id = userId; + TLRPC.Dialog dialog = new TLRPC.TL_dialog(); dialog.id = dialog_id; dialog.folder_id = newChat.folder_id; dialog.unread_count = 0; @@ -223,7 +223,7 @@ public class SecretChatHelper extends BaseController { delayedEncryptedChatUpdates.add(update); } } else { - final TLRPC.EncryptedChat exist = existingChat; + TLRPC.EncryptedChat exist = existingChat; if (exist != null) { newChat.user_id = exist.user_id; newChat.auth_key = exist.auth_key; @@ -288,7 +288,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendNotifyLayerMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { + public void sendNotifyLayerMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -312,7 +312,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendRequestKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { + public void sendRequestKeyMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -335,7 +335,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendAcceptKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { + public void sendAcceptKeyMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -359,7 +359,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendCommitKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { + public void sendCommitKeyMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -382,7 +382,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendAbortKeyMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage, long excange_id) { + public void sendAbortKeyMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage, long excange_id) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -404,7 +404,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendNoopMessage(final TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { + public void sendNoopMessage(TLRPC.EncryptedChat encryptedChat, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -424,7 +424,7 @@ public class SecretChatHelper extends BaseController { performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); } - public void sendResendMessage(final TLRPC.EncryptedChat encryptedChat, int start, int end, TLRPC.Message resendMessage) { + public void sendResendMessage(TLRPC.EncryptedChat encryptedChat, int start, int end, TLRPC.Message resendMessage) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) { return; } @@ -581,13 +581,13 @@ public class SecretChatHelper extends BaseController { return message.action instanceof TLRPC.TL_messageEncryptedAction && !(message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages || message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL); } - protected void performSendEncryptedRequest(final TLRPC.TL_messages_sendEncryptedMultiMedia req, final SendMessagesHelper.DelayedMessage message) { + protected void performSendEncryptedRequest(TLRPC.TL_messages_sendEncryptedMultiMedia req, SendMessagesHelper.DelayedMessage message) { for (int a = 0; a < req.files.size(); a++) { performSendEncryptedRequest(req.messages.get(a), message.messages.get(a), message.encryptedChat, req.files.get(a), message.originalPaths.get(a), message.messageObjects.get(a)); } } - protected void performSendEncryptedRequest(final TLRPC.DecryptedMessage req, final TLRPC.Message newMsgObj, final TLRPC.EncryptedChat chat, final TLRPC.InputEncryptedFile encryptedFile, final String originalPath, final MessageObject newMsg) { + protected void performSendEncryptedRequest(TLRPC.DecryptedMessage req, TLRPC.Message newMsgObj, TLRPC.EncryptedChat chat, TLRPC.InputEncryptedFile encryptedFile, String originalPath, MessageObject newMsg) { if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) { return; } @@ -627,11 +627,9 @@ public class SecretChatHelper extends BaseController { } getMessagesStorage().updateEncryptedChatSeq(chat, false); - if (newMsgObj != null) { - newMsgObj.seq_in = layer.in_seq_no; - newMsgObj.seq_out = layer.out_seq_no; - getMessagesStorage().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out); - } + newMsgObj.seq_in = layer.in_seq_no; + newMsgObj.seq_out = layer.out_seq_no; + getMessagesStorage().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out); } else { layer.in_seq_no = newMsgObj.seq_in; layer.out_seq_no = newMsgObj.seq_out; @@ -741,47 +739,45 @@ public class SecretChatHelper extends BaseController { getMessagesStorage().updateEncryptedChatLayer(currentChat); } } - if (newMsgObj != null) { - if (error == null) { - final String attachPath = newMsgObj.attachPath; - final TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; - if (isSecretVisibleMessage(newMsgObj)) { - newMsgObj.date = res.date; - } - int existFlags; - if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) { - updateMediaPaths(newMsg, res.file, req, originalPath); - existFlags = newMsg.getMediaExistanceFlags(); - } else { - existFlags = 0; - } - getMessagesStorage().getStorageQueue().postRunnable(() -> { - if (isSecretInvisibleMessage(newMsgObj)) { - res.date = 0; - } - getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, (long) newMsgObj.id, newMsgObj.id, res.date, false, 0, 0); - AndroidUtilities.runOnUIThread(() -> { - newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; - getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false); - getSendMessagesHelper().processSentMessage(newMsgObj.id); - if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) { - getSendMessagesHelper().stopVideoService(attachPath); - } - getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false); - }); - }); + if (error == null) { + String attachPath = newMsgObj.attachPath; + TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; + if (isSecretVisibleMessage(newMsgObj)) { + newMsgObj.date = res.date; + } + int existFlags; + if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) { + updateMediaPaths(newMsg, res.file, req, originalPath); + existFlags = newMsg.getMediaExistanceFlags(); } else { - getMessagesStorage().markMessageAsSendError(newMsgObj, false); + existFlags = 0; + } + getMessagesStorage().getStorageQueue().postRunnable(() -> { + if (isSecretInvisibleMessage(newMsgObj)) { + res.date = 0; + } + getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, 0, newMsgObj.id, newMsgObj.id, res.date, false, 0); AndroidUtilities.runOnUIThread(() -> { - newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; - getNotificationCenter().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); + newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; + getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false); getSendMessagesHelper().processSentMessage(newMsgObj.id); if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) { - getSendMessagesHelper().stopVideoService(newMsgObj.attachPath); + getSendMessagesHelper().stopVideoService(attachPath); } getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false); }); - } + }); + } else { + getMessagesStorage().markMessageAsSendError(newMsgObj, false); + AndroidUtilities.runOnUIThread(() -> { + newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; + getNotificationCenter().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); + getSendMessagesHelper().processSentMessage(newMsgObj.id); + if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) { + getSendMessagesHelper().stopVideoService(newMsgObj.attachPath); + } + getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false); + }); } }, ConnectionsManager.RequestFlagInvokeAfter); } catch (Exception e) { @@ -790,7 +786,7 @@ public class SecretChatHelper extends BaseController { }); } - private void applyPeerLayer(final TLRPC.EncryptedChat chat, int newPeerLayer) { + private void applyPeerLayer(TLRPC.EncryptedChat chat, int newPeerLayer) { int currentPeerLayer = AndroidUtilities.getPeerLayerVersion(chat.layer); if (newPeerLayer <= currentPeerLayer) { return; @@ -815,9 +811,9 @@ public class SecretChatHelper extends BaseController { AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.encryptedChatUpdated, chat)); } - public TLRPC.Message processDecryptedObject(final TLRPC.EncryptedChat chat, final TLRPC.EncryptedFile file, int date, TLObject object, boolean new_key_used) { + public TLRPC.Message processDecryptedObject(TLRPC.EncryptedChat chat, TLRPC.EncryptedFile file, int date, TLObject object, boolean new_key_used) { if (object != null) { - int from_id = chat.admin_id; + long from_id = chat.admin_id; if (from_id == getUserConfig().getClientUserId()) { from_id = chat.participant_id; } @@ -869,7 +865,7 @@ public class SecretChatHelper extends BaseController { newMessage.grouped_id = decryptedMessage.grouped_id; newMessage.flags |= 131072; } - newMessage.dialog_id = ((long) chat.id) << 32; + newMessage.dialog_id = DialogObject.makeEncryptedDialogId(chat.id); if (decryptedMessage.reply_to_random_id != 0) { newMessage.reply_to = new TLRPC.TL_messageReplyHeader(); newMessage.reply_to.reply_to_random_id = decryptedMessage.reply_to_random_id; @@ -1117,7 +1113,7 @@ public class SecretChatHelper extends BaseController { } return newMessage; } else if (object instanceof TLRPC.TL_decryptedMessageService) { - final TLRPC.TL_decryptedMessageService serviceMessage = (TLRPC.TL_decryptedMessageService) object; + TLRPC.TL_decryptedMessageService serviceMessage = (TLRPC.TL_decryptedMessageService) object; if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL || serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) { TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService(); if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) { @@ -1128,7 +1124,7 @@ public class SecretChatHelper extends BaseController { chat.ttl = serviceMessage.action.ttl_seconds; newMessage.action.encryptedAction = serviceMessage.action; getMessagesStorage().updateEncryptedChatTTL(chat); - } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) { + } else { newMessage.action = new TLRPC.TL_messageEncryptedAction(); newMessage.action.encryptedAction = serviceMessage.action; } @@ -1141,10 +1137,10 @@ public class SecretChatHelper extends BaseController { newMessage.from_id.user_id = from_id; newMessage.peer_id = new TLRPC.TL_peerUser(); newMessage.peer_id.user_id = getUserConfig().getClientUserId(); - newMessage.dialog_id = ((long) chat.id) << 32; + newMessage.dialog_id = DialogObject.makeEncryptedDialogId(chat.id); return newMessage; } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionFlushHistory) { - final long did = ((long) chat.id) << 32; + long did = DialogObject.makeEncryptedDialogId(chat.id); AndroidUtilities.runOnUIThread(() -> { TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(did); if (dialog != null) { @@ -1153,7 +1149,7 @@ public class SecretChatHelper extends BaseController { } getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { getNotificationsController().processReadMessages(null, did, 0, Integer.MAX_VALUE, false); - LongSparseArray dialogsToUpdate = new LongSparseArray<>(1); + LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1); dialogsToUpdate.put(did, 0); getNotificationsController().processDialogsUpdateRead(dialogsToUpdate); })); @@ -1353,7 +1349,7 @@ public class SecretChatHelper extends BaseController { newMsg.unread = true; newMsg.out = true; newMsg.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; - newMsg.dialog_id = ((long) encryptedChat.id) << 32; + newMsg.dialog_id = DialogObject.makeEncryptedDialogId(encryptedChat.id); newMsg.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; newMsg.seq_in = seq_in; newMsg.seq_out = seq_out; @@ -1368,7 +1364,7 @@ public class SecretChatHelper extends BaseController { return newMsg; } - private void resendMessages(final int startSeq, final int endSeq, final TLRPC.EncryptedChat encryptedChat) { + private void resendMessages(int startSeq, int endSeq, TLRPC.EncryptedChat encryptedChat) { if (encryptedChat == null || endSeq - startSeq < 0) { return; } @@ -1386,13 +1382,13 @@ public class SecretChatHelper extends BaseController { return; } - long dialog_id = ((long) encryptedChat.id) << 32; + long dialog_id = DialogObject.makeEncryptedDialogId(encryptedChat.id); SparseArray messagesToResend = new SparseArray<>(); - final ArrayList messages = new ArrayList<>(); + ArrayList messages = new ArrayList<>(); for (int a = sSeq; a <= endSeq; a += 2) { messagesToResend.put(a, null); } - cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT m.data, r.random_id, s.seq_in, s.seq_out, m.ttl, s.mid FROM messages_seq as s LEFT JOIN randoms as r ON r.mid = s.mid LEFT JOIN messages as m ON m.mid = s.mid WHERE m.uid = %d AND m.out = 1 AND s.seq_out >= %d AND s.seq_out <= %d ORDER BY seq_out ASC", dialog_id, sSeq, endSeq)); + cursor = getMessagesStorage().getDatabase().queryFinalized(String.format(Locale.US, "SELECT m.data, r.random_id, s.seq_in, s.seq_out, m.ttl, s.mid FROM messages_seq as s LEFT JOIN randoms_v2 as r ON r.mid = s.mid LEFT JOIN messages_v2 as m ON m.mid = s.mid WHERE m.uid = %d AND m.out = 1 AND s.seq_out >= %d AND s.seq_out <= %d ORDER BY seq_out ASC", dialog_id, sSeq, endSeq)); while (cursor.next()) { TLRPC.Message message; long random_id = cursor.longValue(1); @@ -1551,7 +1547,7 @@ public class SecretChatHelper extends BaseController { } protected ArrayList decryptMessage(TLRPC.EncryptedMessage message) { - final TLRPC.EncryptedChat chat = getMessagesController().getEncryptedChatDB(message.chat_id, true); + TLRPC.EncryptedChat chat = getMessagesController().getEncryptedChatDB(message.chat_id, true); if (chat == null || chat instanceof TLRPC.TL_encryptedChatDiscarded) { return null; } @@ -1600,7 +1596,7 @@ public class SecretChatHelper extends BaseController { } } else { decryptedWithVersion = 2; - if (!decryptWithMtProtoVersion(is, keyToDecrypt, messageKey, 2, incoming, tryAnotherDecrypt)) { + if (!decryptWithMtProtoVersion(is, keyToDecrypt, messageKey, 2, incoming, true)) { return null; } } @@ -1613,7 +1609,7 @@ public class SecretChatHelper extends BaseController { chat.key_use_count_in++; } if (object instanceof TLRPC.TL_decryptedMessageLayer) { - final TLRPC.TL_decryptedMessageLayer layer = (TLRPC.TL_decryptedMessageLayer) object; + TLRPC.TL_decryptedMessageLayer layer = (TLRPC.TL_decryptedMessageLayer) object; if (chat.seq_in == 0 && chat.seq_out == 0) { if (chat.admin_id == getUserConfig().getClientUserId()) { chat.seq_out = 1; @@ -1650,7 +1646,7 @@ public class SecretChatHelper extends BaseController { } if (arr.size() >= 4) { secretHolesQueue.remove(chat.id); - final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); + TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); newChat.id = chat.id; newChat.user_id = chat.user_id; newChat.auth_key = chat.auth_key; @@ -1708,8 +1704,8 @@ public class SecretChatHelper extends BaseController { return null; } - public void requestNewSecretChatKey(final TLRPC.EncryptedChat encryptedChat) { - final byte[] salt = new byte[256]; + public void requestNewSecretChatKey(TLRPC.EncryptedChat encryptedChat) { + byte[] salt = new byte[256]; Utilities.random.nextBytes(salt); BigInteger i_g_a = BigInteger.valueOf(getMessagesStorage().getSecretG()); @@ -1730,7 +1726,7 @@ public class SecretChatHelper extends BaseController { sendRequestKeyMessage(encryptedChat, null); } - public void processAcceptedSecretChat(final TLRPC.EncryptedChat encryptedChat) { + public void processAcceptedSecretChat(TLRPC.EncryptedChat encryptedChat) { BigInteger p = new BigInteger(1, getMessagesStorage().getSecretPBytes()); BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b); @@ -1775,7 +1771,7 @@ public class SecretChatHelper extends BaseController { sendNotifyLayerMessage(encryptedChat, null); }); } else { - final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); + TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); newChat.id = encryptedChat.id; newChat.user_id = encryptedChat.user_id; newChat.auth_key = encryptedChat.auth_key; @@ -1825,7 +1821,7 @@ public class SecretChatHelper extends BaseController { }); } - public void acceptSecretChat(final TLRPC.EncryptedChat encryptedChat) { + public void acceptSecretChat(TLRPC.EncryptedChat encryptedChat) { if (acceptingChats.get(encryptedChat.id) != null) { return; } @@ -1903,7 +1899,7 @@ public class SecretChatHelper extends BaseController { getConnectionsManager().sendRequest(req2, (response1, error1) -> { acceptingChats.remove(encryptedChat.id); if (error1 == null) { - final TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response1; + TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response1; newChat.auth_key = encryptedChat.auth_key; newChat.user_id = encryptedChat.user_id; newChat.seq_in = encryptedChat.seq_in; @@ -1925,16 +1921,16 @@ public class SecretChatHelper extends BaseController { }); } - public void startSecretChat(final Context context, final TLRPC.User user) { + public void startSecretChat(Context context, TLRPC.User user) { if (user == null || context == null) { return; } startingSecretChat = true; - final AlertDialog progressDialog = new AlertDialog(context, 3); + AlertDialog progressDialog = new AlertDialog(context, 3); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig(); req.random_length = 256; req.version = getMessagesStorage().getLastSecretVersion(); - final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { if (error == null) { TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; if (response instanceof TLRPC.TL_messages_dhConfig) { @@ -1955,7 +1951,7 @@ public class SecretChatHelper extends BaseController { getMessagesStorage().setLastSecretVersion(res.version); getMessagesStorage().saveSecretParams(getMessagesStorage().getLastSecretVersion(), getMessagesStorage().getSecretG(), getMessagesStorage().getSecretPBytes()); } - final byte[] salt = new byte[256]; + byte[] salt = new byte[256]; for (int a = 0; a < 256; a++) { salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[a]); } @@ -1991,7 +1987,7 @@ public class SecretChatHelper extends BaseController { chat.a_or_b = salt; getMessagesController().putEncryptedChat(chat, false); TLRPC.Dialog dialog = new TLRPC.TL_dialog(); - dialog.id = DialogObject.makeSecretDialogId(chat.id); + dialog.id = DialogObject.makeEncryptedDialogId(chat.id); dialog.unread_count = 0; dialog.top_message = 0; dialog.last_message_date = getConnectionsManager().getCurrentTime(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SegmentTree.java b/TMessagesProj/src/main/java/org/telegram/messenger/SegmentTree.java index e0c30333f..cc78ff746 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SegmentTree.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SegmentTree.java @@ -4,7 +4,6 @@ public class SegmentTree { private Node[] heap; private int[] array; - private int size; public SegmentTree(int[] array) { this.array = array; @@ -12,12 +11,11 @@ public class SegmentTree { return; } //The max size of this array is about 2 * 2 ^ log2(n) + 1 - size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1))); + int size = (int) (2 * Math.pow(2.0, Math.floor((Math.log(array.length) / Math.log(2.0)) + 1))); heap = new Node[size]; build(1, 0, array.length); } - private void build(int v, int from, int size) { heap[v] = new Node(); heap[v].from = from; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java index 5ea5e7770..b004f806c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java @@ -29,7 +29,6 @@ import android.os.SystemClock; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Base64; -import android.util.LongSparseArray; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; @@ -40,6 +39,7 @@ import android.widget.TextView; import android.widget.Toast; import androidx.annotation.UiThread; +import androidx.collection.LongSparseArray; import androidx.core.view.inputmethod.InputContentInfoCompat; import org.json.JSONObject; @@ -1018,7 +1018,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe String finalPath = (String) args[1]; long availableSize = (Long) args[2]; long finalSize = (Long) args[3]; - boolean isEncrypted = ((int) messageObject.getDialogId()) == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(messageObject.getDialogId()); getFileLoader().checkUploadNewDataAvailable(finalPath, isEncrypted, availableSize, finalSize); if (finalSize != 0) { stopVideoService(messageObject.messageOwner.attachPath); @@ -1249,17 +1249,15 @@ public class SendMessagesHelper extends BaseController implements NotificationCe ArrayList checkReadyToSendGroups = new ArrayList<>(); ArrayList messageIds = new ArrayList<>(); boolean enc = false; - int channelId = 0; boolean scheduled = false; - long scheduledDialogId = 0; + long dialogId = 0; for (int c = 0; c < objects.size(); c++) { MessageObject object = objects.get(c); if (object.scheduled) { scheduled = true; - scheduledDialogId = object.getDialogId(); } + dialogId = object.getDialogId(); messageIds.add(object.getId()); - channelId = object.messageOwner.peer_id.channel_id; TLRPC.Message sendingMessage = removeFromSendingMessages(object.getId(), object.scheduled); if (sendingMessage != null) { getConnectionsManager().cancelRequest(sendingMessage.reqId, true); @@ -1351,7 +1349,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe if (objects.size() == 1 && objects.get(0).isEditing() && objects.get(0).previousMedia != null) { revertEditingMessageObject(objects.get(0)); } else { - getMessagesController().deleteMessages(messageIds, null, null, scheduledDialogId, channelId, false, scheduled); + getMessagesController().deleteMessages(messageIds, null, null, dialogId, false, scheduled); } } @@ -1363,7 +1361,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe return false; } if (messageObject.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction) { - int enc_id = (int) (messageObject.getDialogId() >> 32); + int enc_id = DialogObject.getEncryptedChatId(messageObject.getDialogId()); TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(enc_id); if (encryptedChat == null) { getMessagesStorage().markMessageAsSendError(messageObject.messageOwner, messageObject.scheduled); @@ -1404,7 +1402,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } return true; } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionScreenshotTaken) { - TLRPC.User user = getMessagesController().getUser((int) messageObject.getDialogId()); + TLRPC.User user = getMessagesController().getUser(messageObject.getDialogId()); sendScreenshotMessage(user, messageObject.getReplyMsgId(), messageObject.messageOwner); } if (unsent) { @@ -1428,7 +1426,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice)) { HashMap params = null; - if ((int) did == 0 && messageObject.messageOwner.peer_id != null && (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo || messageObject.messageOwner.media.document instanceof TLRPC.TL_document)) { + if (DialogObject.isEncryptedDialog(did) && messageObject.messageOwner.peer_id != null && (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo || messageObject.messageOwner.media.document instanceof TLRPC.TL_document)) { params = new HashMap<>(); params.put("parentObject", "sent_" + messageObject.messageOwner.peer_id.channel_id + "_" + messageObject.getId()); } @@ -1445,7 +1443,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe user.last_name = messageObject.messageOwner.media.last_name; user.id = messageObject.messageOwner.media.user_id; sendMessage(user, did, messageObject.replyMessageObject, null, null, null, true, 0); - } else if ((int) did != 0) { + } else if (!DialogObject.isEncryptedDialog(did)) { ArrayList arrayList = new ArrayList<>(); arrayList.add(messageObject); sendMessage(arrayList, did, true, false, true, 0); @@ -1472,7 +1470,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe entities = null; } sendMessage(messageObject.messageOwner.message, did, messageObject.replyMessageObject, null, webPage, true, entities, null, null, true, 0, null); - } else if ((int) did != 0) { + } else if (DialogObject.isEncryptedDialog(did)) { ArrayList arrayList = new ArrayList<>(); arrayList.add(messageObject); sendMessage(arrayList, did, true, false, true, 0); @@ -1532,9 +1530,9 @@ public class SendMessagesHelper extends BaseController implements NotificationCe if (document == null) { return; } - if ((int) peer == 0) { - int high_id = (int) (peer >> 32); - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(peer)) { + int encryptedId = DialogObject.getEncryptedChatId(peer); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedId); if (encryptedChat == null) { return; } @@ -1637,28 +1635,27 @@ public class SendMessagesHelper extends BaseController implements NotificationCe if (messages == null || messages.isEmpty()) { return 0; } - int lower_id = (int) peer; int sendResult = 0; - int myId = getUserConfig().getClientUserId(); + long myId = getUserConfig().getClientUserId(); boolean isChannel = false; - if (lower_id != 0) { - final TLRPC.Peer peer_id = getMessagesController().getPeer((int) peer); + if (!DialogObject.isEncryptedDialog(peer)) { + final TLRPC.Peer peer_id = getMessagesController().getPeer(peer); boolean isSignature = false; boolean canSendStickers = true; boolean canSendMedia = true; boolean canSendPolls = true; boolean canSendPreview = true; String rank = null; - int linkedToGroup = 0; + long linkedToGroup = 0; TLRPC.Chat chat; - if (lower_id > 0) { - TLRPC.User sendToUser = getMessagesController().getUser(lower_id); + if (DialogObject.isUserDialog(peer)) { + TLRPC.User sendToUser = getMessagesController().getUser(peer); if (sendToUser == null) { return 0; } chat = null; } else { - chat = getMessagesController().getChat(-lower_id); + chat = getMessagesController().getChat(-peer); if (ChatObject.isChannel(chat)) { isSignature = chat.signatures; isChannel = !chat.megagroup; @@ -1685,7 +1682,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe ArrayList randomIds = new ArrayList<>(); ArrayList ids = new ArrayList<>(); LongSparseArray messagesByRandomIds = new LongSparseArray<>(); - TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(lower_id); + TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(peer); long lastDialogId = 0; final boolean toMyself = peer == myId; long lastGroupedId; @@ -1744,7 +1741,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsg.fwd_from.date = msgObj.messageOwner.fwd_from.date; newMsg.flags = TLRPC.MESSAGE_FLAG_FWD; } else if (!forwardFromSaved) { //if (!toMyself || !msgObj.isOutOwner()) - int fromId = msgObj.getFromChatId(); + long fromId = msgObj.getFromChatId(); newMsg.fwd_from = new TLRPC.TL_messageFwdHeader(); newMsg.fwd_from.channel_post = msgObj.getId(); newMsg.fwd_from.flags |= 4; @@ -1777,14 +1774,13 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsg.fwd_from.saved_from_msg_id = msgObj.getId(); newMsg.fwd_from.saved_from_peer = msgObj.messageOwner.peer_id; if (newMsg.fwd_from.saved_from_peer.user_id == myId) { - newMsg.fwd_from.saved_from_peer.user_id = (int) msgObj.getDialogId(); + newMsg.fwd_from.saved_from_peer.user_id = msgObj.getDialogId(); } } - } else { - newMsg.params = new HashMap<>(); - newMsg.params.put("fwd_id", "" + msgObj.getId()); - newMsg.params.put("fwd_peer", "" + msgObj.getDialogId()); } + newMsg.params = new HashMap<>(); + newMsg.params.put("fwd_id", "" + msgObj.getId()); + newMsg.params.put("fwd_peer", "" + msgObj.getDialogId()); if (!msgObj.messageOwner.restriction_reason.isEmpty()) { newMsg.restriction_reason = msgObj.messageOwner.restriction_reason; newMsg.flags |= 4194304; @@ -1926,9 +1922,6 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsg.media_unread = true; } } - if (msgObj.messageOwner.peer_id instanceof TLRPC.TL_peerChannel) { - newMsg.ttl = -msgObj.messageOwner.peer_id.channel_id; - } MessageObject newMsgObj = new MessageObject(currentAccount, newMsg, true, true); newMsgObj.scheduled = scheduleDate != 0; newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; @@ -2059,7 +2052,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe AndroidUtilities.runOnUIThread(() -> { ArrayList messageIds = new ArrayList<>(); messageIds.add(oldId); - getMessagesController().deleteMessages(messageIds, null, null, newMsgObj1.dialog_id, newMsgObj1.peer_id.channel_id, false, true); + getMessagesController().deleteMessages(messageIds, null, null, newMsgObj1.dialog_id, false, true); getMessagesStorage().getStorageQueue().postRunnable(() -> { getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false); AndroidUtilities.runOnUIThread(() -> { @@ -2074,7 +2067,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe }); } else { getMessagesStorage().getStorageQueue().postRunnable(() -> { - getMessagesStorage().updateMessageStateAndId(newMsgObj1.random_id, (long) oldId, newMsgObj1.id, 0, false, peer_id.channel_id, scheduleDate != 0 ? 1 : 0); + getMessagesStorage().updateMessageStateAndId(newMsgObj1.random_id, MessageObject.getPeerId(peer_id), oldId, newMsgObj1.id, 0, false, scheduleDate != 0 ? 1 : 0); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduleDate != 0); AndroidUtilities.runOnUIThread(() -> { newMsgObj1.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; @@ -2156,9 +2149,9 @@ public class SendMessagesHelper extends BaseController implements NotificationCe DelayedMessage delayedMessage = null; long peer = messageObject.getDialogId(); boolean supportsSendingNewEntities = true; - if ((int) peer == 0) { - int high_id = (int) (peer >> 32); - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(peer)) { + int encryptedId = DialogObject.getEncryptedChatId(peer); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedId); if (encryptedChat == null || AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) < 101) { supportsSendingNewEntities = false; } @@ -2447,7 +2440,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe TLRPC.TL_messages_editMessage request = new TLRPC.TL_messages_editMessage(); request.id = messageObject.getId(); - request.peer = getMessagesController().getInputPeer((int) peer); + request.peer = getMessagesController().getInputPeer(peer); if (inputMedia != null) { request.flags |= 16384; request.media = inputMedia; @@ -2522,7 +2515,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } final TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); if (message != null) { req.message = message; req.flags |= 2048; @@ -2574,24 +2567,23 @@ public class SendMessagesHelper extends BaseController implements NotificationCe return waitingForLocation.containsKey(key); } - public void sendNotificationCallback(final long dialogId, final int msgId, final byte[] data) { + public void sendNotificationCallback(long dialogId, int msgId, byte[] data) { AndroidUtilities.runOnUIThread(() -> { - int lowerId = (int) dialogId; final String key = dialogId + "_" + msgId + "_" + Utilities.bytesToHex(data) + "_" + 0; waitingForCallback.put(key, true); - if (lowerId > 0) { - TLRPC.User user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = getMessagesController().getUser(dialogId); if (user == null) { - user = getMessagesStorage().getUserSync(lowerId); + user = getMessagesStorage().getUserSync(dialogId); if (user != null) { getMessagesController().putUser(user, true); } } } else { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (chat == null) { - chat = getMessagesStorage().getChatSync(-lowerId); + chat = getMessagesStorage().getChatSync(-dialogId); if (chat != null) { getMessagesController().putChat(chat, true); } @@ -2599,7 +2591,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } TLRPC.TL_messages_getBotCallbackAnswer req = new TLRPC.TL_messages_getBotCallbackAnswer(); - req.peer = getMessagesController().getInputPeer(lowerId); + req.peer = getMessagesController().getInputPeer(dialogId); req.msg_id = msgId; req.game = false; if (data != null) { @@ -2629,7 +2621,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } TLRPC.TL_messages_sendVote req = new TLRPC.TL_messages_sendVote(); req.msg_id = messageObject.getId(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); byte[] options; if (answers != null) { options = new byte[answers.size()]; @@ -2661,12 +2653,12 @@ public class SendMessagesHelper extends BaseController implements NotificationCe return voteSendTime.get(pollId, 0L); } - public void sendReaction(final MessageObject messageObject, CharSequence reaction, final ChatActivity parentFragment) { + public void sendReaction(MessageObject messageObject, CharSequence reaction, ChatActivity parentFragment) { if (messageObject == null || parentFragment == null) { return; } TLRPC.TL_messages_sendReaction req = new TLRPC.TL_messages_sendReaction(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); req.msg_id = messageObject.getId(); if (reaction != null) { req.reaction = reaction.toString(); @@ -2771,7 +2763,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe getMessagesStorage().saveBotCache(key, res); } if (res.message != null) { - int uid = messageObject.getFromChatId(); + long uid = messageObject.getFromChatId(); if (messageObject.messageOwner.via_bot_id != 0) { uid = messageObject.messageOwner.via_bot_id; } @@ -2806,7 +2798,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe if (parentFragment.getParentActivity() == null) { return; } - int uid = messageObject.getFromChatId(); + long uid = messageObject.getFromChatId(); if (messageObject.messageOwner.via_bot_id != 0) { uid = messageObject.messageOwner.via_bot_id; } @@ -2940,7 +2932,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } else { if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) { TLRPC.TL_messages_requestUrlAuth req = new TLRPC.TL_messages_requestUrlAuth(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); req.msg_id = messageObject.getId(); req.button_id = button.button_id; req.flags |= 2; @@ -2974,7 +2966,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } } else { TLRPC.TL_messages_getBotCallbackAnswer req = new TLRPC.TL_messages_getBotCallbackAnswer(); - req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); + req.peer = getMessagesController().getInputPeer(messageObject.getDialogId()); req.msg_id = messageObject.getId(); req.game = button instanceof TLRPC.TL_keyboardButtonGame; if (button.requires_password) { @@ -3106,18 +3098,16 @@ public class SendMessagesHelper extends BaseController implements NotificationCe MessageObject newMsgObj = null; DelayedMessage delayedMessage = null; int type = -1; - int lower_id = (int) peer; - int high_id = (int) (peer >> 32); boolean isChannel = false; boolean forceNoSoundVideo = false; boolean anonymously = false; String rank = null; - int linkedToGroup = 0; + long linkedToGroup = 0; TLRPC.EncryptedChat encryptedChat = null; - TLRPC.InputPeer sendToPeer = lower_id != 0 ? getMessagesController().getInputPeer(lower_id) : null; - int myId = getUserConfig().getClientUserId(); - if (lower_id == 0) { - encryptedChat = getMessagesController().getEncryptedChat(high_id); + TLRPC.InputPeer sendToPeer = !DialogObject.isEncryptedDialog(peer) ? getMessagesController().getInputPeer(peer) : null; + long myId = getUserConfig().getClientUserId(); + if (DialogObject.isEncryptedDialog(peer)) { + encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(peer)); if (encryptedChat == null) { if (retryMessageObject != null) { getMessagesStorage().markMessageAsSendError(retryMessageObject.messageOwner, retryMessageObject.scheduled); @@ -3211,8 +3201,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } } else { boolean canSendStickers = true; - if (lower_id < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); + if (DialogObject.isChatDialog(peer)) { + TLRPC.Chat chat = getMessagesController().getChat(-peer); canSendStickers = ChatObject.canSendStickers(chat); } if (message != null) { @@ -3344,7 +3334,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } else { newMsg = new TLRPC.TL_message(); } - if (lower_id < 0) { + if (DialogObject.isChatDialog(peer)) { if (!canSendStickers) { for (int a = 0, N = document.attributes.size(); a < N; a++) { if (document.attributes.get(a) instanceof TLRPC.TL_documentAttributeAnimated) { @@ -3437,7 +3427,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsg.from_id = new TLRPC.TL_peerChannel(); newMsg.from_id.channel_id = sendToPeer.channel_id; } else if (anonymously) { - newMsg.from_id = getMessagesController().getPeer(lower_id); + newMsg.from_id = getMessagesController().getPeer(peer); if (rank != null) { newMsg.post_author = rank; newMsg.flags |= 65536; @@ -3516,10 +3506,10 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsg.flags |= TLRPC.MESSAGE_FLAG_HAS_MARKUP; newMsg.reply_markup = replyMarkup; } - if (lower_id != 0) { - newMsg.peer_id = getMessagesController().getPeer(lower_id); - if (lower_id > 0) { - TLRPC.User sendToUser = getMessagesController().getUser(lower_id); + if (!DialogObject.isEncryptedDialog(peer)) { + newMsg.peer_id = getMessagesController().getPeer(peer); + if (DialogObject.isUserDialog(peer)) { + TLRPC.User sendToUser = getMessagesController().getUser(peer); if (sendToUser == null) { processSentMessage(newMsg.id); return; @@ -3568,7 +3558,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } } } - if (high_id != 1 && (MessageObject.isVoiceMessage(newMsg) || MessageObject.isRoundVideoMessage(newMsg))) { + if (MessageObject.isVoiceMessage(newMsg) || MessageObject.isRoundVideoMessage(newMsg)) { newMsg.media_unread = true; } @@ -4346,7 +4336,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe reqSend.drop_author = true; long peerId = Utilities.parseLong(params.get("fwd_peer")); if (peerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat((int) -peerId); + TLRPC.Chat chat = getMessagesController().getChat(-peerId); if (ChatObject.isChannel(chat)) { reqSend.from_peer = new TLRPC.TL_inputPeerChannel(); reqSend.from_peer.channel_id = chat.id; @@ -4359,16 +4349,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } reqSend.id.add(fwdId); } else { - if (retryMessageObject.messageOwner.ttl != 0) { - TLRPC.Chat chat = getMessagesController().getChat(-retryMessageObject.messageOwner.ttl); - reqSend.from_peer = new TLRPC.TL_inputPeerChannel(); - reqSend.from_peer.channel_id = -retryMessageObject.messageOwner.ttl; - if (chat != null) { - reqSend.from_peer.access_hash = chat.access_hash; - } - } else { - reqSend.from_peer = new TLRPC.TL_inputPeerEmpty(); - } + reqSend.from_peer = new TLRPC.TL_inputPeerEmpty(); } reqSend.silent = newMsg.silent; if (scheduleDate != 0) { @@ -5059,7 +5040,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe LongSparseArray newIds = new LongSparseArray<>(); final TLRPC.Updates updates = (TLRPC.Updates) response; ArrayList updatesArr = ((TLRPC.Updates) response).updates; - SparseArray> channelReplies = null; + LongSparseArray> channelReplies = null; for (int a = 0; a < updatesArr.size(); a++) { TLRPC.Update update = updatesArr.get(a); if (update instanceof TLRPC.TL_updateMessageID) { @@ -5075,20 +5056,20 @@ public class SendMessagesHelper extends BaseController implements NotificationCe a--; } else if (update instanceof TLRPC.TL_updateNewChannelMessage) { final TLRPC.TL_updateNewChannelMessage newMessage = (TLRPC.TL_updateNewChannelMessage) update; - int channelId = MessagesController.getUpdateChannelId(newMessage); + long channelId = MessagesController.getUpdateChannelId(newMessage); TLRPC.Chat chat = getMessagesController().getChat(channelId); if ((chat == null || chat.megagroup) && newMessage.message.reply_to != null && (newMessage.message.reply_to.reply_to_top_id != 0 || newMessage.message.reply_to.reply_to_msg_id != 0)) { if (channelReplies == null) { - channelReplies = new SparseArray<>(); + channelReplies = new LongSparseArray<>(); } - int did = (int) MessageObject.getDialogId(newMessage.message); - SparseArray replies = channelReplies.get(did); + long did = MessageObject.getDialogId(newMessage.message); + SparseArray replies = channelReplies.get(did); if (replies == null) { replies = new SparseArray<>(); channelReplies.put(did, replies); } int id = newMessage.message.reply_to.reply_to_top_id != 0 ? newMessage.message.reply_to.reply_to_top_id : newMessage.message.reply_to.reply_to_msg_id; - TLRPC.TL_messageReplies messageReplies = replies.get(id); + TLRPC.MessageReplies messageReplies = replies.get(id); if (messageReplies == null) { messageReplies = new TLRPC.TL_messageReplies(); replies.put(id, messageReplies); @@ -5111,7 +5092,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } } if (channelReplies != null) { - getMessagesStorage().putChannelViews(null, null, channelReplies, true, true); + getMessagesStorage().putChannelViews(null, null, channelReplies, true); getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, null, null, channelReplies, true); } @@ -5162,7 +5143,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled); getMessagesStorage().getStorageQueue().postRunnable(() -> { - getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, (long) oldId, newMsgObj.id, 0, false, newMsgObj.peer_id.channel_id, scheduled ? 1 : 0); + getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, MessageObject.getPeerId(newMsgObj.peer_id), oldId, newMsgObj.id, 0, false, scheduled ? 1 : 0); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduled); AndroidUtilities.runOnUIThread(() -> { getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); @@ -5363,7 +5344,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe final TLRPC.Updates updates = (TLRPC.Updates) response; ArrayList updatesArr = ((TLRPC.Updates) response).updates; TLRPC.Message message = null; - SparseArray> channelReplies = null; + LongSparseArray> channelReplies = null; for (int a = 0; a < updatesArr.size(); a++) { TLRPC.Update update = updatesArr.get(a); if (update instanceof TLRPC.TL_updateNewMessage) { @@ -5374,20 +5355,20 @@ public class SendMessagesHelper extends BaseController implements NotificationCe break; } else if (update instanceof TLRPC.TL_updateNewChannelMessage) { final TLRPC.TL_updateNewChannelMessage newMessage = (TLRPC.TL_updateNewChannelMessage) update; - int channelId = MessagesController.getUpdateChannelId(newMessage); + long channelId = MessagesController.getUpdateChannelId(newMessage); TLRPC.Chat chat = getMessagesController().getChat(channelId); if ((chat == null || chat.megagroup) && newMessage.message.reply_to != null && (newMessage.message.reply_to.reply_to_top_id != 0 || newMessage.message.reply_to.reply_to_msg_id != 0)) { if (channelReplies == null) { - channelReplies = new SparseArray<>(); + channelReplies = new LongSparseArray<>(); } - int did = (int) MessageObject.getDialogId(newMessage.message); - SparseArray replies = channelReplies.get(did); + long did = MessageObject.getDialogId(newMessage.message); + SparseArray replies = channelReplies.get(did); if (replies == null) { replies = new SparseArray<>(); channelReplies.put(did, replies); } int id = newMessage.message.reply_to.reply_to_top_id != 0 ? newMessage.message.reply_to.reply_to_top_id : newMessage.message.reply_to.reply_to_msg_id; - TLRPC.TL_messageReplies messageReplies = replies.get(id); + TLRPC.MessageReplies messageReplies = replies.get(id); if (messageReplies == null) { messageReplies = new TLRPC.TL_messageReplies(); replies.put(id, messageReplies); @@ -5410,7 +5391,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } } if (channelReplies != null) { - getMessagesStorage().putChannelViews(null, null, channelReplies, true, true); + getMessagesStorage().putChannelViews(null, null, channelReplies, true); getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, null, null, channelReplies, true); } if (message != null) { @@ -5455,7 +5436,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe if (scheduled && !currentSchedule) { ArrayList messageIds = new ArrayList<>(); messageIds.add(oldId); - getMessagesController().deleteMessages(messageIds, null, null, newMsgObj.dialog_id, newMsgObj.peer_id.channel_id, false, true); + getMessagesController().deleteMessages(messageIds, null, null, newMsgObj.dialog_id, false, true); getMessagesStorage().getStorageQueue().postRunnable(() -> { getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false); AndroidUtilities.runOnUIThread(() -> { @@ -5473,7 +5454,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } else { getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled); getMessagesStorage().getStorageQueue().postRunnable(() -> { - getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, (long) oldId, newMsgObj.id, 0, false, newMsgObj.peer_id.channel_id, scheduled ? 1 : 0); + getMessagesStorage().updateMessageStateAndId(newMsgObj.random_id, MessageObject.getPeerId(newMsgObj.peer_id), oldId, newMsgObj.id, 0, false, scheduled ? 1 : 0); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduled); AndroidUtilities.runOnUIThread(() -> { getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); @@ -5823,16 +5804,15 @@ public class SendMessagesHelper extends BaseController implements NotificationCe return importingHistoryMap.size() != 0; } - public void prepareImportHistory(long dialogId, Uri uri, ArrayList mediaUris, MessagesStorage.IntCallback onStartImport) { + public void prepareImportHistory(long dialogId, Uri uri, ArrayList mediaUris, MessagesStorage.LongCallback onStartImport) { if (importingHistoryMap.get(dialogId) != null) { onStartImport.run(0); return; } - int lowerId = (int) dialogId; - if (lowerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (chat != null && !chat.megagroup) { - getMessagesController().convertToMegaGroup(null, -lowerId, null, (chatId) -> { + getMessagesController().convertToMegaGroup(null, -dialogId, null, (chatId) -> { if (chatId != 0) { prepareImportHistory(-chatId, uri, mediaUris, onStartImport); } else { @@ -5847,7 +5827,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe ImportingHistory importingHistory = new ImportingHistory(); importingHistory.mediaPaths = uris; importingHistory.dialogId = dialogId; - importingHistory.peer = getMessagesController().getInputPeer((int) dialogId); + importingHistory.peer = getMessagesController().getInputPeer(dialogId); HashMap files = new HashMap<>(); for (int a = 0, N = uris.size(); a < N + 1; a++) { Uri mediaUri; @@ -5903,7 +5883,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe importingHistoryMap.put(dialogId, importingHistory); getFileLoader().uploadFile(importingHistory.historyPath, false, true, 0, ConnectionsManager.FileTypeFile, true); getNotificationCenter().postNotificationName(NotificationCenter.historyImportProgressChanged, dialogId); - onStartImport.run((int) dialogId); + onStartImport.run(dialogId); Intent intent = new Intent(ApplicationLoader.applicationContext, ImportingService.class); try { @@ -6036,7 +6016,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe return false; } - boolean isEncrypted = (int) dialogId == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); String name = f.getName(); String ext = ""; @@ -6302,7 +6282,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe String originalPath = messageObject.messageOwner.attachPath; final File f = new File(originalPath); - boolean isEncrypted = (int) dialogId == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); if (!isEncrypted && count > 1 && mediaCount % 10 == 0) { groupId = Utilities.random.nextLong(); mediaCount = 0; @@ -6327,8 +6307,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } if (isEncrypted) { - int high_id = (int) (dialogId >> 32); - TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(high_id); + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { return; } @@ -6391,7 +6371,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe int mediaCount = 0; Integer[] docType = new Integer[1]; - boolean isEncrypted = (int) dialogId == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); if (paths != null) { int count = paths.size(); @@ -6484,13 +6464,13 @@ public class SendMessagesHelper extends BaseController implements NotificationCe } if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto) { new Thread(() -> { - boolean isEncrypted = (int) dialogId == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); String finalPath = null; TLRPC.TL_document document = null; TLRPC.TL_photo photo = null; TLRPC.TL_game game = null; if ("game".equals(result.type)) { - if ((int) dialogId == 0) { + if (isEncrypted) { return; //doesn't work in secret chats for now } game = new TLRPC.TL_game(); @@ -6749,7 +6729,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe }).run(); } else if (result.send_message instanceof TLRPC.TL_botInlineMessageText) { TLRPC.WebPage webPage = null; - if ((int) dialogId == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { for (int a = 0; a < result.send_message.entities.size(); a++) { TLRPC.MessageEntity entity = result.send_message.entities.get(a); if (entity instanceof TLRPC.TL_messageEntityUrl) { @@ -6798,7 +6778,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe user.restriction_reason.add(reason); accountInstance.getSendMessagesHelper().sendMessage(user, dialogId, replyToMsg, replyToTopMsg, result.send_message.reply_markup, params, notify, scheduleDate); } else if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaInvoice) { - if (DialogObject.isSecretDialogId(dialogId)) { + if (DialogObject.isEncryptedDialog(dialogId)) { return; //doesn't work in secret chats for now } TLRPC.TL_botInlineMessageMediaInvoice invoice = (TLRPC.TL_botInlineMessageMediaInvoice) result.send_message; @@ -6988,7 +6968,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe long beginTime = System.currentTimeMillis(); HashMap workers; int count = media.size(); - boolean isEncrypted = (int) dialogId == 0; + + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); if (!forceDocument && groupMediaFinal) { workers = new HashMap<>(); for (int a = 0; a < count; a++) { @@ -7862,12 +7843,14 @@ public class SendMessagesHelper extends BaseController implements NotificationCe compressionsCount = 1; } - int selectedCompression = Math.round(DownloadController.getInstance(UserConfig.selectedAccount).getMaxVideoBitrate() / (100f / compressionsCount)) - 1; + int selectedCompression = Math.round(DownloadController.getInstance(UserConfig.selectedAccount).getMaxVideoBitrate() / (100f / compressionsCount)); - if (selectedCompression >= compressionsCount) { - selectedCompression = compressionsCount - 1; + if (selectedCompression > compressionsCount) { + selectedCompression = compressionsCount; } - if (selectedCompression != compressionsCount - 1) { + boolean needCompress = false; + if (selectedCompression != compressionsCount - 1 || Math.max(videoEditedInfo.originalWidth, videoEditedInfo.originalHeight) > 1280) { + needCompress = true; switch (selectedCompression) { case 1: maxSize = 432.0f; @@ -7892,7 +7875,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe videoEditedInfo.resultHeight, videoEditedInfo.resultWidth ); - if (selectedCompression == compressionsCount - 1) { + if (!needCompress) { videoEditedInfo.resultWidth = videoEditedInfo.originalWidth; videoEditedInfo.resultHeight = videoEditedInfo.originalHeight; videoEditedInfo.bitrate = bitrate; @@ -7917,7 +7900,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe new Thread(() -> { final VideoEditedInfo videoEditedInfo = info != null ? info : createCompressionSettings(videoPath); - boolean isEncrypted = (int) dialogId == 0; + boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId); boolean isRound = videoEditedInfo != null && videoEditedInfo.roundVideo; Bitmap thumb = null; @@ -7982,8 +7965,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe accountInstance.getUserConfig().saveConfig(false); TLRPC.TL_documentAttributeVideo attributeVideo; if (isEncrypted) { - int high_id = (int) (dialogId >> 32); - TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(high_id); + int encryptedChatId = DialogObject.getEncryptedChatId(dialogId); + TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { return; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SharedConfig.java b/TMessagesProj/src/main/java/org/telegram/messenger/SharedConfig.java index 48ec3daf9..2e6d70657 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SharedConfig.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SharedConfig.java @@ -23,8 +23,8 @@ import android.util.SparseArray; import org.json.JSONObject; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.SerializedData; +import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.tgnet.TLRPC; -import org.telegram.ui.SwipeGestureSettingsView; import java.io.File; import java.io.RandomAccessFile; @@ -116,6 +116,9 @@ public class SharedConfig { public static int fontSize = 16; public static int bubbleRadius = 10; public static int ivFontSize = 16; + public static int messageSeenHintCount; + public static int emojiInteractionsHintCount; + public static int dayNightThemeSwitchHintCount; public static TLRPC.TL_help_appUpdate pendingAppUpdate; public static int pendingAppUpdateBuildVersion; @@ -364,6 +367,9 @@ public class SharedConfig { disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false); noiseSupression = preferences.getBoolean("noiseSupression", false); chatSwipeAction = preferences.getInt("ChatSwipeAction", -1); + messageSeenHintCount = preferences.getInt("messageSeenCount", 3); + emojiInteractionsHintCount = preferences.getInt("emojiInteractionsHintCount", 3); + dayNightThemeSwitchHintCount = preferences.getInt("dayNightThemeSwitchHintCount", 3); preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true); @@ -522,6 +528,9 @@ public class SharedConfig { scheduledOrNoSoundHintShows = 0; lockRecordAudioVideoHint = 0; forwardingOptionsHintShown = false; + messageSeenHintCount = 3; + emojiInteractionsHintCount = 3; + dayNightThemeSwitchHintCount = 3; saveConfig(); } @@ -1033,8 +1042,6 @@ public class SharedConfig { public static void checkSaveToGalleryFiles() { Utilities.globalQueue.postRunnable(() -> { try { - - File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram"); File imagePath = new File(telegramPath, "Telegram Images"); imagePath.mkdir(); @@ -1081,6 +1088,25 @@ public class SharedConfig { preferences.edit().putInt("ChatSwipeAction", chatSwipeAction).apply(); } + public static void updateMessageSeenHintCount(int count) { + messageSeenHintCount = count; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + preferences.edit().putInt("messageSeenCount", messageSeenHintCount).apply(); + } + + public static void updateEmojiInteractionsHintCount(int count) { + emojiInteractionsHintCount = count; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + preferences.edit().putInt("emojiInteractionsHintCount", emojiInteractionsHintCount).apply(); + } + + + public static void updateDayNightThemeSwitchHintCount(int count) { + dayNightThemeSwitchHintCount = count; + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); + preferences.edit().putInt("dayNightThemeSwitchHintCount", dayNightThemeSwitchHintCount).apply(); + } + public final static int PERFORMANCE_CLASS_LOW = 0; public final static int PERFORMANCE_CLASS_AVERAGE = 1; public final static int PERFORMANCE_CLASS_HIGH = 2; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SmsReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/SmsReceiver.java index b70adb834..610bce9b6 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SmsReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SmsReceiver.java @@ -47,7 +47,7 @@ public class SmsReceiver extends BroadcastReceiver { if (matcher.find()) { String code = matcher.group(0).replace("-", ""); if (code.length() >= 3) { - if (preferences != null && hash != null) { + if (hash != null) { preferences.edit().putString("sms_hash_code", hash + "|" + code).commit(); } AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReceiveSmsCode, code)); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SvgHelper.java b/TMessagesProj/src/main/java/org/telegram/messenger/SvgHelper.java index a09986ad8..a01bb348e 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SvgHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SvgHelper.java @@ -106,7 +106,6 @@ public class SvgHelper { protected int height; private static int[] parentPosition = new int[2]; - private Shader backgroundGradient; private Bitmap backgroundBitmap; private Canvas backgroundCanvas; private LinearGradient placeholderGradient; @@ -263,6 +262,7 @@ public class SvgHelper { color = Color.argb((int) (Color.alpha(color) / 2 * colorAlpha), Color.red(color), Color.green(color), Color.blue(color)); float centerX = (1.0f - w) / 2; placeholderGradient = new LinearGradient(0, 0, gradientWidth, 0, new int[]{0x00000000, 0x00000000, color, 0x00000000, 0x00000000}, new float[]{0.0f, centerX - w / 2.0f, centerX, centerX + w / 2.0f, 1.0f}, Shader.TileMode.REPEAT); + Shader backgroundGradient; if (Build.VERSION.SDK_INT >= 28) { backgroundGradient = new LinearGradient(0, 0, gradientWidth, 0, new int[]{color, color}, null, Shader.TileMode.REPEAT); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java index cce6fa3b2..f75d54520 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/UserConfig.java @@ -31,7 +31,7 @@ public class UserConfig extends BaseController { public int lastSendMessageId = -210000; public int lastBroadcastId = -1; public int contactsSavedCount; - public int clientUserId; + public long clientUserId; public int lastContactsSyncTime; public int lastHintsSyncTime; public boolean draftsLoaded; @@ -43,9 +43,9 @@ public class UserConfig extends BaseController { public boolean hasValidDialogLoadIds; public int migrateOffsetId = -1; public int migrateOffsetDate = -1; - public int migrateOffsetUserId = -1; - public int migrateOffsetChatId = -1; - public int migrateOffsetChannelId = -1; + public long migrateOffsetUserId = -1; + public long migrateOffsetChatId = -1; + public long migrateOffsetChannelId = -1; public long migrateOffsetAccess = -1; public boolean filtersLoaded; @@ -136,9 +136,9 @@ public class UserConfig extends BaseController { editor.putInt("6migrateOffsetId", migrateOffsetId); if (migrateOffsetId != -1) { editor.putInt("6migrateOffsetDate", migrateOffsetDate); - editor.putInt("6migrateOffsetUserId", migrateOffsetUserId); - editor.putInt("6migrateOffsetChatId", migrateOffsetChatId); - editor.putInt("6migrateOffsetChannelId", migrateOffsetChannelId); + editor.putLong("6migrateOffsetUserId", migrateOffsetUserId); + editor.putLong("6migrateOffsetChatId", migrateOffsetChatId); + editor.putLong("6migrateOffsetChannelId", migrateOffsetChannelId); editor.putLong("6migrateOffsetAccess", migrateOffsetAccess); } @@ -197,7 +197,7 @@ public class UserConfig extends BaseController { } } - public int getClientUserId() { + public long getClientUserId() { synchronized (sync) { return currentUser != null ? currentUser.id : 0; } @@ -271,9 +271,9 @@ public class UserConfig extends BaseController { migrateOffsetId = preferences.getInt("6migrateOffsetId", 0); if (migrateOffsetId != -1) { migrateOffsetDate = preferences.getInt("6migrateOffsetDate", 0); - migrateOffsetUserId = preferences.getInt("6migrateOffsetUserId", 0); - migrateOffsetChatId = preferences.getInt("6migrateOffsetChatId", 0); - migrateOffsetChannelId = preferences.getInt("6migrateOffsetChannelId", 0); + migrateOffsetUserId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetUserId", 0); + migrateOffsetChatId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChatId", 0); + migrateOffsetChannelId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChannelId", 0); migrateOffsetAccess = preferences.getLong("6migrateOffsetAccess", 0); } @@ -400,8 +400,7 @@ public class UserConfig extends BaseController { public static final int i_dialogsLoadOffsetUserId = 2; public static final int i_dialogsLoadOffsetChatId = 3; public static final int i_dialogsLoadOffsetChannelId = 4; - public static final int i_dialogsLoadOffsetAccess_1 = 5; - public static final int i_dialogsLoadOffsetAccess_2 = 6; + public static final int i_dialogsLoadOffsetAccess = 5; public int getTotalDialogsCount(int folderId) { return getPreferences().getInt("2totalDialogsLoadCount" + (folderId == 0 ? "" : folderId), 0); @@ -411,24 +410,24 @@ public class UserConfig extends BaseController { getPreferences().edit().putInt("2totalDialogsLoadCount" + (folderId == 0 ? "" : folderId), totalDialogsLoadCount).commit(); } - public int[] getDialogLoadOffsets(int folderId) { + public long[] getDialogLoadOffsets(int folderId) { SharedPreferences preferences = getPreferences(); int dialogsLoadOffsetId = preferences.getInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); int dialogsLoadOffsetDate = preferences.getInt("2dialogsLoadOffsetDate" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); - int dialogsLoadOffsetUserId = preferences.getInt("2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); - int dialogsLoadOffsetChatId = preferences.getInt("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); - int dialogsLoadOffsetChannelId = preferences.getInt("2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); + long dialogsLoadOffsetUserId = AndroidUtilities.getPrefIntOrLong(preferences, "2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); + long dialogsLoadOffsetChatId = AndroidUtilities.getPrefIntOrLong(preferences, "2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); + long dialogsLoadOffsetChannelId = AndroidUtilities.getPrefIntOrLong(preferences, "2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); long dialogsLoadOffsetAccess = preferences.getLong("2dialogsLoadOffsetAccess" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); - return new int[]{dialogsLoadOffsetId, dialogsLoadOffsetDate, dialogsLoadOffsetUserId, dialogsLoadOffsetChatId, dialogsLoadOffsetChannelId, (int) dialogsLoadOffsetAccess, (int) (dialogsLoadOffsetAccess >> 32)}; + return new long[]{dialogsLoadOffsetId, dialogsLoadOffsetDate, dialogsLoadOffsetUserId, dialogsLoadOffsetChatId, dialogsLoadOffsetChannelId, dialogsLoadOffsetAccess}; } - public void setDialogsLoadOffset(int folderId, int dialogsLoadOffsetId, int dialogsLoadOffsetDate, int dialogsLoadOffsetUserId, int dialogsLoadOffsetChatId, int dialogsLoadOffsetChannelId, long dialogsLoadOffsetAccess) { + public void setDialogsLoadOffset(int folderId, int dialogsLoadOffsetId, int dialogsLoadOffsetDate, long dialogsLoadOffsetUserId, long dialogsLoadOffsetChatId, long dialogsLoadOffsetChannelId, long dialogsLoadOffsetAccess) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetId); editor.putInt("2dialogsLoadOffsetDate" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetDate); - editor.putInt("2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetUserId); - editor.putInt("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChatId); - editor.putInt("2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChannelId); + editor.putLong("2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetUserId); + editor.putLong("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChatId); + editor.putLong("2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChannelId); editor.putLong("2dialogsLoadOffsetAccess" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetAccess); editor.putBoolean("hasValidDialogLoadIds", true); editor.commit(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java b/TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java index baf650911..f0b59ae0e 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java @@ -374,7 +374,7 @@ public class VideoEditedInfo { } public boolean needConvert() { - return mediaEntities != null || paintPath != null || filterState != null || cropState != null || !roundVideo || roundVideo && (startTime > 0 || endTime != -1 && endTime != estimatedDuration); + return mediaEntities != null || paintPath != null || filterState != null || cropState != null || !roundVideo || startTime > 0 || endTime != -1 && endTime != estimatedDuration; } public boolean canAutoPlaySourceVideo() { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java b/TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java index 361e8e3fb..125b06f08 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/VideoEncodingService.java @@ -107,7 +107,7 @@ public class VideoEncodingService extends Service implements NotificationCenter. } } currentProgress = 0; - builder.setProgress(100, currentProgress, currentProgress == 0); + builder.setProgress(100, currentProgress, true); startForeground(4, builder.build()); NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); return Service.START_NOT_STICKY; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/WearDataLayerListenerService.java b/TMessagesProj/src/main/java/org/telegram/messenger/WearDataLayerListenerService.java deleted file mode 100644 index a53f92718..000000000 --- a/TMessagesProj/src/main/java/org/telegram/messenger/WearDataLayerListenerService.java +++ /dev/null @@ -1,313 +0,0 @@ -package org.telegram.messenger; - -import android.text.TextUtils; - -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.wearable.CapabilityClient; -import com.google.android.gms.wearable.CapabilityInfo; -import com.google.android.gms.wearable.Channel; -import com.google.android.gms.wearable.MessageClient; -import com.google.android.gms.wearable.MessageEvent; -import com.google.android.gms.wearable.Node; -import com.google.android.gms.wearable.Wearable; -import com.google.android.gms.wearable.WearableListenerService; - -import org.json.JSONObject; -import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.TLRPC; - -import java.io.BufferedOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.Set; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class WearDataLayerListenerService extends WearableListenerService { - - private int currentAccount = UserConfig.selectedAccount; - private static boolean watchConnected; - - @Override - public void onCreate() { - super.onCreate(); - if (BuildVars.LOGS_ENABLED) { - FileLog.d("WearableDataLayer service created"); - } - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (BuildVars.LOGS_ENABLED) { - FileLog.d("WearableDataLayer service destroyed"); - } - } - - @Override - public void onChannelOpened(final Channel ch) { - //new Thread(new Runnable(){ - // @Override - // public void run(){ - GoogleApiClient apiClient = new GoogleApiClient.Builder(WearDataLayerListenerService.this).addApi(Wearable.API).build(); - if (!apiClient.blockingConnect().isSuccess()) { - if (BuildVars.LOGS_ENABLED) { - FileLog.e("failed to connect google api client"); - } - return; - } - String path = ch.getPath(); - if (BuildVars.LOGS_ENABLED) { - FileLog.d("wear channel path: " + path); - } - try { - if ("/getCurrentUser".equals(path)) { - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(ch.getOutputStream(apiClient).await().getOutputStream())); - if (UserConfig.getInstance(currentAccount).isClientActivated()) { - final TLRPC.User user = UserConfig.getInstance(currentAccount).getCurrentUser(); - out.writeInt(user.id); - out.writeUTF(user.first_name); - out.writeUTF(user.last_name); - out.writeUTF(user.phone); - if (user.photo != null) { - final File photo = FileLoader.getPathToAttach(user.photo.photo_small, true); - final CyclicBarrier barrier = new CyclicBarrier(2); - if (!photo.exists()) { - final NotificationCenter.NotificationCenterDelegate listener = (id, account, args) -> { - if (id == NotificationCenter.fileLoaded) { - if (BuildVars.LOGS_ENABLED) { - FileLog.d("file loaded: " + args[0] + " " + args[0].getClass().getName()); - } - if (args[0].equals(photo.getName())) { - if (BuildVars.LOGS_ENABLED) { - FileLog.e("LOADED USER PHOTO"); - } - try { - barrier.await(10, TimeUnit.MILLISECONDS); - } catch (Exception ignore) { - } - } - } - }; - AndroidUtilities.runOnUIThread(() -> { - NotificationCenter.getInstance(currentAccount).addObserver(listener, NotificationCenter.fileLoaded); - FileLoader.getInstance(currentAccount).loadFile(ImageLocation.getForUserOrChat(user, ImageLocation.TYPE_SMALL), user, null, 1, 1); - }); - try { - barrier.await(10, TimeUnit.SECONDS); - } catch (Exception ignore) { - } - AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).removeObserver(listener, NotificationCenter.fileLoaded)); - } - if (photo.exists() && photo.length() <= 50 * 1024 * 1024) { - byte[] photoData = new byte[(int) photo.length()]; - FileInputStream photoIn = new FileInputStream(photo); - new DataInputStream(photoIn).readFully(photoData); - photoIn.close(); - out.writeInt(photoData.length); - out.write(photoData); - } else { - out.writeInt(0); - } - } else { - out.writeInt(0); - } - } else { - out.writeInt(0); - } - out.flush(); - out.close(); - } else if ("/waitForAuthCode".equals(path)) { - ConnectionsManager.getInstance(currentAccount).setAppPaused(false, false); - final String[] code = {null}; - final CyclicBarrier barrier = new CyclicBarrier(2); - final NotificationCenter.NotificationCenterDelegate listener = (id, account, args) -> { - if (id == NotificationCenter.didReceiveNewMessages) { - long did = (Long) args[0]; - if (did == 777000) { - ArrayList arr = (ArrayList) args[1]; - if (arr.size() > 0) { - MessageObject msg = arr.get(0); - if (!TextUtils.isEmpty(msg.messageText)) { - Matcher matcher = Pattern.compile("[0-9]+").matcher(msg.messageText); - if (matcher.find()) { - code[0] = matcher.group(); - try { - barrier.await(10, TimeUnit.MILLISECONDS); - } catch (Exception ignore) { - } - } - } - } - } - } - }; - AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).addObserver(listener, NotificationCenter.didReceiveNewMessages)); - try { - barrier.await(30, TimeUnit.SECONDS); - } catch (Exception ignore) { - } - AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).removeObserver(listener, NotificationCenter.didReceiveNewMessages)); - DataOutputStream out = new DataOutputStream(ch.getOutputStream(apiClient).await().getOutputStream()); - if (code[0] != null) { - out.writeUTF(code[0]); - } else { - out.writeUTF(""); - } - out.flush(); - out.close(); - ConnectionsManager.getInstance(currentAccount).setAppPaused(true, false); - } else if ("/getChatPhoto".equals(path)) { - try (DataInputStream in = new DataInputStream(ch.getInputStream(apiClient).await().getInputStream()); DataOutputStream out = new DataOutputStream(ch.getOutputStream(apiClient).await().getOutputStream())) { - String _req = in.readUTF(); - JSONObject req = new JSONObject(_req); - int chatID = req.getInt("chat_id"); - int accountID = req.getInt("account_id"); - int currentAccount = -1; - for (int i = 0; i < UserConfig.getActivatedAccountsCount(); i++) { - if (UserConfig.getInstance(i).getClientUserId() == accountID) { - currentAccount = i; - break; - } - } - if (currentAccount != -1) { - TLRPC.FileLocation location = null; - if (chatID > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(chatID); - if (user != null && user.photo != null) - location = user.photo.photo_small; - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-chatID); - if (chat != null && chat.photo != null) - location = chat.photo.photo_small; - } - if (location != null) { - File file = FileLoader.getPathToAttach(location, true); - if (file.exists() && file.length() < 102400) { - out.writeInt((int) file.length()); - FileInputStream fin = new FileInputStream(file); - byte[] buf = new byte[10240]; - int read; - while ((read = fin.read(buf)) > 0) { - out.write(buf, 0, read); - } - fin.close(); - } else { - out.writeInt(0); - } - } else { - out.writeInt(0); - } - } else { - out.writeInt(0); - } - out.flush(); - } catch (Exception ignore) { - } - } - } catch (Exception x) { - if (BuildVars.LOGS_ENABLED) { - FileLog.e("error processing wear request", x); - } - } - ch.close(apiClient).await(); - apiClient.disconnect(); - if (BuildVars.LOGS_ENABLED) { - FileLog.d("WearableDataLayer channel thread exiting"); - } - // } - //}).start(); - } - - @Override - public void onMessageReceived(final MessageEvent messageEvent) { - if ("/reply".equals(messageEvent.getPath())) { - AndroidUtilities.runOnUIThread(() -> { - try { - ApplicationLoader.postInitApplication(); - String data = new String(messageEvent.getData(), "UTF-8"); - JSONObject r = new JSONObject(data); - CharSequence text = r.getString("text"); - if (text == null || text.length() == 0) { - return; - } - long dialog_id = r.getLong("chat_id"); - int max_id = r.getInt("max_id"); - int currentAccount = -1; - int accountID = r.getInt("account_id"); - for (int i = 0; i < UserConfig.getActivatedAccountsCount(); i++) { - if (UserConfig.getInstance(i).getClientUserId() == accountID) { - currentAccount = i; - break; - } - } - if (dialog_id == 0 || max_id == 0 || currentAccount == -1) { - return; - } - SendMessagesHelper.getInstance(currentAccount).sendMessage(text.toString(), dialog_id, null, null, null, true, null, null, null, true, 0, null); - MessagesController.getInstance(currentAccount).markDialogAsRead(dialog_id, max_id, max_id, 0, false, 0, 0, true, 0); - } catch (Exception x) { - if (BuildVars.LOGS_ENABLED) - FileLog.e(x); - } - }); - } - } - - public static void sendMessageToWatch(final String path, final byte[] data, String capability) { - Wearable.getCapabilityClient(ApplicationLoader.applicationContext) - .getCapability(capability, CapabilityClient.FILTER_REACHABLE) - .addOnCompleteListener(task -> { - CapabilityInfo info = task.getResult(); - if (info != null) { - MessageClient mc = Wearable.getMessageClient(ApplicationLoader.applicationContext); - Set nodes = info.getNodes(); - for (Node node : nodes) { - mc.sendMessage(node.getId(), path, data); - } - } - }); - } - - @Override - public void onCapabilityChanged(CapabilityInfo capabilityInfo) { - if ("remote_notifications".equals(capabilityInfo.getName())) { - watchConnected = false; - for (Node node : capabilityInfo.getNodes()) { - if (node.isNearby()) - watchConnected = true; - } - } - } - - public static void updateWatchConnectionState() { - try { - Wearable.getCapabilityClient(ApplicationLoader.applicationContext) - .getCapability("remote_notifications", CapabilityClient.FILTER_REACHABLE) - .addOnCompleteListener(task -> { - watchConnected = false; - try { - CapabilityInfo capabilityInfo = task.getResult(); - if (capabilityInfo == null) - return; - for (Node node : capabilityInfo.getNodes()) { - if (node.isNearby()) - watchConnected = true; - } - } catch (Exception ignore) { - } - }); - } catch (Throwable ignore) { - - } - } - - public static boolean isWatchConnected() { - return watchConnected; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/WearReplyReceiver.java b/TMessagesProj/src/main/java/org/telegram/messenger/WearReplyReceiver.java index 70e7e522a..03a2af93a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/WearReplyReceiver.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/WearReplyReceiver.java @@ -31,41 +31,39 @@ public class WearReplyReceiver extends BroadcastReceiver { if (TextUtils.isEmpty(text)) { return; } - long dialog_id = intent.getLongExtra("dialog_id", 0); - int max_id = intent.getIntExtra("max_id", 0); + long dialogId = intent.getLongExtra("dialog_id", 0); + int maxId = intent.getIntExtra("max_id", 0); int currentAccount = intent.getIntExtra("currentAccount", 0); - if (dialog_id == 0 || max_id == 0 || !UserConfig.isValidAccount(currentAccount)) { + if (dialogId == 0 || maxId == 0 || !UserConfig.isValidAccount(currentAccount)) { return; } - int lowerId = (int) dialog_id; - int highId = (int) (dialog_id >> 32); AccountInstance accountInstance = AccountInstance.getInstance(currentAccount); - if (lowerId > 0) { - TLRPC.User user = accountInstance.getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = accountInstance.getMessagesController().getUser(dialogId); if (user == null) { Utilities.globalQueue.postRunnable(() -> { - TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(lowerId); + TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(dialogId); AndroidUtilities.runOnUIThread(() -> { accountInstance.getMessagesController().putUser(user1, true); - sendMessage(accountInstance, text, dialog_id, max_id); + sendMessage(accountInstance, text, dialogId, maxId); }); }); return; } - } else if (lowerId < 0) { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-lowerId); + } else if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialogId); if (chat == null) { Utilities.globalQueue.postRunnable(() -> { - TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-lowerId); + TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-dialogId); AndroidUtilities.runOnUIThread(() -> { accountInstance.getMessagesController().putChat(chat1, true); - sendMessage(accountInstance, text, dialog_id, max_id); + sendMessage(accountInstance, text, dialogId, maxId); }); }); return; } } - sendMessage(accountInstance, text, dialog_id, max_id); + sendMessage(accountInstance, text, dialogId, maxId); } private void sendMessage(AccountInstance accountInstance, CharSequence text, long dialog_id, int max_id) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraController.java b/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraController.java index 95f7e7d34..e79b8d3dc 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraController.java @@ -239,6 +239,7 @@ public class CameraController implements MediaRecorder.OnInfoListener { NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.cameraInitied); }); } catch (Exception e) { + FileLog.e(e); AndroidUtilities.runOnUIThread(() -> { onFinishCameraInitRunnables.clear(); loadingCameras = false; @@ -247,7 +248,6 @@ public class CameraController implements MediaRecorder.OnInfoListener { AndroidUtilities.runOnUIThread(() -> initCamera(onInitRunnable, true), 1000); } }); - } }); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraSession.java b/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraSession.java index 7c4a2452e..71e364cf9 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraSession.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/camera/CameraSession.java @@ -264,8 +264,6 @@ public class CameraSession { if (params.getMaxNumMeteringAreas() > 0) { meteringAreaSupported = true; } - - } } } catch (Throwable e) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseIntArray.java b/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseIntArray.java new file mode 100644 index 000000000..d82cc62f9 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseIntArray.java @@ -0,0 +1,251 @@ +/* + * This is the source code of Telegram for Android v. 5.x.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2018. + */ + +package org.telegram.messenger.support; + +/** + * SparseLongArrays map integers to longs. Unlike a normal array of longs, + * there can be gaps in the indices. It is intended to be more memory efficient + * than using a HashMap to map Integers to Longs, both because it avoids + * auto-boxing keys and values and its data structure doesn't rely on an extra entry object + * for each mapping. + * + *

Note that this container keeps its mappings in an array data structure, + * using a binary search to find keys. The implementation is not intended to be appropriate for + * data structures + * that may contain large numbers of items. It is generally slower than a traditional + * HashMap, since lookups require a binary search and adds and removes require inserting + * and deleting entries in the array. For containers holding up to hundreds of items, + * the performance difference is not significant, less than 50%.

+ * + *

It is possible to iterate over the items in this container using + * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using + * keyAt(int) with ascending values of the index will return the + * keys in ascending order, or the values corresponding to the keys in ascending + * order in the case of valueAt(int).

+ */ +public class LongSparseIntArray implements Cloneable { + + private long[] mKeys; + private int[] mValues; + private int mSize; + + /** + * Creates a new SparseLongArray containing no mappings. + */ + public LongSparseIntArray() { + this(10); + } + + /** + * Creates a new SparseLongArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public LongSparseIntArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealLongArraySize(initialCapacity); + + mKeys = new long[initialCapacity]; + mValues = new int[initialCapacity]; + mSize = 0; + } + + @Override + public LongSparseIntArray clone() { + LongSparseIntArray clone = null; + try { + clone = (LongSparseIntArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the long mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public int get(long key) { + return get(key, 0); + } + + /** + * Gets the long mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public int get(long key, int valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(long key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + removeAt(i); + } + } + + /** + * Removes the mapping at the given index. + */ + public void removeAt(int index) { + System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1)); + System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1)); + mSize--; + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(long key, int value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + growKeyAndValueArrays(mSize + 1); + } + + if (mSize - i != 0) { + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseIntArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public long keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public int valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(long key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(long value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseIntArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(long key, int value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + growKeyAndValueArrays(pos + 1); + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private void growKeyAndValueArrays(int minNeededSize) { + int n = ArrayUtils.idealLongArraySize(minNeededSize); + + long[] nkeys = new long[n]; + int[] nvalues = new int[n]; + + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + private static int binarySearch(long[] a, int start, int len, long key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseLongArray.java b/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseLongArray.java new file mode 100644 index 000000000..6c5158b9f --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/messenger/support/LongSparseLongArray.java @@ -0,0 +1,251 @@ +/* + * This is the source code of Telegram for Android v. 5.x.x. + * It is licensed under GNU GPL v. 2 or later. + * You should have received a copy of the license in this archive (see LICENSE). + * + * Copyright Nikolai Kudashov, 2013-2018. + */ + +package org.telegram.messenger.support; + +/** + * SparseLongArrays map integers to longs. Unlike a normal array of longs, + * there can be gaps in the indices. It is intended to be more memory efficient + * than using a HashMap to map Integers to Longs, both because it avoids + * auto-boxing keys and values and its data structure doesn't rely on an extra entry object + * for each mapping. + * + *

Note that this container keeps its mappings in an array data structure, + * using a binary search to find keys. The implementation is not intended to be appropriate for + * data structures + * that may contain large numbers of items. It is generally slower than a traditional + * HashMap, since lookups require a binary search and adds and removes require inserting + * and deleting entries in the array. For containers holding up to hundreds of items, + * the performance difference is not significant, less than 50%.

+ * + *

It is possible to iterate over the items in this container using + * {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using + * keyAt(int) with ascending values of the index will return the + * keys in ascending order, or the values corresponding to the keys in ascending + * order in the case of valueAt(int).

+ */ +public class LongSparseLongArray implements Cloneable { + + private long[] mKeys; + private long[] mValues; + private int mSize; + + /** + * Creates a new SparseLongArray containing no mappings. + */ + public LongSparseLongArray() { + this(10); + } + + /** + * Creates a new SparseLongArray containing no mappings that will not + * require any additional memory allocation to store the specified + * number of mappings. + */ + public LongSparseLongArray(int initialCapacity) { + initialCapacity = ArrayUtils.idealLongArraySize(initialCapacity); + + mKeys = new long[initialCapacity]; + mValues = new long[initialCapacity]; + mSize = 0; + } + + @Override + public LongSparseLongArray clone() { + LongSparseLongArray clone = null; + try { + clone = (LongSparseLongArray) super.clone(); + clone.mKeys = mKeys.clone(); + clone.mValues = mValues.clone(); + } catch (CloneNotSupportedException cnse) { + /* ignore */ + } + return clone; + } + + /** + * Gets the long mapped from the specified key, or 0 + * if no such mapping has been made. + */ + public long get(long key) { + return get(key, 0); + } + + /** + * Gets the long mapped from the specified key, or the specified value + * if no such mapping has been made. + */ + public long get(long key, long valueIfKeyNotFound) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i < 0) { + return valueIfKeyNotFound; + } else { + return mValues[i]; + } + } + + /** + * Removes the mapping from the specified key, if there was any. + */ + public void delete(long key) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + removeAt(i); + } + } + + /** + * Removes the mapping at the given index. + */ + public void removeAt(int index) { + System.arraycopy(mKeys, index + 1, mKeys, index, mSize - (index + 1)); + System.arraycopy(mValues, index + 1, mValues, index, mSize - (index + 1)); + mSize--; + } + + /** + * Adds a mapping from the specified key to the specified value, + * replacing the previous mapping from the specified key if there + * was one. + */ + public void put(long key, long value) { + int i = binarySearch(mKeys, 0, mSize, key); + + if (i >= 0) { + mValues[i] = value; + } else { + i = ~i; + + if (mSize >= mKeys.length) { + growKeyAndValueArrays(mSize + 1); + } + + if (mSize - i != 0) { + System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i); + System.arraycopy(mValues, i, mValues, i + 1, mSize - i); + } + + mKeys[i] = key; + mValues[i] = value; + mSize++; + } + } + + /** + * Returns the number of key-value mappings that this SparseIntArray + * currently stores. + */ + public int size() { + return mSize; + } + + /** + * Given an index in the range 0...size()-1, returns + * the key from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public long keyAt(int index) { + return mKeys[index]; + } + + /** + * Given an index in the range 0...size()-1, returns + * the value from the indexth key-value mapping that this + * SparseLongArray stores. + */ + public long valueAt(int index) { + return mValues[index]; + } + + /** + * Returns the index for which {@link #keyAt} would return the + * specified key, or a negative number if the specified + * key is not mapped. + */ + public int indexOfKey(long key) { + return binarySearch(mKeys, 0, mSize, key); + } + + /** + * Returns an index for which {@link #valueAt} would return the + * specified key, or a negative number if no keys map to the + * specified value. + * Beware that this is a linear search, unlike lookups by key, + * and that multiple keys can map to the same value and this will + * find only one of them. + */ + public int indexOfValue(long value) { + for (int i = 0; i < mSize; i++) + if (mValues[i] == value) + return i; + + return -1; + } + + /** + * Removes all key-value mappings from this SparseIntArray. + */ + public void clear() { + mSize = 0; + } + + /** + * Puts a key/value pair into the array, optimizing for the case where + * the key is greater than all existing keys in the array. + */ + public void append(long key, long value) { + if (mSize != 0 && key <= mKeys[mSize - 1]) { + put(key, value); + return; + } + + int pos = mSize; + if (pos >= mKeys.length) { + growKeyAndValueArrays(pos + 1); + } + + mKeys[pos] = key; + mValues[pos] = value; + mSize = pos + 1; + } + + private void growKeyAndValueArrays(int minNeededSize) { + int n = ArrayUtils.idealLongArraySize(minNeededSize); + + long[] nkeys = new long[n]; + long[] nvalues = new long[n]; + + System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length); + System.arraycopy(mValues, 0, nvalues, 0, mValues.length); + + mKeys = nkeys; + mValues = nvalues; + } + + private static int binarySearch(long[] a, int start, int len, long key) { + int high = start + len, low = start - 1, guess; + + while (high - low > 1) { + guess = (high + low) / 2; + + if (a[guess] < key) + low = guess; + else + high = guess; + } + + if (high == start + len) + return ~(start + len); + else if (a[high] == key) + return high; + else + return ~high; + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/video/MediaCodecVideoConvertor.java b/TMessagesProj/src/main/java/org/telegram/messenger/video/MediaCodecVideoConvertor.java index d6c3c4a70..2a1abfd08 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/video/MediaCodecVideoConvertor.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/video/MediaCodecVideoConvertor.java @@ -7,10 +7,21 @@ import android.media.MediaExtractor; import android.media.MediaFormat; import android.os.Build; +import com.google.android.exoplayer2.util.Log; + +import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BuildVars; import org.telegram.messenger.FileLog; +import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; +import org.telegram.messenger.NotificationCenter; +import org.telegram.messenger.NotificationsController; +import org.telegram.messenger.R; +import org.telegram.messenger.UserConfig; import org.telegram.messenger.VideoEditedInfo; +import org.telegram.ui.Components.Bulletin; +import org.telegram.ui.Components.BulletinFactory; +import org.telegram.ui.LaunchActivity; import java.io.File; import java.nio.ByteBuffer; @@ -70,6 +81,7 @@ public class MediaCodecVideoConvertor { boolean isPhoto, MediaController.CropState cropState) { + long time = System.currentTimeMillis(); boolean error = false; boolean repeatWithIncreasedTimeout = false; int videoTrackIndex = -5; @@ -784,6 +796,11 @@ public class MediaCodecVideoConvertor { isPhoto, cropState); } + long timeLeft = System.currentTimeMillis() - time; + if (BuildVars.LOGS_ENABLED) { + FileLog.d("compression completed time=" + timeLeft + " needCompress=" + needCompress + " w=" + resultWidth + " h=" + resultHeight + " bitrate=" + bitrate); + } + return error; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPPendingCall.java b/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPPendingCall.java index cd97ecbb1..142536086 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPPendingCall.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPPendingCall.java @@ -15,7 +15,7 @@ import org.telegram.ui.Components.voip.VoIPHelper; public final class VoIPPendingCall { - public static VoIPPendingCall startOrSchedule(Activity activity, int userId, boolean video, AccountInstance accountInstance) { + public static VoIPPendingCall startOrSchedule(Activity activity, long userId, boolean video, AccountInstance accountInstance) { return new VoIPPendingCall(activity, userId, video, 1000, accountInstance); } @@ -27,7 +27,7 @@ public final class VoIPPendingCall { private final Runnable releaseRunnable = () -> onConnectionStateUpdated(true); - private final int userId; + private final long userId; private final boolean video; private final Activity activity; @@ -36,7 +36,7 @@ public final class VoIPPendingCall { private boolean released; private AccountInstance accountInstance; - private VoIPPendingCall(Activity activity, int userId, boolean video, long expirationTime, AccountInstance accountInstance) { + private VoIPPendingCall(Activity activity, long userId, boolean video, long expirationTime, AccountInstance accountInstance) { this.activity = activity; this.userId = userId; this.video = video; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java b/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java index 5bcf94226..8e0cdcd39 100755 --- a/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/voip/VoIPService.java @@ -483,7 +483,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa public boolean mutedByAdmin() { ChatObject.Call call = groupCall; if (call != null) { - int selfId = getSelfId(); + long selfId = getSelfId(); TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId); if (participant != null && !participant.can_self_unmute && participant.muted && !ChatObject.canManageCalls(chat)) { return true; @@ -666,14 +666,14 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa throw new IllegalStateException("No account specified when starting VoIP service"); } classGuid = ConnectionsManager.generateClassGuid(); - int userID = intent.getIntExtra("user_id", 0); - int chatID = intent.getIntExtra("chat_id", 0); + long userID = intent.getLongExtra("user_id", 0); + long chatID = intent.getLongExtra("chat_id", 0); createGroupCall = intent.getBooleanExtra("createGroupCall", false); hasFewPeers = intent.getBooleanExtra("hasFewPeers", false); joinHash = intent.getStringExtra("hash"); - int peerChannelId = intent.getIntExtra("peerChannelId", 0); - int peerChatId = intent.getIntExtra("peerChatId", 0); - int peerUserId = intent.getIntExtra("peerUserId", 0); + long peerChannelId = intent.getLongExtra("peerChannelId", 0); + long peerChatId = intent.getLongExtra("peerChatId", 0); + long peerUserId = intent.getLongExtra("peerUserId", 0); if (peerChatId != 0) { groupCallPeer = new TLRPC.TL_inputPeerChat(); groupCallPeer.chat_id = peerChatId; @@ -836,7 +836,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa createGroupInstance(CAPTURE_DEVICE_CAMERA, false); } - public int getCallerId() { + public long getCallerId() { if (user != null) { return user.id; } else { @@ -1321,7 +1321,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa tgVoip[CAPTURE_DEVICE_CAMERA].onSignalingDataReceive(data.data); } - public int getSelfId() { + public long getSelfId() { if (groupCallPeer == null) { return UserConfig.getInstance(currentAccount).clientUserId; } @@ -1338,7 +1338,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa if (chat == null || groupCall == null || groupCall.call.id != update.call.id) { return; } - int selfId = getSelfId(); + long selfId = getSelfId(); for (int a = 0, N = update.participants.size(); a < N; a++) { TLRPC.TL_groupCallParticipant participant = update.participants.get(a); if (participant.left) { @@ -1748,7 +1748,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa if (response != null) { AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_CAMERA] = ssrc); TLRPC.Updates updates = (TLRPC.Updates) response; - int selfId = getSelfId(); + long selfId = getSelfId(); for (int a = 0, N = updates.updates.size(); a < N; a++) { TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateGroupCallParticipants) { @@ -1817,7 +1817,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa TLRPC.Updates updates = (TLRPC.Updates) response; AndroidUtilities.runOnUIThread(() -> { if (tgVoip[CAPTURE_DEVICE_SCREEN] != null) { - int selfId = getSelfId(); + long selfId = getSelfId(); for (int a = 0, N = updates.updates.size(); a < N; a++) { TLRPC.Update update = updates.updates.get(a); if (update instanceof TLRPC.TL_updateGroupCallConnection) { @@ -1964,7 +1964,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa if (groupCall == null || tgVoip[CAPTURE_DEVICE_CAMERA] == null) { return; } - int selfId = getSelfId(); + long selfId = getSelfId(); ArrayList participants = null; for (int a = 0, N = unknown.length; a < N; a++) { TLRPC.TL_groupCallParticipant p = groupCall.participantsBySources.get(unknown[a]); @@ -2849,7 +2849,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa startForeground(ID_ONGOING_CALL_NOTIFICATION, builder.getNotification()); } - private void startRingtoneAndVibration(int chatID) { + private void startRingtoneAndVibration(long chatID) { SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount); AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); boolean needRing = am.getRingerMode() != AudioManager.RINGER_MODE_SILENT; diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java b/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java index be1960813..f42520d8f 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java @@ -352,7 +352,7 @@ public class ConnectionsManager extends BaseController { return connectionState; } - public void setUserId(int id) { + public void setUserId(long id) { native_setUserId(currentAccount, id); } @@ -365,13 +365,14 @@ public class ConnectionsManager extends BaseController { native_setPushConnectionEnabled(currentAccount, value); } - public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, int timezoneOffset, int userId, boolean enablePushConnection) { + public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, int timezoneOffset, long userId, boolean enablePushConnection) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); String proxyAddress = preferences.getString("proxy_ip", ""); String proxyUsername = preferences.getString("proxy_user", ""); String proxyPassword = preferences.getString("proxy_pass", ""); String proxySecret = preferences.getString("proxy_secret", ""); int proxyPort = preferences.getInt("proxy_port", 1080); + if (preferences.getBoolean("proxy_enabled", false) && !TextUtils.isEmpty(proxyAddress)) { native_setProxySettings(currentAccount, proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret); } @@ -680,6 +681,7 @@ public class ConnectionsManager extends BaseController { if (secret == null) { secret = ""; } + for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { if (enabled && !TextUtils.isEmpty(address)) { native_setProxySettings(a, address, port, username, password, secret); @@ -711,8 +713,8 @@ public class ConnectionsManager extends BaseController { public static native void native_bindRequestToGuid(int currentAccount, int requestToken, int guid); public static native void native_applyDatacenterAddress(int currentAccount, int datacenterId, String ipAddress, int port); public static native int native_getConnectionState(int currentAccount); - public static native void native_setUserId(int currentAccount, int id); - public static native void native_init(int currentAccount, int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, String installer, String packageId, int timezoneOffset, int userId, boolean enablePushConnection, boolean hasNetwork, int networkType); + public static native void native_setUserId(int currentAccount, long id); + public static native void native_init(int currentAccount, int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, String installer, String packageId, int timezoneOffset, long userId, boolean enablePushConnection, boolean hasNetwork, int networkType); public static native void native_setProxySettings(int currentAccount, String address, int port, String username, String password, String secret); public static native void native_setLangCode(int currentAccount, String langCode); public static native void native_setRegId(int currentAccount, String regId); diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java b/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java index 7ba789685..55000fb8c 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java @@ -5,6 +5,7 @@ import org.telegram.messenger.FileLog; import java.nio.ByteBuffer; import java.nio.ByteOrder; +import java.util.LinkedList; public class NativeByteBuffer extends AbstractSerializedData { @@ -14,20 +15,19 @@ public class NativeByteBuffer extends AbstractSerializedData { private int len; public boolean reused = true; - private static final ThreadLocal addressWrapper = new ThreadLocal() { + private static final ThreadLocal> addressWrappers = new ThreadLocal>() { @Override - protected NativeByteBuffer initialValue() { - return new NativeByteBuffer(0, true); + protected LinkedList initialValue() { + return new LinkedList<>(); } }; public static NativeByteBuffer wrap(long address) { - NativeByteBuffer result = addressWrapper.get(); if (address != 0) { - if (!result.reused) { - if (BuildVars.LOGS_ENABLED) { - FileLog.e("forgot to reuse?"); - } + LinkedList queue = addressWrappers.get(); + NativeByteBuffer result = queue.poll(); + if (result == null) { + result = new NativeByteBuffer(0, true); } result.address = address; result.reused = false; @@ -38,8 +38,10 @@ public class NativeByteBuffer extends AbstractSerializedData { result.buffer.position(position); } result.buffer.order(ByteOrder.LITTLE_ENDIAN); + return result; + } else { + return null; } - return result; } private NativeByteBuffer(int address, boolean wrap) { @@ -567,6 +569,7 @@ public class NativeByteBuffer extends AbstractSerializedData { public void reuse() { if (address != 0) { + addressWrappers.get().add(this); reused = true; native_reuse(address); } diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/ResultCallback.java b/TMessagesProj/src/main/java/org/telegram/tgnet/ResultCallback.java new file mode 100644 index 000000000..c9ebac73a --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/ResultCallback.java @@ -0,0 +1,10 @@ +package org.telegram.tgnet; + +public interface ResultCallback { + + void onComplete(T result); + + default void onError(TLRPC.TL_error error) {} + + default void onError(Throwable throwable) {} +} diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java index 4f7021bcf..a9398f35b 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java @@ -64,7 +64,7 @@ public class TLRPC { public static final int MESSAGE_FLAG_HAS_BOT_ID = 0x00000800; public static final int MESSAGE_FLAG_EDITED = 0x00008000; - public static final int LAYER = 132; + public static final int LAYER = 133; public static class TL_stats_megagroupStats extends TLObject { public static int constructor = 0xef7ff916; @@ -666,12 +666,12 @@ public class TLRPC { } public static class TL_payments_paymentReceipt extends TLObject { - public static int constructor = 0x10b555d0; + public static int constructor = 0x70c4fe03; public int flags; public int date; - public int bot_id; - public int provider_id; + public long bot_id; + public long provider_id; public String title; public String description; public WebDocument photo; @@ -700,8 +700,8 @@ public class TLRPC { public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); date = stream.readInt32(exception); - bot_id = stream.readInt32(exception); - provider_id = stream.readInt32(exception); + bot_id = stream.readInt64(exception); + provider_id = stream.readInt64(exception); title = stream.readString(exception); description = stream.readString(exception); if ((flags & 4) != 0) { @@ -741,8 +741,8 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(date); - stream.writeInt32(bot_id); - stream.writeInt32(provider_id); + stream.writeInt64(bot_id); + stream.writeInt64(provider_id); stream.writeString(title); stream.writeString(description); if ((flags & 4) != 0) { @@ -1965,36 +1965,36 @@ public class TLRPC { } } - public static class TL_contactStatus extends TLObject { - public static int constructor = 0xd3680c61; + public static class TL_contactStatus extends TLObject { + public static int constructor = 0x16d9703b; - public int user_id; - public UserStatus status; + public long user_id; + public UserStatus status; - public static TL_contactStatus TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_contactStatus.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_contactStatus", constructor)); - } else { - return null; - } - } - TL_contactStatus result = new TL_contactStatus(); - result.readParams(stream, exception); - return result; - } + public static TL_contactStatus TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_contactStatus.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_contactStatus", constructor)); + } else { + return null; + } + } + TL_contactStatus result = new TL_contactStatus(); + result.readParams(stream, exception); + return result; + } - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - status = UserStatus.TLdeserialize(stream, stream.readInt32(exception), exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + status = UserStatus.TLdeserialize(stream, stream.readInt32(exception), exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - status.serializeToStream(stream); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + status.serializeToStream(stream); + } + } public static abstract class GroupCall extends TLObject { @@ -2231,7 +2231,7 @@ public class TLRPC { public static class TL_messageUserReaction extends TLObject { public static int constructor = 0xd267dcbc; - public int user_id; + public long user_id; public String reaction; public static TL_messageUserReaction TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -2254,7 +2254,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeString(reaction); } } @@ -2988,9 +2988,9 @@ public class TLRPC { } public static class TL_statsGroupTopAdmin extends TLObject { - public static int constructor = 0x6014f412; + public static int constructor = 0xd7584c87; - public int user_id; + public long user_id; public int deleted; public int kicked; public int banned; @@ -3009,7 +3009,7 @@ public class TLRPC { } public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); deleted = stream.readInt32(exception); kicked = stream.readInt32(exception); banned = stream.readInt32(exception); @@ -3017,7 +3017,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(deleted); stream.writeInt32(kicked); stream.writeInt32(banned); @@ -3025,15 +3025,15 @@ public class TLRPC { } public static class TL_payments_paymentForm extends TLObject { - public static int constructor = 0x8d0b2415; + public static int constructor = 0x1694761b; public int flags; public boolean can_save_credentials; public boolean password_missing; public long form_id; - public int bot_id; + public long bot_id; public TL_invoice invoice; - public int provider_id; + public long provider_id; public String url; public String native_provider; public TL_dataJSON native_params; @@ -3059,9 +3059,9 @@ public class TLRPC { can_save_credentials = (flags & 4) != 0; password_missing = (flags & 8) != 0; form_id = stream.readInt64(exception); - bot_id = stream.readInt32(exception); + bot_id = stream.readInt64(exception); invoice = TL_invoice.TLdeserialize(stream, stream.readInt32(exception), exception); - provider_id = stream.readInt32(exception); + provider_id = stream.readInt64(exception); url = stream.readString(exception); if ((flags & 16) != 0) { native_provider = stream.readString(exception); @@ -3098,9 +3098,9 @@ public class TLRPC { flags = password_missing ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); stream.writeInt64(form_id); - stream.writeInt32(bot_id); + stream.writeInt64(bot_id); invoice.serializeToStream(stream); - stream.writeInt32(provider_id); + stream.writeInt64(provider_id); stream.writeString(url); if ((flags & 16) != 0) { stream.writeString(native_provider); @@ -3268,75 +3268,127 @@ public class TLRPC { } } - public static abstract class Peer extends TLObject { - public int channel_id; - public int user_id; - public int chat_id; + public static abstract class Peer extends TLObject { - public static Peer TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - Peer result = null; - switch (constructor) { - case 0xbddde532: - result = new TL_peerChannel(); - break; - case 0x9db1bc6d: - result = new TL_peerUser(); - break; - case 0xbad0e5bb: - result = new TL_peerChat(); - break; - } - if (result == null && exception) { - throw new RuntimeException(String.format("can't parse magic %x in Peer", constructor)); - } - if (result != null) { - result.readParams(stream, exception); - } - return result; - } - } + public long user_id; + public long chat_id; + public long channel_id; - public static class TL_peerChannel extends Peer { - public static int constructor = 0xbddde532; + public static Peer TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + Peer result = null; + switch (constructor) { + case 0xbddde532: + result = new TL_peerChannel_layer131(); + break; + case 0x59511722: + result = new TL_peerUser(); + break; + case 0xa2a5371e: + result = new TL_peerChannel(); + break; + case 0x36c6019a: + result = new TL_peerChat(); + break; + case 0x9db1bc6d: + result = new TL_peerUser_layer131(); + break; + case 0xbad0e5bb: + result = new TL_peerChat_layer131(); + break; + } + if (result == null && exception) { + throw new RuntimeException(String.format("can't parse magic %x in Peer", constructor)); + } + if (result != null) { + result.readParams(stream, exception); + } + return result; + } + } + + public static class TL_peerChannel_layer131 extends TL_peerChannel { + public static int constructor = 0xbddde532; - public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(channel_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) channel_id); + } + } - public static class TL_peerUser extends Peer { - public static int constructor = 0x9db1bc6d; + public static class TL_peerUser extends Peer { + public static int constructor = 0x59511722; - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + } + } - public static class TL_peerChat extends Peer { - public static int constructor = 0xbad0e5bb; + public static class TL_peerChannel extends Peer { + public static int constructor = 0xa2a5371e; - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + } + } + + public static class TL_peerChat extends Peer { + public static int constructor = 0x36c6019a; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + } + } + + public static class TL_peerUser_layer131 extends TL_peerUser { + public static int constructor = 0x9db1bc6d; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) user_id); + } + } + + public static class TL_peerChat_layer131 extends TL_peerChat { + public static int constructor = 0xbad0e5bb; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) chat_id); + } + } public static class TL_labeledPrice extends TLObject { public static int constructor = 0xcb296bf8; @@ -3714,7 +3766,7 @@ public class TLRPC { public boolean min; public ArrayList results = new ArrayList<>(); public int total_voters; - public ArrayList recent_voters = new ArrayList<>(); + public ArrayList recent_voters = new ArrayList<>(); public String solution; public ArrayList solution_entities = new ArrayList<>(); @@ -3728,6 +3780,9 @@ public class TLRPC { result = new TL_pollResults_layer111(); break; case 0xbadcc1a3: + result = new TL_pollResults_layer131(); + break; + case 0xdcb82ea3: result = new TL_pollResults(); break; } @@ -3825,7 +3880,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - recent_voters.add(stream.readInt32(exception)); + recent_voters.add((long) stream.readInt32(exception)); } } } @@ -3850,13 +3905,13 @@ public class TLRPC { int count = recent_voters.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(recent_voters.get(a)); + stream.writeInt32((int) (long) recent_voters.get(a)); } } } } - public static class TL_pollResults extends PollResults { + public static class TL_pollResults_layer131 extends TL_pollResults { public static int constructor = 0xbadcc1a3; @@ -3893,7 +3948,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - recent_voters.add(stream.readInt32(exception)); + recent_voters.add((long) stream.readInt32(exception)); } } if ((flags & 16) != 0) { @@ -3938,7 +3993,106 @@ public class TLRPC { int count = recent_voters.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(recent_voters.get(a)); + stream.writeInt32((int) (long) recent_voters.get(a)); + } + } + if ((flags & 16) != 0) { + stream.writeString(solution); + } + if ((flags & 16) != 0) { + stream.writeInt32(0x1cb5c415); + int count = solution_entities.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + solution_entities.get(a).serializeToStream(stream); + } + } + } + } + + public static class TL_pollResults extends PollResults { + public static int constructor = 0xdcb82ea3; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + min = (flags & 1) != 0; + if ((flags & 2) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_pollAnswerVoters object = TL_pollAnswerVoters.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + results.add(object); + } + } + if ((flags & 4) != 0) { + total_voters = stream.readInt32(exception); + } + if ((flags & 8) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + recent_voters.add(stream.readInt64(exception)); + } + } + if ((flags & 16) != 0) { + solution = stream.readString(exception); + } + if ((flags & 16) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + MessageEntity object = MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + solution_entities.add(object); + } + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = min ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + if ((flags & 2) != 0) { + stream.writeInt32(0x1cb5c415); + int count = results.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + results.get(a).serializeToStream(stream); + } + } + if ((flags & 4) != 0) { + stream.writeInt32(total_voters); + } + if ((flags & 8) != 0) { + stream.writeInt32(0x1cb5c415); + int count = recent_voters.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(recent_voters.get(a)); } } if ((flags & 16) != 0) { @@ -5336,47 +5490,47 @@ public class TLRPC { } } - public static class TL_channelAdminLogEvent extends TLObject { - public static int constructor = 0x3b5a3e40; + public static class TL_channelAdminLogEvent extends TLObject { + public static int constructor = 0x1fad68cd; - public long id; - public int date; - public int user_id; - public ChannelAdminLogEventAction action; + public long id; + public int date; + public long user_id; + public ChannelAdminLogEventAction action; - public static TL_channelAdminLogEvent TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_channelAdminLogEvent.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_channelAdminLogEvent", constructor)); - } else { - return null; - } - } - TL_channelAdminLogEvent result = new TL_channelAdminLogEvent(); - result.readParams(stream, exception); - return result; - } + public static TL_channelAdminLogEvent TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_channelAdminLogEvent.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_channelAdminLogEvent", constructor)); + } else { + return null; + } + } + TL_channelAdminLogEvent result = new TL_channelAdminLogEvent(); + result.readParams(stream, exception); + return result; + } - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt64(exception); - date = stream.readInt32(exception); - user_id = stream.readInt32(exception); - action = ChannelAdminLogEventAction.TLdeserialize(stream, stream.readInt32(exception), exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt64(exception); + date = stream.readInt32(exception); + user_id = stream.readInt64(exception); + action = ChannelAdminLogEventAction.TLdeserialize(stream, stream.readInt32(exception), exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(id); - stream.writeInt32(date); - stream.writeInt32(user_id); - action.serializeToStream(stream); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(id); + stream.writeInt32(date); + stream.writeInt64(user_id); + action.serializeToStream(stream); + } + } public static abstract class messages_FavedStickers extends TLObject { - public int hash; - public ArrayList packs = new ArrayList<>(); - public ArrayList stickers = new ArrayList<>(); + public long hash; + public ArrayList packs = new ArrayList<>(); + public ArrayList stickers = new ArrayList<>(); public static messages_FavedStickers TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { messages_FavedStickers result = null; @@ -5384,9 +5538,9 @@ public class TLRPC { case 0x9e8fa6d3: result = new TL_messages_favedStickersNotModified(); break; - case 0xf37f2f16: - result = new TL_messages_favedStickers(); - break; + case 0x2cb51097: + result = new TL_messages_favedStickers(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in messages_FavedStickers", constructor)); @@ -5407,61 +5561,61 @@ public class TLRPC { } } - public static class TL_messages_favedStickers extends messages_FavedStickers { - public static int constructor = 0xf37f2f16; + public static class TL_messages_favedStickers extends messages_FavedStickers { + public static int constructor = 0x2cb51097; - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - TL_stickerPack object = TL_stickerPack.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - packs.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - stickers.add(object); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_stickerPack object = TL_stickerPack.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + packs.add(object); + } + magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + stickers.add(object); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = packs.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - packs.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = stickers.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stickers.get(a).serializeToStream(stream); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = packs.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + packs.get(a).serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + count = stickers.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stickers.get(a).serializeToStream(stream); + } + } + } public static class TL_langPackLanguage extends TLObject { public static int constructor = 0xeeca5ce3; @@ -5526,9 +5680,9 @@ public class TLRPC { } public static class TL_chatInviteImporter extends TLObject { - public static int constructor = 0x1e3e6680; + public static int constructor = 0xb5cd5f4; - public int user_id; + public long user_id; public int date; public static TL_chatInviteImporter TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -5545,13 +5699,13 @@ public class TLRPC { } public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(date); } } @@ -5622,6 +5776,12 @@ public class TLRPC { case 0xa187d66f: result = new TL_sendMessageRecordVideoAction(); break; + case 0x25972bcb: + result = new TL_sendMessageEmojiInteraction(); + break; + case 0xb665902e: + result = new TL_sendMessageEmojiInteractionSeen(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in SendMessageAction", constructor)); @@ -5663,7 +5823,28 @@ public class TLRPC { } } - public static class TL_sendMessageUploadAudioAction_old extends TL_sendMessageUploadAudioAction { + public static class TL_sendMessageEmojiInteraction extends SendMessageAction { + public static int constructor = 0x25972bcb; + + public String emoticon; + public int msg_id; + public TL_dataJSON interaction; + + public void readParams(AbstractSerializedData stream, boolean exception) { + emoticon = stream.readString(exception); + msg_id = stream.readInt32(exception); + interaction = TL_dataJSON.TLdeserialize(stream, stream.readInt32(exception), exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(emoticon); + stream.writeInt32(msg_id); + interaction.serializeToStream(stream); + } + } + + public static class TL_sendMessageUploadAudioAction_old extends TL_sendMessageUploadAudioAction { public static int constructor = 0xe6ac8a6f; @@ -5788,6 +5969,21 @@ public class TLRPC { } } + public static class TL_sendMessageEmojiInteractionSeen extends SendMessageAction { + public static int constructor = 0xb665902e; + + public String emoticon; + + public void readParams(AbstractSerializedData stream, boolean exception) { + emoticon = stream.readString(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(emoticon); + } + } + public static class TL_sendMessageTypingAction extends SendMessageAction { public static int constructor = 0x16bf744e; @@ -6067,9 +6263,9 @@ public class TLRPC { } public static class TL_statsGroupTopInviter extends TLObject { - public static int constructor = 0x31962a4c; + public static int constructor = 0x535f779d; - public int user_id; + public long user_id; public int invitations; public static TL_statsGroupTopInviter TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -6086,13 +6282,13 @@ public class TLRPC { } public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); invitations = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(invitations); } } @@ -6329,16 +6525,42 @@ public class TLRPC { } } - public static class TL_themeSettings extends TLObject { - public static int constructor = 0x8db4e76c; + public static abstract class ThemeSettings extends TLObject { public int flags; public boolean message_colors_animated; public BaseTheme base_theme; public int accent_color; + public int outbox_accent_color; public ArrayList message_colors = new ArrayList<>(); public WallPaper wallpaper; + public static ThemeSettings TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + ThemeSettings result = null; + switch (constructor) { + case 0xfa58b6d4: + result = new TL_themeSettings(); + break; + case 0x8db4e76c: + result = new TL_themeSettings_layer132(); + break; + case 0x9c14984a: + result = new TL_themeSettings_layer131(); + break; + } + if (result == null && exception) { + throw new RuntimeException(String.format("can't parse magic %x in ThemeSettings", constructor)); + } + if (result != null) { + result.readParams(stream, exception); + } + return result; + } + } + + public static class TL_themeSettings extends ThemeSettings { + public static int constructor = 0xfa58b6d4; + public static TL_themeSettings TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_themeSettings.constructor != constructor) { if (exception) { @@ -6352,6 +6574,59 @@ public class TLRPC { return result; } + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + message_colors_animated = (flags & 4) != 0; + base_theme = BaseTheme.TLdeserialize(stream, stream.readInt32(exception), exception); + accent_color = stream.readInt32(exception); + if ((flags & 8) != 0) { + outbox_accent_color = stream.readInt32(exception); + } + if ((flags & 1) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + message_colors.add(stream.readInt32(exception)); + } + } + if ((flags & 2) != 0) { + wallpaper = WallPaper.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = message_colors_animated ? (flags | 4) : (flags &~ 4); + stream.writeInt32(flags); + base_theme.serializeToStream(stream); + stream.writeInt32(accent_color); + if ((flags & 8) != 0) { + stream.writeInt32(outbox_accent_color); + } + if ((flags & 1) != 0) { + stream.writeInt32(0x1cb5c415); + int count = message_colors.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt32(message_colors.get(a)); + } + } + if ((flags & 2) != 0) { + wallpaper.serializeToStream(stream); + } + } + } + + public static class TL_themeSettings_layer132 extends ThemeSettings { + public static int constructor = 0x8db4e76c; + + public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); message_colors_animated = (flags & 4) != 0; @@ -6395,6 +6670,48 @@ public class TLRPC { } } + public static class TL_themeSettings_layer131 extends ThemeSettings { + public static int constructor = 0x9c14984a; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + base_theme = BaseTheme.TLdeserialize(stream, stream.readInt32(exception), exception); + accent_color = stream.readInt32(exception); + if ((flags & 1) != 0) { + int color = stream.readInt32(exception); + if (color != 0) { + message_colors.add(color); + } + } + if ((flags & 1) != 0) { + int color = stream.readInt32(exception); + if (color != 0) { + message_colors.add(0, color); + } + } + if ((flags & 2) != 0) { + wallpaper = WallPaper.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + base_theme.serializeToStream(stream); + stream.writeInt32(accent_color); + if ((flags & 1) != 0) { + stream.writeInt32(message_colors.size() > 1 ? message_colors.get(1) : 0); + } + if ((flags & 1) != 0) { + stream.writeInt32(message_colors.size() > 0 ? message_colors.get(0) : 0); + } + if ((flags & 2) != 0) { + wallpaper.serializeToStream(stream); + } + } + } + public static class TL_pageCaption extends TLObject { public static int constructor = 0x6f747657; @@ -6434,13 +6751,13 @@ public class TLRPC { case 0xf888fa1a: result = new TL_privacyValueDisallowContacts(); break; - case 0xc7f49b7: + case 0xe4621141: result = new TL_privacyValueDisallowUsers(); break; - case 0x18be796b: + case 0x6b134e8e: result = new TL_privacyValueAllowChatParticipants(); break; - case 0xacae0690: + case 0x41c87565: result = new TL_privacyValueDisallowChatParticipants(); break; case 0x65427b82: @@ -6449,7 +6766,7 @@ public class TLRPC { case 0x8b73e763: result = new TL_privacyValueDisallowAll(); break; - case 0x4d5bbe0c: + case 0xb8905fb2: result = new TL_privacyValueAllowUsers(); break; case 0xfffe1bac: @@ -6476,9 +6793,9 @@ public class TLRPC { } public static class TL_privacyValueDisallowUsers extends PrivacyRule { - public static int constructor = 0xc7f49b7; + public static int constructor = 0xe4621141; - public ArrayList users = new ArrayList<>(); + public ArrayList users = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -6490,7 +6807,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - users.add(stream.readInt32(exception)); + users.add(stream.readInt64(exception)); } } @@ -6500,15 +6817,15 @@ public class TLRPC { int count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(users.get(a)); + stream.writeInt64(users.get(a)); } } } public static class TL_privacyValueAllowChatParticipants extends PrivacyRule { - public static int constructor = 0x18be796b; + public static int constructor = 0x6b134e8e; - public ArrayList chats = new ArrayList<>(); + public ArrayList chats = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -6520,7 +6837,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - chats.add(stream.readInt32(exception)); + chats.add(stream.readInt64(exception)); } } @@ -6530,15 +6847,15 @@ public class TLRPC { int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(chats.get(a)); + stream.writeInt64(chats.get(a)); } } } public static class TL_privacyValueDisallowChatParticipants extends PrivacyRule { - public static int constructor = 0xacae0690; + public static int constructor = 0x41c87565; - public ArrayList chats = new ArrayList<>(); + public ArrayList chats = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -6550,7 +6867,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - chats.add(stream.readInt32(exception)); + chats.add(stream.readInt64(exception)); } } @@ -6560,7 +6877,7 @@ public class TLRPC { int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(chats.get(a)); + stream.writeInt64(chats.get(a)); } } } @@ -6584,9 +6901,9 @@ public class TLRPC { } public static class TL_privacyValueAllowUsers extends PrivacyRule { - public static int constructor = 0x4d5bbe0c; + public static int constructor = 0xb8905fb2; - public ArrayList users = new ArrayList<>(); + public ArrayList users = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -6598,7 +6915,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - users.add(stream.readInt32(exception)); + users.add(stream.readInt64(exception)); } } @@ -6608,7 +6925,7 @@ public class TLRPC { int count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(users.get(a)); + stream.writeInt64(users.get(a)); } } } @@ -7093,7 +7410,7 @@ public class TLRPC { stream.writeString(phone_number); stream.writeString(first_name); stream.writeString(last_name); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } @@ -7129,7 +7446,7 @@ public class TLRPC { } } - public static class TL_messageMediaContact extends MessageMedia { + public static class TL_messageMediaContact_layer131 extends TL_messageMediaContact { public static int constructor = 0xcbf24940; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -7146,10 +7463,32 @@ public class TLRPC { stream.writeString(first_name); stream.writeString(last_name); stream.writeString(vcard); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } + public static class TL_messageMediaContact extends MessageMedia { + public static int constructor = 0x70322949; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + phone_number = stream.readString(exception); + first_name = stream.readString(exception); + last_name = stream.readString(exception); + vcard = stream.readString(exception); + user_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(phone_number); + stream.writeString(first_name); + stream.writeString(last_name); + stream.writeString(vcard); + stream.writeInt64(user_id); + } + } + public static class TL_messageMediaDice extends MessageMedia { public static int constructor = 0x3f7ee58b; @@ -8397,7 +8736,7 @@ public class TLRPC { public String mime_type; public int size; public int dc_id; - public int user_id; + public long user_id; public byte[] key; public byte[] iv; @@ -8488,7 +8827,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeInt32(duration); stream.writeInt32(size); @@ -8516,7 +8855,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeInt32(duration); stream.writeInt32(size); @@ -8545,7 +8884,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeInt32(duration); stream.writeString(mime_type); @@ -8713,7 +9052,7 @@ public class TLRPC { } public static abstract class BotInfo extends TLObject { - public int user_id; + public long user_id; public String description; public ArrayList commands = new ArrayList<>(); public int version; @@ -8725,11 +9064,14 @@ public class TLRPC { result = new TL_botInfoEmpty_layer48(); break; case 0x98e81d3a: - result = new TL_botInfo(); + result = new TL_botInfo_layer131(); break; case 0x9cf585d: result = new TL_botInfo_layer48(); break; + case 0x1b74b335: + result = new TL_botInfo(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in BotInfo", constructor)); @@ -8750,7 +9092,7 @@ public class TLRPC { } } - public static class TL_botInfo extends BotInfo { + public static class TL_botInfo_layer131 extends TL_botInfo { public static int constructor = 0x98e81d3a; @@ -8776,7 +9118,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeString(description); stream.writeInt32(0x1cb5c415); int count = commands.size(); @@ -8815,7 +9157,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(version); stream.writeString(""); stream.writeString(description); @@ -8828,6 +9170,43 @@ public class TLRPC { } } + public static class TL_botInfo extends BotInfo { + public static int constructor = 0x1b74b335; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + description = stream.readString(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_botCommand object = TL_botCommand.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + commands.add(object); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeString(description); + stream.writeInt32(0x1cb5c415); + int count = commands.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + commands.get(a).serializeToStream(stream); + } + } + } + public static abstract class InputGame extends TLObject { public InputUser bot_id; public String short_name; @@ -8886,30 +9265,40 @@ public class TLRPC { } } - public static class TL_messageReplies extends TLObject { - public static int constructor = 0x4128faac; + public static abstract class MessageReplies extends TLObject { public int flags; public boolean comments; public int replies; public int replies_pts; public ArrayList recent_repliers = new ArrayList<>(); - public int channel_id; + public long channel_id; public int max_id; public int read_max_id; - public static TL_messageReplies TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_messageReplies.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_messageReplies", constructor)); - } else { - return null; - } + public static MessageReplies TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + MessageReplies result = null; + switch (constructor) { + case 0x4128faac: + result = new TL_messageReplies_layer131(); + break; + case 0x83d60fc2: + result = new TL_messageReplies(); + break; + } + if (result == null && exception) { + throw new RuntimeException(String.format("can't parse magic %x in MessageReplies", constructor)); + } + if (result != null) { + result.readParams(stream, exception); } - TL_messageReplies result = new TL_messageReplies(); - result.readParams(stream, exception); return result; } + } + + public static class TL_messageReplies_layer131 extends TL_messageReplies { + public static int constructor = 0x4128faac; + public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); @@ -8959,7 +9348,70 @@ public class TLRPC { } } if ((flags & 1) != 0) { - stream.writeInt32(channel_id); + stream.writeInt32((int) channel_id); + } + if ((flags & 4) != 0) { + stream.writeInt32(max_id); + } + if ((flags & 8) != 0) { + stream.writeInt32(read_max_id); + } + } + } + + public static class TL_messageReplies extends MessageReplies { + public static int constructor = 0x83d60fc2; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + comments = (flags & 1) != 0; + replies = stream.readInt32(exception); + replies_pts = stream.readInt32(exception); + if ((flags & 2) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + Peer object = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + recent_repliers.add(object); + } + } + if ((flags & 1) != 0) { + channel_id = stream.readInt64(exception); + } + if ((flags & 4) != 0) { + max_id = stream.readInt32(exception); + } + if ((flags & 8) != 0) { + read_max_id = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = comments ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + stream.writeInt32(replies); + stream.writeInt32(replies_pts); + if ((flags & 2) != 0) { + stream.writeInt32(0x1cb5c415); + int count = recent_repliers.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + recent_repliers.get(a).serializeToStream(stream); + } + } + if ((flags & 1) != 0) { + stream.writeInt64(channel_id); } if ((flags & 4) != 0) { stream.writeInt32(max_id); @@ -9067,7 +9519,7 @@ public class TLRPC { public int flags; public int views; public int forwards; - public TL_messageReplies replies; + public MessageReplies replies; public static TL_messageViews TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_messageViews.constructor != constructor) { @@ -9091,7 +9543,7 @@ public class TLRPC { forwards = stream.readInt32(exception); } if ((flags & 4) != 0) { - replies = TL_messageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); + replies = MessageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); } } @@ -9335,7 +9787,7 @@ public class TLRPC { public int flags; public ArrayList documents = new ArrayList<>(); - public TL_themeSettings settings; + public ThemeSettings settings; public static TL_webPageAttributeTheme TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_webPageAttributeTheme.constructor != constructor) { @@ -9370,7 +9822,7 @@ public class TLRPC { } } if ((flags & 2) != 0) { - settings = TL_themeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); + settings = ThemeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); } } @@ -9965,7 +10417,7 @@ public class TLRPC { } public static abstract class ChatFull extends TLObject { - public int id; + public long id; public ChatParticipants participants; public Photo chat_photo; public PeerNotifySettings notify_settings; @@ -9981,7 +10433,7 @@ public class TLRPC { public int read_inbox_max_id; public int read_outbox_max_id; public int unread_count; - public int migrated_from_chat_id; + public long migrated_from_chat_id; public int migrated_from_max_id; public int pinned_msg_id; public int kicked_count; @@ -9997,7 +10449,7 @@ public class TLRPC { public StickerSet stickerset; public int available_min_id; public int call_msg_id; - public int linked_chat_id; + public long linked_chat_id; public ChannelLocation location; public int slowmode_seconds; public int slowmode_next_send_date; @@ -10008,7 +10460,7 @@ public class TLRPC { public ArrayList pending_suggestions = new ArrayList<>(); public Peer groupcall_default_join_as; public String theme_emoticon; - public int inviterId; //custom + public long inviterId; //custom public int invitesCount; //custom public static ChatFull TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -10075,9 +10527,15 @@ public class TLRPC { result = new TL_channelFull_layer131(); break; case 0x49a0a5d9: - result = new TL_chatFull(); + result = new TL_chatFull_layer132(); break; case 0x2f532f3c: + result = new TL_channelFull_layer132(); + break; + case 0x4dbdc099: + result = new TL_chatFull(); + break; + case 0xe9b27a17: result = new TL_channelFull(); break; case 0x1b7c9db3: @@ -10206,7 +10664,7 @@ public class TLRPC { flags = can_set_location ? (flags | 65536) : (flags &~ 65536); flags = has_scheduled ? (flags | 524288) : (flags &~ 524288); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -10236,7 +10694,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -10254,7 +10712,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -10323,7 +10781,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -10476,7 +10934,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); flags = blocked ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -10508,7 +10966,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -10526,7 +10984,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -10609,7 +11067,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -10743,7 +11201,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); flags = blocked ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -10775,7 +11233,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -10793,7 +11251,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -10871,7 +11329,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -10907,215 +11365,7 @@ public class TLRPC { } } - public static class TL_channelFull_layer131 extends TL_channelFull { - public static int constructor = 0x548c3f93; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - can_view_participants = (flags & 8) != 0; - can_set_username = (flags & 64) != 0; - can_set_stickers = (flags & 128) != 0; - hidden_prehistory = (flags & 1024) != 0; - can_set_location = (flags & 65536) != 0; - has_scheduled = (flags & 524288) != 0; - can_view_stats = (flags & 1048576) != 0; - blocked = (flags & 4194304) != 0; - id = stream.readInt32(exception); - about = stream.readString(exception); - if ((flags & 1) != 0) { - participants_count = stream.readInt32(exception); - } - if ((flags & 2) != 0) { - admins_count = stream.readInt32(exception); - } - if ((flags & 4) != 0) { - kicked_count = stream.readInt32(exception); - } - if ((flags & 4) != 0) { - banned_count = stream.readInt32(exception); - } - if ((flags & 8192) != 0) { - online_count = stream.readInt32(exception); - } - read_inbox_max_id = stream.readInt32(exception); - read_outbox_max_id = stream.readInt32(exception); - unread_count = stream.readInt32(exception); - chat_photo = Photo.TLdeserialize(stream, stream.readInt32(exception), exception); - notify_settings = PeerNotifySettings.TLdeserialize(stream, stream.readInt32(exception), exception); - if ((flags & 8388608) != 0) { - exported_invite = (TLRPC.TL_chatInviteExported) ExportedChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); - } - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - BotInfo object = BotInfo.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - bot_info.add(object); - } - if ((flags & 16) != 0) { - migrated_from_chat_id = stream.readInt32(exception); - } - if ((flags & 16) != 0) { - migrated_from_max_id = stream.readInt32(exception); - } - if ((flags & 32) != 0) { - pinned_msg_id = stream.readInt32(exception); - } - if ((flags & 256) != 0) { - stickerset = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); - } - if ((flags & 512) != 0) { - available_min_id = stream.readInt32(exception); - } - if ((flags & 2048) != 0) { - folder_id = stream.readInt32(exception); - } - if ((flags & 16384) != 0) { - linked_chat_id = stream.readInt32(exception); - } - if ((flags & 32768) != 0) { - location = ChannelLocation.TLdeserialize(stream, stream.readInt32(exception), exception); - } - if ((flags & 131072) != 0) { - slowmode_seconds = stream.readInt32(exception); - } - if ((flags & 262144) != 0) { - slowmode_next_send_date = stream.readInt32(exception); - } - if ((flags & 4096) != 0) { - stats_dc = stream.readInt32(exception); - } - pts = stream.readInt32(exception); - if ((flags & 2097152) != 0) { - call = TL_inputGroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); - } - if ((flags & 16777216) != 0) { - ttl_period = stream.readInt32(exception); - } - if ((flags & 33554432) != 0) { - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - pending_suggestions.add(stream.readString(exception)); - } - } - if ((flags & 67108864) != 0) { - groupcall_default_join_as = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = can_view_participants ? (flags | 8) : (flags &~ 8); - flags = can_set_username ? (flags | 64) : (flags &~ 64); - flags = can_set_stickers ? (flags | 128) : (flags &~ 128); - flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); - flags = can_set_location ? (flags | 65536) : (flags &~ 65536); - flags = has_scheduled ? (flags | 524288) : (flags &~ 524288); - flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); - flags = blocked ? (flags | 4194304) : (flags &~ 4194304); - stream.writeInt32(flags); - stream.writeInt32(id); - stream.writeString(about); - if ((flags & 1) != 0) { - stream.writeInt32(participants_count); - } - if ((flags & 2) != 0) { - stream.writeInt32(admins_count); - } - if ((flags & 4) != 0) { - stream.writeInt32(kicked_count); - } - if ((flags & 4) != 0) { - stream.writeInt32(banned_count); - } - if ((flags & 8192) != 0) { - stream.writeInt32(online_count); - } - stream.writeInt32(read_inbox_max_id); - stream.writeInt32(read_outbox_max_id); - stream.writeInt32(unread_count); - chat_photo.serializeToStream(stream); - notify_settings.serializeToStream(stream); - if ((flags & 8388608) != 0) { - exported_invite.serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - int count = bot_info.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - bot_info.get(a).serializeToStream(stream); - } - if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); - } - if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_max_id); - } - if ((flags & 32) != 0) { - stream.writeInt32(pinned_msg_id); - } - if ((flags & 256) != 0) { - stickerset.serializeToStream(stream); - } - if ((flags & 512) != 0) { - stream.writeInt32(available_min_id); - } - if ((flags & 2048) != 0) { - stream.writeInt32(folder_id); - } - if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); - } - if ((flags & 32768) != 0) { - location.serializeToStream(stream); - } - if ((flags & 131072) != 0) { - stream.writeInt32(slowmode_seconds); - } - if ((flags & 262144) != 0) { - stream.writeInt32(slowmode_next_send_date); - } - if ((flags & 4096) != 0) { - stream.writeInt32(stats_dc); - } - stream.writeInt32(pts); - if ((flags & 2097152) != 0) { - call.serializeToStream(stream); - } - if ((flags & 16777216) != 0) { - stream.writeInt32(ttl_period); - } - if ((flags & 33554432) != 0) { - stream.writeInt32(0x1cb5c415); - count = pending_suggestions.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeString(pending_suggestions.get(a)); - } - } - if ((flags & 67108864) != 0) { - groupcall_default_join_as.serializeToStream(stream); - } - } - } - - public static class TL_chatFull extends ChatFull { + public static class TL_chatFull_layer132 extends TL_chatFull { public static int constructor = 0x49a0a5d9; @@ -11175,7 +11425,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -11214,7 +11464,7 @@ public class TLRPC { } } - public static class TL_channelFull extends ChatFull { + public static class TL_channelFull_layer132 extends TL_channelFull { public static int constructor = 0x2f532f3c; @@ -11340,7 +11590,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); flags = blocked ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -11372,7 +11622,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -11390,7 +11640,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -11428,6 +11678,527 @@ public class TLRPC { } } + public static class TL_chatFull extends ChatFull { + public static int constructor = 0x4dbdc099; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + can_set_username = (flags & 128) != 0; + has_scheduled = (flags & 256) != 0; + id = stream.readInt64(exception); + about = stream.readString(exception); + participants = ChatParticipants.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 4) != 0) { + chat_photo = Photo.TLdeserialize(stream, stream.readInt32(exception), exception); + } + notify_settings = PeerNotifySettings.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 8192) != 0) { + exported_invite = (TLRPC.TL_chatInviteExported) ExportedChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 8) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + BotInfo object = BotInfo.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + bot_info.add(object); + } + } + if ((flags & 64) != 0) { + pinned_msg_id = stream.readInt32(exception); + } + if ((flags & 2048) != 0) { + folder_id = stream.readInt32(exception); + } + if ((flags & 4096) != 0) { + call = TL_inputGroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 16384) != 0) { + ttl_period = stream.readInt32(exception); + } + if ((flags & 32768) != 0) { + groupcall_default_join_as = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 65536) != 0) { + theme_emoticon = stream.readString(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = can_set_username ? (flags | 128) : (flags &~ 128); + flags = has_scheduled ? (flags | 256) : (flags &~ 256); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeString(about); + participants.serializeToStream(stream); + if ((flags & 4) != 0) { + chat_photo.serializeToStream(stream); + } + notify_settings.serializeToStream(stream); + if ((flags & 8192) != 0) { + exported_invite.serializeToStream(stream); + } + if ((flags & 8) != 0) { + stream.writeInt32(0x1cb5c415); + int count = bot_info.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + bot_info.get(a).serializeToStream(stream); + } + } + if ((flags & 64) != 0) { + stream.writeInt32(pinned_msg_id); + } + if ((flags & 2048) != 0) { + stream.writeInt32(folder_id); + } + if ((flags & 4096) != 0) { + call.serializeToStream(stream); + } + if ((flags & 16384) != 0) { + stream.writeInt32(ttl_period); + } + if ((flags & 32768) != 0) { + groupcall_default_join_as.serializeToStream(stream); + } + if ((flags & 65536) != 0) { + stream.writeString(theme_emoticon); + } + } + } + + public static class TL_channelFull extends ChatFull { + public static int constructor = 0xe9b27a17; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + can_view_participants = (flags & 8) != 0; + can_set_username = (flags & 64) != 0; + can_set_stickers = (flags & 128) != 0; + hidden_prehistory = (flags & 1024) != 0; + can_set_location = (flags & 65536) != 0; + has_scheduled = (flags & 524288) != 0; + can_view_stats = (flags & 1048576) != 0; + blocked = (flags & 4194304) != 0; + id = stream.readInt64(exception); + about = stream.readString(exception); + if ((flags & 1) != 0) { + participants_count = stream.readInt32(exception); + } + if ((flags & 2) != 0) { + admins_count = stream.readInt32(exception); + } + if ((flags & 4) != 0) { + kicked_count = stream.readInt32(exception); + } + if ((flags & 4) != 0) { + banned_count = stream.readInt32(exception); + } + if ((flags & 8192) != 0) { + online_count = stream.readInt32(exception); + } + read_inbox_max_id = stream.readInt32(exception); + read_outbox_max_id = stream.readInt32(exception); + unread_count = stream.readInt32(exception); + chat_photo = Photo.TLdeserialize(stream, stream.readInt32(exception), exception); + notify_settings = PeerNotifySettings.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 8388608) != 0) { + exported_invite = (TLRPC.TL_chatInviteExported) ExportedChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); + } + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + BotInfo object = BotInfo.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + bot_info.add(object); + } + if ((flags & 16) != 0) { + migrated_from_chat_id = stream.readInt64(exception); + } + if ((flags & 16) != 0) { + migrated_from_max_id = stream.readInt32(exception); + } + if ((flags & 32) != 0) { + pinned_msg_id = stream.readInt32(exception); + } + if ((flags & 256) != 0) { + stickerset = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 512) != 0) { + available_min_id = stream.readInt32(exception); + } + if ((flags & 2048) != 0) { + folder_id = stream.readInt32(exception); + } + if ((flags & 16384) != 0) { + linked_chat_id = stream.readInt64(exception); + } + if ((flags & 32768) != 0) { + location = ChannelLocation.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 131072) != 0) { + slowmode_seconds = stream.readInt32(exception); + } + if ((flags & 262144) != 0) { + slowmode_next_send_date = stream.readInt32(exception); + } + if ((flags & 4096) != 0) { + stats_dc = stream.readInt32(exception); + } + pts = stream.readInt32(exception); + if ((flags & 2097152) != 0) { + call = TL_inputGroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 16777216) != 0) { + ttl_period = stream.readInt32(exception); + } + if ((flags & 33554432) != 0) { + magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + pending_suggestions.add(stream.readString(exception)); + } + } + if ((flags & 67108864) != 0) { + groupcall_default_join_as = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 134217728) != 0) { + theme_emoticon = stream.readString(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = can_view_participants ? (flags | 8) : (flags &~ 8); + flags = can_set_username ? (flags | 64) : (flags &~ 64); + flags = can_set_stickers ? (flags | 128) : (flags &~ 128); + flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); + flags = can_set_location ? (flags | 65536) : (flags &~ 65536); + flags = has_scheduled ? (flags | 524288) : (flags &~ 524288); + flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); + flags = blocked ? (flags | 4194304) : (flags &~ 4194304); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeString(about); + if ((flags & 1) != 0) { + stream.writeInt32(participants_count); + } + if ((flags & 2) != 0) { + stream.writeInt32(admins_count); + } + if ((flags & 4) != 0) { + stream.writeInt32(kicked_count); + } + if ((flags & 4) != 0) { + stream.writeInt32(banned_count); + } + if ((flags & 8192) != 0) { + stream.writeInt32(online_count); + } + stream.writeInt32(read_inbox_max_id); + stream.writeInt32(read_outbox_max_id); + stream.writeInt32(unread_count); + chat_photo.serializeToStream(stream); + notify_settings.serializeToStream(stream); + if ((flags & 8388608) != 0) { + exported_invite.serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + int count = bot_info.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + bot_info.get(a).serializeToStream(stream); + } + if ((flags & 16) != 0) { + stream.writeInt64(migrated_from_chat_id); + } + if ((flags & 16) != 0) { + stream.writeInt32(migrated_from_max_id); + } + if ((flags & 32) != 0) { + stream.writeInt32(pinned_msg_id); + } + if ((flags & 256) != 0) { + stickerset.serializeToStream(stream); + } + if ((flags & 512) != 0) { + stream.writeInt32(available_min_id); + } + if ((flags & 2048) != 0) { + stream.writeInt32(folder_id); + } + if ((flags & 16384) != 0) { + stream.writeInt64(linked_chat_id); + } + if ((flags & 32768) != 0) { + location.serializeToStream(stream); + } + if ((flags & 131072) != 0) { + stream.writeInt32(slowmode_seconds); + } + if ((flags & 262144) != 0) { + stream.writeInt32(slowmode_next_send_date); + } + if ((flags & 4096) != 0) { + stream.writeInt32(stats_dc); + } + stream.writeInt32(pts); + if ((flags & 2097152) != 0) { + call.serializeToStream(stream); + } + if ((flags & 16777216) != 0) { + stream.writeInt32(ttl_period); + } + if ((flags & 33554432) != 0) { + stream.writeInt32(0x1cb5c415); + count = pending_suggestions.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeString(pending_suggestions.get(a)); + } + } + if ((flags & 67108864) != 0) { + groupcall_default_join_as.serializeToStream(stream); + } + if ((flags & 134217728) != 0) { + stream.writeString(theme_emoticon); + } + } + } + + public static class TL_channelFull_layer131 extends TL_channelFull { + public static int constructor = 0x548c3f93; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + can_view_participants = (flags & 8) != 0; + can_set_username = (flags & 64) != 0; + can_set_stickers = (flags & 128) != 0; + hidden_prehistory = (flags & 1024) != 0; + can_set_location = (flags & 65536) != 0; + has_scheduled = (flags & 524288) != 0; + can_view_stats = (flags & 1048576) != 0; + blocked = (flags & 4194304) != 0; + id = stream.readInt64(exception); + about = stream.readString(exception); + if ((flags & 1) != 0) { + participants_count = stream.readInt32(exception); + } + if ((flags & 2) != 0) { + admins_count = stream.readInt32(exception); + } + if ((flags & 4) != 0) { + kicked_count = stream.readInt32(exception); + } + if ((flags & 4) != 0) { + banned_count = stream.readInt32(exception); + } + if ((flags & 8192) != 0) { + online_count = stream.readInt32(exception); + } + read_inbox_max_id = stream.readInt32(exception); + read_outbox_max_id = stream.readInt32(exception); + unread_count = stream.readInt32(exception); + chat_photo = Photo.TLdeserialize(stream, stream.readInt32(exception), exception); + notify_settings = PeerNotifySettings.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 8388608) != 0) { + exported_invite = (TL_chatInviteExported) ExportedChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); + } + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + BotInfo object = BotInfo.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + bot_info.add(object); + } + if ((flags & 16) != 0) { + migrated_from_chat_id = stream.readInt64(exception); + } + if ((flags & 16) != 0) { + migrated_from_max_id = stream.readInt32(exception); + } + if ((flags & 32) != 0) { + pinned_msg_id = stream.readInt32(exception); + } + if ((flags & 256) != 0) { + stickerset = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 512) != 0) { + available_min_id = stream.readInt32(exception); + } + if ((flags & 2048) != 0) { + folder_id = stream.readInt32(exception); + } + if ((flags & 16384) != 0) { + linked_chat_id = stream.readInt64(exception); + } + if ((flags & 32768) != 0) { + location = ChannelLocation.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 131072) != 0) { + slowmode_seconds = stream.readInt32(exception); + } + if ((flags & 262144) != 0) { + slowmode_next_send_date = stream.readInt32(exception); + } + if ((flags & 4096) != 0) { + stats_dc = stream.readInt32(exception); + } + pts = stream.readInt32(exception); + if ((flags & 2097152) != 0) { + call = TL_inputGroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 16777216) != 0) { + ttl_period = stream.readInt32(exception); + } + if ((flags & 33554432) != 0) { + magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + pending_suggestions.add(stream.readString(exception)); + } + } + if ((flags & 67108864) != 0) { + groupcall_default_join_as = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = can_view_participants ? (flags | 8) : (flags &~ 8); + flags = can_set_username ? (flags | 64) : (flags &~ 64); + flags = can_set_stickers ? (flags | 128) : (flags &~ 128); + flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); + flags = can_set_location ? (flags | 65536) : (flags &~ 65536); + flags = has_scheduled ? (flags | 524288) : (flags &~ 524288); + flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); + flags = blocked ? (flags | 4194304) : (flags &~ 4194304); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeString(about); + if ((flags & 1) != 0) { + stream.writeInt32(participants_count); + } + if ((flags & 2) != 0) { + stream.writeInt32(admins_count); + } + if ((flags & 4) != 0) { + stream.writeInt32(kicked_count); + } + if ((flags & 4) != 0) { + stream.writeInt32(banned_count); + } + if ((flags & 8192) != 0) { + stream.writeInt32(online_count); + } + stream.writeInt32(read_inbox_max_id); + stream.writeInt32(read_outbox_max_id); + stream.writeInt32(unread_count); + chat_photo.serializeToStream(stream); + notify_settings.serializeToStream(stream); + if ((flags & 8388608) != 0) { + exported_invite.serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + int count = bot_info.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + bot_info.get(a).serializeToStream(stream); + } + if ((flags & 16) != 0) { + stream.writeInt64(migrated_from_chat_id); + } + if ((flags & 16) != 0) { + stream.writeInt32(migrated_from_max_id); + } + if ((flags & 32) != 0) { + stream.writeInt32(pinned_msg_id); + } + if ((flags & 256) != 0) { + stickerset.serializeToStream(stream); + } + if ((flags & 512) != 0) { + stream.writeInt32(available_min_id); + } + if ((flags & 2048) != 0) { + stream.writeInt32(folder_id); + } + if ((flags & 16384) != 0) { + stream.writeInt64(linked_chat_id); + } + if ((flags & 32768) != 0) { + location.serializeToStream(stream); + } + if ((flags & 131072) != 0) { + stream.writeInt32(slowmode_seconds); + } + if ((flags & 262144) != 0) { + stream.writeInt32(slowmode_next_send_date); + } + if ((flags & 4096) != 0) { + stream.writeInt32(stats_dc); + } + stream.writeInt32(pts); + if ((flags & 2097152) != 0) { + call.serializeToStream(stream); + } + if ((flags & 16777216) != 0) { + stream.writeInt32(ttl_period); + } + if ((flags & 33554432) != 0) { + stream.writeInt32(0x1cb5c415); + count = pending_suggestions.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeString(pending_suggestions.get(a)); + } + } + if ((flags & 67108864) != 0) { + groupcall_default_join_as.serializeToStream(stream); + } + } + } + public static class TL_channelFull_layer122 extends TL_channelFull { public static int constructor = 0xef3a6acd; @@ -11533,7 +12304,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); flags = blocked ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -11567,7 +12338,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -11585,7 +12356,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -11708,7 +12479,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 1048576) : (flags &~ 1048576); flags = blocked ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -11738,7 +12509,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -11756,7 +12527,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -11863,7 +12634,7 @@ public class TLRPC { flags = can_view_stats ? (flags | 4096) : (flags &~ 4096); flags = can_set_location ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -11893,7 +12664,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -11911,7 +12682,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 16384) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } if ((flags & 32768) != 0) { location.serializeToStream(stream); @@ -12004,7 +12775,7 @@ public class TLRPC { flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); flags = can_view_stats ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12034,7 +12805,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12052,7 +12823,7 @@ public class TLRPC { stream.writeInt32(folder_id); } if ((flags & 8192) != 0) { - stream.writeInt32(linked_chat_id); + stream.writeInt32((int) linked_chat_id); } stream.writeInt32(pts); } @@ -12139,7 +12910,7 @@ public class TLRPC { flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); flags = can_view_stats ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12169,7 +12940,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12267,7 +13038,7 @@ public class TLRPC { flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); flags = can_view_stats ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12297,7 +13068,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12346,7 +13117,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); participants.serializeToStream(stream); chat_photo.serializeToStream(stream); notify_settings.serializeToStream(stream); @@ -12435,7 +13206,7 @@ public class TLRPC { flags = can_set_stickers ? (flags | 128) : (flags &~ 128); flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12462,7 +13233,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12554,7 +13325,7 @@ public class TLRPC { flags = can_set_stickers ? (flags | 128) : (flags &~ 128); flags = hidden_prehistory ? (flags | 1024) : (flags &~ 1024); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12581,7 +13352,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12665,7 +13436,7 @@ public class TLRPC { flags = can_set_username ? (flags | 64) : (flags &~ 64); flags = can_set_stickers ? (flags | 128) : (flags &~ 128); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -12692,7 +13463,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -12758,7 +13529,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -12835,7 +13606,7 @@ public class TLRPC { flags = can_set_username ? (flags | 128) : (flags &~ 128); flags = has_scheduled ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -12904,7 +13675,7 @@ public class TLRPC { stream.writeInt32(constructor); flags = can_set_username ? (flags | 128) : (flags &~ 128); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); participants.serializeToStream(stream); if ((flags & 4) != 0) { @@ -12967,7 +13738,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); participants.serializeToStream(stream); if ((flags & 4) != 0) { chat_photo.serializeToStream(stream); @@ -13050,7 +13821,7 @@ public class TLRPC { flags = can_view_participants ? (flags | 8) : (flags &~ 8); flags = can_set_username ? (flags | 64) : (flags &~ 64); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -13077,7 +13848,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -13147,7 +13918,7 @@ public class TLRPC { flags = can_view_participants ? (flags | 8) : (flags &~ 8); flags = can_set_username ? (flags | 64) : (flags &~ 64); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -13171,7 +13942,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -13241,7 +14012,7 @@ public class TLRPC { flags = can_view_participants ? (flags | 8) : (flags &~ 8); flags = can_set_username ? (flags | 64) : (flags &~ 64); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -13265,7 +14036,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -13330,7 +14101,7 @@ public class TLRPC { stream.writeInt32(constructor); flags = can_view_participants ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -13354,7 +14125,7 @@ public class TLRPC { bot_info.get(a).serializeToStream(stream); } if ((flags & 16) != 0) { - stream.writeInt32(migrated_from_chat_id); + stream.writeInt32((int) migrated_from_chat_id); } if ((flags & 16) != 0) { stream.writeInt32(migrated_from_max_id); @@ -13395,7 +14166,7 @@ public class TLRPC { stream.writeInt32(constructor); flags = can_view_participants ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(about); if ((flags & 1) != 0) { stream.writeInt32(participants_count); @@ -14283,7 +15054,7 @@ public class TLRPC { public static abstract class InputUser extends TLObject { - public int user_id; + public long user_id; public long access_hash; public static InputUser TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -14292,13 +15063,13 @@ public class TLRPC { case 0xf7c1b13f: result = new TL_inputUserSelf(); break; - case 0xd8292816: + case 0xf21158c6: result = new TL_inputUser(); break; case 0xb98886cf: result = new TL_inputUserEmpty(); break; - case 0x2d117597: + case 0x1da448e2: result = new TL_inputUserFromMessage(); break; } @@ -14322,17 +15093,17 @@ public class TLRPC { } public static class TL_inputUser extends InputUser { - public static int constructor = 0xd8292816; + public static int constructor = 0xf21158c6; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); access_hash = stream.readInt64(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt64(access_hash); } } @@ -14347,7 +15118,7 @@ public class TLRPC { } public static class TL_inputUserFromMessage extends InputUser { - public static int constructor = 0x2d117597; + public static int constructor = 0x1da448e2; public InputPeer peer; public int msg_id; @@ -14355,14 +15126,14 @@ public class TLRPC { public void readParams(AbstractSerializedData stream, boolean exception) { peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); msg_id = stream.readInt32(exception); - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(msg_id); - stream.writeInt32(user_id); + stream.writeInt64(user_id); } } @@ -15483,36 +16254,36 @@ public class TLRPC { } } - public static class TL_auth_exportedAuthorization extends TLObject { - public static int constructor = 0xdf969c2d; + public static class TL_auth_exportedAuthorization extends TLObject { + public static int constructor = 0xb434e2b8; - public int id; - public byte[] bytes; + public long id; + public byte[] bytes; - public static TL_auth_exportedAuthorization TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_auth_exportedAuthorization.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_auth_exportedAuthorization", constructor)); - } else { - return null; + public static TL_auth_exportedAuthorization TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_auth_exportedAuthorization.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_auth_exportedAuthorization", constructor)); + } else { + return null; } } TL_auth_exportedAuthorization result = new TL_auth_exportedAuthorization(); - result.readParams(stream, exception); - return result; - } + result.readParams(stream, exception); + return result; + } - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt32(exception); - bytes = stream.readByteArray(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt64(exception); + bytes = stream.readByteArray(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(id); - stream.writeByteArray(bytes); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(id); + stream.writeByteArray(bytes); + } + } public static abstract class WebPage extends TLObject { public int flags; @@ -16185,7 +16956,7 @@ public class TLRPC { public static messages_FeaturedStickers TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { messages_FeaturedStickers result = null; switch (constructor) { - case 0xb6abc341: + case 0x84c02310: result = new TL_messages_featuredStickers(); break; case 0xc6dc0c66: @@ -16203,15 +16974,15 @@ public class TLRPC { } public static class TL_messages_featuredStickers extends messages_FeaturedStickers { - public static int constructor = 0xb6abc341; + public static int constructor = 0x84c02310; - public int hash; + public long hash; public int count; public ArrayList sets = new ArrayList<>(); public ArrayList unread = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); + hash = stream.readInt64(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { @@ -16243,7 +17014,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(hash); + stream.writeInt64(hash); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = sets.size(); @@ -16831,7 +17602,7 @@ public class TLRPC { flags = exclude_read ? (flags | 4096) : (flags &~ 4096); flags = exclude_archived ? (flags | 8192) : (flags &~ 8192); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); if ((flags & 33554432) != 0) { stream.writeString(emoticon); @@ -17552,8 +18323,8 @@ public class TLRPC { public long id; public long access_hash; public int date; - public int admin_id; - public int participant_id; + public long admin_id; + public long participant_id; public byte[] g_a_or_b; public long key_fingerprint; public PhoneCallProtocol protocol; @@ -17571,19 +18342,19 @@ public class TLRPC { public static PhoneCall TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { PhoneCall result = null; switch (constructor) { - case 0x87eabb53: + case 0x14b0ed0c: result = new TL_phoneCallRequested(); break; - case 0x8742ae7f: + case 0x967f7c67: result = new TL_phoneCall(); break; case 0x5366c915: result = new TL_phoneCallEmpty(); break; - case 0x997c454a: + case 0x3660c311: result = new TL_phoneCallAccepted(); break; - case 0x1b8f4ad1: + case 0xc5226f17: result = new TL_phoneCallWaiting(); break; case 0x50ca4de1: @@ -17601,7 +18372,7 @@ public class TLRPC { } public static class TL_phoneCallRequested extends PhoneCall { - public static int constructor = 0x87eabb53; + public static int constructor = 0x14b0ed0c; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -17610,8 +18381,8 @@ public class TLRPC { id = stream.readInt64(exception); access_hash = stream.readInt64(exception); date = stream.readInt32(exception); - admin_id = stream.readInt32(exception); - participant_id = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); g_a_hash = stream.readByteArray(exception); protocol = PhoneCallProtocol.TLdeserialize(stream, stream.readInt32(exception), exception); } @@ -17623,15 +18394,15 @@ public class TLRPC { stream.writeInt64(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); stream.writeByteArray(g_a_hash); protocol.serializeToStream(stream); } } public static class TL_phoneCall extends PhoneCall { - public static int constructor = 0x8742ae7f; + public static int constructor = 0x967f7c67; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -17641,8 +18412,8 @@ public class TLRPC { id = stream.readInt64(exception); access_hash = stream.readInt64(exception); date = stream.readInt32(exception); - admin_id = stream.readInt32(exception); - participant_id = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); g_a_or_b = stream.readByteArray(exception); key_fingerprint = stream.readInt64(exception); protocol = PhoneCallProtocol.TLdeserialize(stream, stream.readInt32(exception), exception); @@ -17672,8 +18443,8 @@ public class TLRPC { stream.writeInt64(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); stream.writeByteArray(g_a_or_b); stream.writeInt64(key_fingerprint); protocol.serializeToStream(stream); @@ -17702,7 +18473,7 @@ public class TLRPC { } public static class TL_phoneCallAccepted extends PhoneCall { - public static int constructor = 0x997c454a; + public static int constructor = 0x3660c311; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -17711,8 +18482,8 @@ public class TLRPC { id = stream.readInt64(exception); access_hash = stream.readInt64(exception); date = stream.readInt32(exception); - admin_id = stream.readInt32(exception); - participant_id = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); g_b = stream.readByteArray(exception); protocol = PhoneCallProtocol.TLdeserialize(stream, stream.readInt32(exception), exception); } @@ -17724,15 +18495,15 @@ public class TLRPC { stream.writeInt64(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); stream.writeByteArray(g_b); protocol.serializeToStream(stream); } } public static class TL_phoneCallWaiting extends PhoneCall { - public static int constructor = 0x1b8f4ad1; + public static int constructor = 0xc5226f17; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -17741,8 +18512,8 @@ public class TLRPC { id = stream.readInt64(exception); access_hash = stream.readInt64(exception); date = stream.readInt32(exception); - admin_id = stream.readInt32(exception); - participant_id = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); protocol = PhoneCallProtocol.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 1) != 0) { receive_date = stream.readInt32(exception); @@ -17756,8 +18527,8 @@ public class TLRPC { stream.writeInt64(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); protocol.serializeToStream(stream); if ((flags & 1) != 0) { stream.writeInt32(receive_date); @@ -17868,7 +18639,7 @@ public class TLRPC { } public static abstract class User extends TLObject { - public int id; + public long id; public String first_name; public String last_name; public String username; @@ -17908,8 +18679,14 @@ public class TLRPC { case 0xf2fb8319: result = new TL_userContact_old(); break; - case 0x938458c1: + case 0xd3bc4b7a: + result = new TL_userEmpty(); + break; + case 0x3ff6ecb0: result = new TL_user(); + break; + case 0x938458c1: + result = new TL_user_layer131(); break; case 0x2e13f4c3: result = new TL_user_layer104(); @@ -17924,7 +18701,7 @@ public class TLRPC { result = new TL_userDeleted_old2(); break; case 0x200250ba: - result = new TL_userEmpty(); + result = new TL_userEmpty_layer131(); break; case 0x22e8ceb0: result = new TL_userRequest_old(); @@ -17978,7 +18755,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); @@ -18005,7 +18782,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeInt64(access_hash); @@ -18015,7 +18792,152 @@ public class TLRPC { } } + public static class TL_userEmpty extends User { + public static int constructor = 0xd3bc4b7a; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(id); + } + } + public static class TL_user extends User { + public static int constructor = 0x3ff6ecb0; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + self = (flags & 1024) != 0; + contact = (flags & 2048) != 0; + mutual_contact = (flags & 4096) != 0; + deleted = (flags & 8192) != 0; + bot = (flags & 16384) != 0; + bot_chat_history = (flags & 32768) != 0; + bot_nochats = (flags & 65536) != 0; + verified = (flags & 131072) != 0; + restricted = (flags & 262144) != 0; + min = (flags & 1048576) != 0; + bot_inline_geo = (flags & 2097152) != 0; + support = (flags & 8388608) != 0; + scam = (flags & 16777216) != 0; + apply_min_photo = (flags & 33554432) != 0; + fake = (flags & 67108864) != 0; + id = stream.readInt64(exception); + if ((flags & 1) != 0) { + access_hash = stream.readInt64(exception); + } + if ((flags & 2) != 0) { + first_name = stream.readString(exception); + } + if ((flags & 4) != 0) { + last_name = stream.readString(exception); + } + if ((flags & 8) != 0) { + username = stream.readString(exception); + } + if ((flags & 16) != 0) { + phone = stream.readString(exception); + } + if ((flags & 32) != 0) { + photo = UserProfilePhoto.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 64) != 0) { + status = UserStatus.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 16384) != 0) { + bot_info_version = stream.readInt32(exception); + } + if ((flags & 262144) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_restrictionReason object = TL_restrictionReason.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + restriction_reason.add(object); + } + } + if ((flags & 524288) != 0) { + bot_inline_placeholder = stream.readString(exception); + } + if ((flags & 4194304) != 0) { + lang_code = stream.readString(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = self ? (flags | 1024) : (flags &~ 1024); + flags = contact ? (flags | 2048) : (flags &~ 2048); + flags = mutual_contact ? (flags | 4096) : (flags &~ 4096); + flags = deleted ? (flags | 8192) : (flags &~ 8192); + flags = bot ? (flags | 16384) : (flags &~ 16384); + flags = bot_chat_history ? (flags | 32768) : (flags &~ 32768); + flags = bot_nochats ? (flags | 65536) : (flags &~ 65536); + flags = verified ? (flags | 131072) : (flags &~ 131072); + flags = restricted ? (flags | 262144) : (flags &~ 262144); + flags = min ? (flags | 1048576) : (flags &~ 1048576); + flags = bot_inline_geo ? (flags | 2097152) : (flags &~ 2097152); + flags = support ? (flags | 8388608) : (flags &~ 8388608); + flags = scam ? (flags | 16777216) : (flags &~ 16777216); + flags = apply_min_photo ? (flags | 33554432) : (flags &~ 33554432); + flags = fake ? (flags | 67108864) : (flags &~ 67108864); + stream.writeInt32(flags); + stream.writeInt64(id); + if ((flags & 1) != 0) { + stream.writeInt64(access_hash); + } + if ((flags & 2) != 0) { + stream.writeString(first_name); + } + if ((flags & 4) != 0) { + stream.writeString(last_name); + } + if ((flags & 8) != 0) { + stream.writeString(username); + } + if ((flags & 16) != 0) { + stream.writeString(phone); + } + if ((flags & 32) != 0) { + photo.serializeToStream(stream); + } + if ((flags & 64) != 0) { + status.serializeToStream(stream); + } + if ((flags & 16384) != 0) { + stream.writeInt32(bot_info_version); + } + if ((flags & 262144) != 0) { + stream.writeInt32(0x1cb5c415); + int count = restriction_reason.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + restriction_reason.get(a).serializeToStream(stream); + } + } + if ((flags & 524288) != 0) { + stream.writeString(bot_inline_placeholder); + } + if ((flags & 4194304) != 0) { + stream.writeString(lang_code); + } + } + } + + public static class TL_user_layer131 extends TL_user { public static int constructor = 0x938458c1; @@ -18104,7 +19026,7 @@ public class TLRPC { flags = apply_min_photo ? (flags | 33554432) : (flags &~ 33554432); flags = fake ? (flags | 67108864) : (flags &~ 67108864); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 1) != 0) { stream.writeInt64(access_hash); } @@ -18217,7 +19139,7 @@ public class TLRPC { flags = support ? (flags | 8388608) : (flags &~ 8388608); flags = scam ? (flags | 16777216) : (flags &~ 16777216); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 1) != 0) { stream.writeInt64(access_hash); } @@ -18270,7 +19192,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(phone); @@ -18296,7 +19218,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); @@ -18319,14 +19241,14 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); } } - public static class TL_userEmpty extends User { + public static class TL_userEmpty_layer131 extends TL_userEmpty { public static int constructor = 0x200250ba; @@ -18336,7 +19258,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); } } @@ -18356,7 +19278,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeInt64(access_hash); @@ -18381,7 +19303,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeInt64(access_hash); @@ -18406,7 +19328,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); @@ -18433,7 +19355,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); @@ -18456,7 +19378,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); } @@ -18526,7 +19448,7 @@ public class TLRPC { flags = min ? (flags | 1048576) : (flags &~ 1048576); flags = bot_inline_geo ? (flags | 2097152) : (flags &~ 2097152); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 1) != 0) { stream.writeInt64(access_hash); } @@ -18614,7 +19536,7 @@ public class TLRPC { flags = verified ? (flags | 131072) : (flags &~ 131072); flags = explicit_content ? (flags | 262144) : (flags &~ 262144); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 1) != 0) { stream.writeInt64(access_hash); } @@ -18659,7 +19581,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(first_name); stream.writeString(last_name); stream.writeString(username); @@ -18670,124 +19592,125 @@ public class TLRPC { } } - public static abstract class RecentMeUrl extends TLObject { - public String url; - public int chat_id; - public StickerSetCovered set; - public ChatInvite chat_invite; - public int user_id; + public static abstract class RecentMeUrl extends TLObject { - public static RecentMeUrl TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - RecentMeUrl result = null; - switch (constructor) { - case 0xa01b22f9: - result = new TL_recentMeUrlChat(); - break; - case 0xbc0a57dc: - result = new TL_recentMeUrlStickerSet(); - break; - case 0x46e1d13d: - result = new TL_recentMeUrlUnknown(); - break; - case 0xeb49081d: - result = new TL_recentMeUrlChatInvite(); - break; - case 0x8dbc3336: - result = new TL_recentMeUrlUser(); - break; - } - if (result == null && exception) { - throw new RuntimeException(String.format("can't parse magic %x in RecentMeUrl", constructor)); - } - if (result != null) { - result.readParams(stream, exception); - } - return result; - } - } + public long chat_id; + public String url; + public ChatInvite chat_invite; + public long user_id; + public StickerSetCovered set; - public static class TL_recentMeUrlChat extends RecentMeUrl { - public static int constructor = 0xa01b22f9; + public static RecentMeUrl TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + RecentMeUrl result = null; + switch (constructor) { + case 0xb2da71d2: + result = new TL_recentMeUrlChat(); + break; + case 0xbc0a57dc: + result = new TL_recentMeUrlStickerSet(); + break; + case 0x46e1d13d: + result = new TL_recentMeUrlUnknown(); + break; + case 0xeb49081d: + result = new TL_recentMeUrlChatInvite(); + break; + case 0xb92c09e2: + result = new TL_recentMeUrlUser(); + break; + } + if (result == null && exception) { + throw new RuntimeException(String.format("can't parse magic %x in RecentMeUrl", constructor)); + } + if (result != null) { + result.readParams(stream, exception); + } + return result; + } + } + + public static class TL_recentMeUrlChat extends RecentMeUrl { + public static int constructor = 0xb2da71d2; - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - chat_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + url = stream.readString(exception); + chat_id = stream.readInt64(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - stream.writeInt32(chat_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(url); + stream.writeInt64(chat_id); + } + } - public static class TL_recentMeUrlStickerSet extends RecentMeUrl { - public static int constructor = 0xbc0a57dc; + public static class TL_recentMeUrlStickerSet extends RecentMeUrl { + public static int constructor = 0xbc0a57dc; - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - set = StickerSetCovered.TLdeserialize(stream, stream.readInt32(exception), exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + url = stream.readString(exception); + set = StickerSetCovered.TLdeserialize(stream, stream.readInt32(exception), exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - set.serializeToStream(stream); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(url); + set.serializeToStream(stream); + } + } - public static class TL_recentMeUrlUnknown extends RecentMeUrl { - public static int constructor = 0x46e1d13d; + public static class TL_recentMeUrlUnknown extends RecentMeUrl { + public static int constructor = 0x46e1d13d; - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + url = stream.readString(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(url); + } + } - public static class TL_recentMeUrlChatInvite extends RecentMeUrl { - public static int constructor = 0xeb49081d; + public static class TL_recentMeUrlChatInvite extends RecentMeUrl { + public static int constructor = 0xeb49081d; - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - chat_invite = ChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + url = stream.readString(exception); + chat_invite = ChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - chat_invite.serializeToStream(stream); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(url); + chat_invite.serializeToStream(stream); + } + } - public static class TL_recentMeUrlUser extends RecentMeUrl { - public static int constructor = 0x8dbc3336; + public static class TL_recentMeUrlUser extends RecentMeUrl { + public static int constructor = 0xb92c09e2; - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - user_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + url = stream.readString(exception); + user_id = stream.readInt64(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - stream.writeInt32(user_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(url); + stream.writeInt64(user_id); + } + } public static class TL_statsGroupTopPoster extends TLObject { - public static int constructor = 0x18f3d0f7; + public static int constructor = 0x9d04af9b; - public int user_id; + public long user_id; public int messages; public int avg_chars; @@ -18805,14 +19728,14 @@ public class TLRPC { } public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); messages = stream.readInt32(exception); avg_chars = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(messages); stream.writeInt32(avg_chars); } @@ -19176,14 +20099,14 @@ public class TLRPC { public String address; public DecryptedMessageAction encryptedAction; public String message; - public ArrayList users = new ArrayList<>(); + public ArrayList users = new ArrayList<>(); public TL_inputGroupCall call; - public int channel_id; + public long channel_id; public Photo photo; - public int chat_id; - public int user_id; + public long chat_id; + public long user_id; public UserProfilePhoto newUserPhoto; - public int inviter_id; + public long inviter_id; public int ttl; public int flags; public long call_id; @@ -19208,11 +20131,29 @@ public class TLRPC { result = new TL_messageActionCustomAction(); break; case 0xa6638b9a: - result = new TL_messageActionChatCreate(); + result = new TL_messageActionChatCreate_layer131(); break; + case 0xbd47cbad: + result = new TL_messageActionChatCreate(); + break; + case 0x502f92f7: + result = new TL_messageActionInviteToGroupCall(); + break; + case 0x15cefd00: + result = new TL_messageActionChatAddUser(); + break; + case 0xa43f30cc: + result = new TL_messageActionChatDeleteUser(); + break; case 0x51bdb021: - result = new TL_messageActionChatMigrateTo(); + result = new TL_messageActionChatMigrateTo_layer131(); break; + case 0xe1037f92: + result = new TL_messageActionChatMigrateTo(); + break; + case 0xea3948e9: + result = new TL_messageActionChannelMigrateFrom(); + break; case 0x7a0d7f42: result = new TL_messageActionGroupCall(); break; @@ -19228,14 +20169,17 @@ public class TLRPC { case 0x7fcb13a8: result = new TL_messageActionChatEditPhoto(); break; + case 0x31224c3: + result = new TL_messageActionChatJoinedByLink(); + break; case 0xb055eaee: - result = new TL_messageActionChannelMigrateFrom(); + result = new TL_messageActionChannelMigrateFrom_layer131(); break; case 0x488a7337: - result = new TL_messageActionChatAddUser(); + result = new TL_messageActionChatAddUser_layer131(); break; case 0xb2ae9b0c: - result = new TL_messageActionChatDeleteUser(); + result = new TL_messageActionChatDeleteUser_layer131(); break; case 0x55555557: result = new TL_messageActionCreatedBroadcastList(); @@ -19259,7 +20203,7 @@ public class TLRPC { result = new TL_messageActionSecureValuesSent(); break; case 0xf89cf5e8: - result = new TL_messageActionChatJoinedByLink(); + result = new TL_messageActionChatJoinedByLink_layer131(); break; case 0xf3f25f76: result = new TL_messageActionContactSignUp(); @@ -19277,7 +20221,7 @@ public class TLRPC { result = new TL_messageActionChatDeletePhoto(); break; case 0x76b9f11a: - result = new TL_messageActionInviteToGroupCall(); + result = new TL_messageActionInviteToGroupCall_layer131(); break; case 0x80e11a7f: result = new TL_messageActionPhoneCall(); @@ -19355,7 +20299,38 @@ public class TLRPC { } } - public static class TL_messageActionChatCreate extends MessageAction { + public static class TL_messageActionChatCreate extends MessageAction { + public static int constructor = 0xbd47cbad; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + title = stream.readString(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + users.add(stream.readInt64(exception)); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(title); + stream.writeInt32(0x1cb5c415); + int count = users.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(users.get(a)); + } + } + } + + public static class TL_messageActionChatCreate_layer131 extends TL_messageActionChatCreate { public static int constructor = 0xa6638b9a; @@ -19370,7 +20345,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - users.add(stream.readInt32(exception)); + users.add((long) stream.readInt32(exception)); } } @@ -19381,11 +20356,58 @@ public class TLRPC { int count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(users.get(a)); + stream.writeInt32((int) (long) users.get(a)); } } } + public static class TL_messageActionInviteToGroupCall extends MessageAction { + public static int constructor = 0x502f92f7; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + call = TL_inputGroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + users.add(stream.readInt64(exception)); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + call.serializeToStream(stream); + stream.writeInt32(0x1cb5c415); + int count = users.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(users.get(a)); + } + } + } + + public static class TL_messageActionChannelMigrateFrom extends MessageAction { + public static int constructor = 0xea3948e9; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + title = stream.readString(exception); + chat_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(title); + stream.writeInt64(chat_id); + } + } + public static class TL_messageActionGroupCall extends MessageAction { public static int constructor = 0x7a0d7f42; @@ -19423,7 +20445,72 @@ public class TLRPC { } } - public static class TL_messageActionChatMigrateTo extends MessageAction { + public static class TL_messages_getMessageReadParticipants extends TLObject { + public static int constructor = 0x2c6f97b7; + + public InputPeer peer; + public int msg_id; + + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + Vector vector = new Vector(); + int size = stream.readInt32(exception); + for (int a = 0; a < size; a++) { + vector.objects.add(stream.readInt64(exception)); + } + return vector; + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(msg_id); + } + } + + public static class TL_messageActionChatDeleteUser extends MessageAction { + public static int constructor = 0xa43f30cc; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + } + } + + public static class TL_messageActionChatAddUser extends MessageAction { + public static int constructor = 0x15cefd00; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + users.add(stream.readInt64(exception)); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(0x1cb5c415); + int count = users.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(users.get(a)); + } + } + } + + public static class TL_messageActionChatMigrateTo_layer131 extends TL_messageActionChatMigrateTo { public static int constructor = 0x51bdb021; @@ -19433,7 +20520,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt32((int) channel_id); } } @@ -19469,7 +20556,35 @@ public class TLRPC { } } - public static class TL_messageActionChannelMigrateFrom extends MessageAction { + public static class TL_messageActionChatMigrateTo extends MessageAction { + public static int constructor = 0xe1037f92; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + } + } + + public static class TL_messageActionChatJoinedByLink extends MessageAction { + public static int constructor = 0x31224c3; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + inviter_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(inviter_id); + } + } + + public static class TL_messageActionChannelMigrateFrom_layer131 extends TL_messageActionChannelMigrateFrom { public static int constructor = 0xb055eaee; @@ -19481,11 +20596,11 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeString(title); - stream.writeInt32(chat_id); + stream.writeInt32((int) chat_id); } } - public static class TL_messageActionChatAddUser extends MessageAction { + public static class TL_messageActionChatAddUser_layer131 extends TL_messageActionChatAddUser { public static int constructor = 0x488a7337; @@ -19499,7 +20614,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - users.add(stream.readInt32(exception)); + users.add((long) stream.readInt32(exception)); } } @@ -19509,12 +20624,12 @@ public class TLRPC { int count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(users.get(a)); + stream.writeInt32((int) (long) users.get(a)); } } } - public static class TL_messageActionChatDeleteUser extends MessageAction { + public static class TL_messageActionChatDeleteUser_layer131 extends TL_messageActionChatDeleteUser { public static int constructor = 0xb2ae9b0c; @@ -19524,7 +20639,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } @@ -19537,7 +20652,7 @@ public class TLRPC { } } - public static class TL_messageActionInviteToGroupCall extends MessageAction { + public static class TL_messageActionInviteToGroupCall_layer131 extends TL_messageActionInviteToGroupCall { public static int constructor = 0x76b9f11a; @@ -19552,7 +20667,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - users.add(stream.readInt32(exception)); + users.add((long) stream.readInt32(exception)); } } @@ -19563,7 +20678,7 @@ public class TLRPC { int count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(users.get(a)); + stream.writeInt32((int) (long) users.get(a)); } } } @@ -19610,7 +20725,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } @@ -19643,7 +20758,7 @@ public class TLRPC { } } - public static class TL_messageActionChatJoinedByLink extends MessageAction { + public static class TL_messageActionChatJoinedByLink_layer131 extends TL_messageActionChatJoinedByLink { public static int constructor = 0xf89cf5e8; @@ -19653,7 +20768,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(inviter_id); + stream.writeInt32((int) inviter_id); } } @@ -20023,37 +21138,6 @@ public class TLRPC { } } - public static class TL_chatLocated extends TLObject { - public static int constructor = 0x3631cf4c; - - public int chat_id; - public int distance; - - public static TL_chatLocated TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_chatLocated.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_chatLocated", constructor)); - } else { - return null; - } - } - TL_chatLocated result = new TL_chatLocated(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - distance = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(distance); - } - } - public static abstract class DecryptedMessage extends TLObject { public long random_id; public int ttl; @@ -20313,7 +21397,7 @@ public class TLRPC { public static account_Themes TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { account_Themes result = null; switch (constructor) { - case 0x7f676421: + case 0x9a3d8c6d: result = new TL_account_themes(); break; case 0xf41eb622: @@ -20331,13 +21415,13 @@ public class TLRPC { } public static class TL_account_themes extends account_Themes { - public static int constructor = 0x7f676421; + public static int constructor = 0x9a3d8c6d; - public int hash; + public long hash; public ArrayList themes = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); + hash = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -20357,7 +21441,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(hash); + stream.writeInt64(hash); stream.writeInt32(0x1cb5c415); int count = themes.size(); stream.writeInt32(count); @@ -20490,7 +21574,7 @@ public class TLRPC { case 0x1c199183: result = new TL_account_wallPapersNotModified(); break; - case 0x702b65a9: + case 0xcdc3858c: result = new TL_account_wallPapers(); break; } @@ -20514,13 +21598,13 @@ public class TLRPC { } public static class TL_account_wallPapers extends account_WallPapers { - public static int constructor = 0x702b65a9; + public static int constructor = 0xcdc3858c; - public int hash; + public long hash; public ArrayList wallpapers = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); + hash = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -20540,7 +21624,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(hash); + stream.writeInt64(hash); stream.writeInt32(0x1cb5c415); int count = wallpapers.size(); stream.writeInt32(count); @@ -20662,7 +21746,7 @@ public class TLRPC { public static abstract class Video extends TLObject { public long id; public long access_hash; - public int user_id; + public long user_id; public int date; public int duration; public int size; @@ -20728,7 +21812,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeInt32(duration); stream.writeInt32(size); @@ -20795,7 +21879,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(caption); stream.writeInt32(duration); @@ -20831,7 +21915,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(caption); stream.writeInt32(duration); @@ -20866,7 +21950,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(caption); stream.writeInt32(duration); @@ -21785,7 +22869,7 @@ public class TLRPC { public long id; public long access_hash; public byte[] file_reference; - public int user_id; + public long user_id; public int date; public String file_name; public String mime_type; @@ -21959,7 +23043,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(file_name); stream.writeString(mime_type); @@ -22164,7 +23248,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(file_name); stream.writeString(mime_type); @@ -23266,7 +24350,7 @@ public class TLRPC { case 0xd09e07b: result = new TL_inputPrivacyValueAllowContacts(); break; - case 0x4c81c1ba: + case 0x840649cf: result = new TL_inputPrivacyValueAllowChatParticipants(); break; case 0xba52007: @@ -23278,7 +24362,7 @@ public class TLRPC { case 0x131cc67f: result = new TL_inputPrivacyValueAllowUsers(); break; - case 0xd82363af: + case 0xe94f0f86: result = new TL_inputPrivacyValueDisallowChatParticipants(); break; } @@ -23345,9 +24429,9 @@ public class TLRPC { } public static class TL_inputPrivacyValueAllowChatParticipants extends InputPrivacyRule { - public static int constructor = 0x4c81c1ba; + public static int constructor = 0x840649cf; - public ArrayList chats = new ArrayList<>(); + public ArrayList chats = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -23359,7 +24443,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - chats.add(stream.readInt32(exception)); + chats.add(stream.readInt64(exception)); } } @@ -23369,7 +24453,7 @@ public class TLRPC { int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(chats.get(a)); + stream.writeInt64(chats.get(a)); } } } @@ -23427,9 +24511,9 @@ public class TLRPC { } public static class TL_inputPrivacyValueDisallowChatParticipants extends InputPrivacyRule { - public static int constructor = 0xd82363af; + public static int constructor = 0xe94f0f86; - public ArrayList chats = new ArrayList<>(); + public ArrayList chats = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); @@ -23441,7 +24525,7 @@ public class TLRPC { } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { - chats.add(stream.readInt32(exception)); + chats.add(stream.readInt64(exception)); } } @@ -23451,7 +24535,7 @@ public class TLRPC { int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(chats.get(a)); + stream.writeInt64(chats.get(a)); } } } @@ -23575,39 +24659,39 @@ public class TLRPC { } } - public static class TL_highScore extends TLObject { - public static int constructor = 0x58fffcd0; + public static class TL_highScore extends TLObject { + public static int constructor = 0x73a379eb; - public int pos; - public int user_id; - public int score; + public int pos; + public long user_id; + public int score; - public static TL_highScore TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_highScore.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_highScore", constructor)); - } else { - return null; - } - } - TL_highScore result = new TL_highScore(); - result.readParams(stream, exception); - return result; - } + public static TL_highScore TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_highScore.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_highScore", constructor)); + } else { + return null; + } + } + TL_highScore result = new TL_highScore(); + result.readParams(stream, exception); + return result; + } - public void readParams(AbstractSerializedData stream, boolean exception) { - pos = stream.readInt32(exception); - user_id = stream.readInt32(exception); - score = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + pos = stream.readInt32(exception); + user_id = stream.readInt64(exception); + score = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(pos); - stream.writeInt32(user_id); - stream.writeInt32(score); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(pos); + stream.writeInt64(user_id); + stream.writeInt32(score); + } + } public static abstract class InputMedia extends TLObject { public String phone_number; @@ -24599,19 +25683,19 @@ public class TLRPC { public static abstract class MessageUserVote extends TLObject { - public int user_id; + public long user_id; public int date; public static MessageUserVote TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { MessageUserVote result = null; switch (constructor) { - case 0xa28e5559: + case 0x34d247b4: result = new TL_messageUserVote(); break; - case 0x36377430: + case 0x3ca5b0ec: result = new TL_messageUserVoteInputOption(); break; - case 0xe8fe0de: + case 0x8a65e557: result = new TL_messageUserVoteMultiple(); break; } @@ -24626,47 +25710,47 @@ public class TLRPC { } public static class TL_messageUserVote extends MessageUserVote { - public static int constructor = 0xa28e5559; + public static int constructor = 0x34d247b4; public byte[] option; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); option = stream.readByteArray(exception); date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeByteArray(option); stream.writeInt32(date); } } public static class TL_messageUserVoteInputOption extends MessageUserVote { - public static int constructor = 0x36377430; + public static int constructor = 0x3ca5b0ec; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(date); } } public static class TL_messageUserVoteMultiple extends MessageUserVote { - public static int constructor = 0xe8fe0de; + public static int constructor = 0x8a65e557; public ArrayList options = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -24683,7 +25767,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(0x1cb5c415); int count = options.size(); stream.writeInt32(count); @@ -24876,13 +25960,13 @@ public class TLRPC { case 0xbb9bb9a5: result = new TL_updatePeerHistoryTTL(); break; - case 0x1330a196: + case 0xf89a6a4e: result = new TL_updateChat(); break; case 0xa20db0e5: result = new TL_updateDeleteMessages(); break; - case 0x8588878b: + case 0x5bb98608: result = new TL_updatePinnedChannelMessages(); break; case 0xf2ebdb4e: @@ -24894,27 +25978,33 @@ public class TLRPC { case 0x1710f156: result = new TL_updateEncryptedChatTyping(); break; - case 0x62ba04d9: - result = new TL_updateNewChannelMessage(); + case 0xd6b19546: + result = new TL_updateReadChannelDiscussionInbox(); break; case 0x2f2f21bf: result = new TL_updateReadHistoryOutbox(); break; + case 0x62ba04d9: + result = new TL_updateNewChannelMessage(); + break; case 0x6e6fe51c: result = new TL_updateDialogPinned(); break; case 0x6a7e7366: result = new TL_updatePeerSettings(); break; - case 0x12b9417b: + case 0x5492a13: result = new TL_updateUserPhone(); break; case 0x4e90bfd6: result = new TL_updateMessageID(); break; - case 0x25d6c9c7: + case 0xb75f99a9: result = new TL_updateReadChannelOutbox(); break; + case 0x8c88c923: + result = new TL_updateChannelUserTyping(); + break; case 0x43ae3dec: result = new TL_updateStickerSets(); break; @@ -24930,16 +26020,16 @@ public class TLRPC { case 0x12bcbd9a: result = new TL_updateNewEncryptedMessage(); break; - case 0x1bfbd823: + case 0xe5bdf8de: result = new TL_updateUserStatus(); break; - case 0x98a12b4b: + case 0xf226ac08: result = new TL_updateChannelMessageViews(); break; case 0xb783982: result = new TL_updateGroupCallConnection(); break; - case 0xcf7e0873: + case 0x4d712f2e: result = new TL_updateBotCommands(); break; case 0x871fb939: @@ -24948,10 +26038,13 @@ public class TLRPC { case 0xbec268ef: result = new TL_updateNotifySettings(); break; - case 0x65d2b464: + case 0x985d3abb: result = new TL_updateChannelParticipant(); break; - case 0x6e5f8c22: + case 0x695c9e7c: + result = new TL_updateReadChannelDiscussionOutbox(); + break; + case 0xe32f3d77: result = new TL_updateChatParticipantDelete(); break; case 0xe40370a3: @@ -24963,13 +26056,10 @@ public class TLRPC { case 0xe511996d: result = new TL_updateFavedStickers(); break; - case 0xb4afcfb0: - result = new TL_updatePeerLocated(); - break; - case 0xea4b0e5c: + case 0x3dda5451: result = new TL_updateChatParticipantAdd(); break; - case 0x86cadb6c: + case 0x83487af0: result = new TL_updateChatUserTyping(); break; case 0x564fe691: @@ -24978,13 +26068,13 @@ public class TLRPC { case 0xb4a2e88d: result = new TL_updateEncryption(); break; - case 0xa45eb99b: + case 0x14b24500: result = new TL_updateGroupCall(); break; - case 0xeb0467fb: + case 0x108d941f: result = new TL_updateChannelTooLong(); break; - case 0x5c486927: + case 0xc01e857f: result = new TL_updateUserTyping(); break; case 0xebe46819: @@ -24993,10 +26083,13 @@ public class TLRPC { case 0x56022f4d: result = new TL_updateLangPack(); break; - case 0xb6901959: + case 0xb23fc698: + result = new TL_updateChannelAvailableMessages(); + break; + case 0xd7ca61a2: result = new TL_updateChatParticipantAdmin(); break; - case 0x89893b45: + case 0x44bdd535: result = new TL_updateChannelReadMessagesContents(); break; case 0xee3b272a: @@ -25005,35 +26098,29 @@ public class TLRPC { case 0xa229dd06: result = new TL_updateConfig(); break; - case 0xee2bb969: - result = new TL_updateDraftMessage(); - break; - case 0xa7332b73: - result = new TL_updateUserName(); - break; - case 0x70db6837: - result = new TL_updateChannelAvailableMessages(); - break; case 0xe16459c3: result = new TL_updateDialogUnreadMark(); break; - case 0xab0f6b1e: - result = new TL_updatePhoneCall(); + case 0xee2bb969: + result = new TL_updateDraftMessage(); + break; + case 0xc3f202e0: + result = new TL_updateUserName(); break; case 0x154798c3: result = new TL_updateMessageReactions(); break; + case 0xab0f6b1e: + result = new TL_updatePhoneCall(); + break; case 0x26ffde7d: result = new TL_updateDialogFilter(); break; - case 0x1cc7de54: - result = new TL_updateReadChannelDiscussionInbox(); + case 0x246a4b22: + result = new TL_updatePeerBlocked(); break; - case 0x4638a26c: - result = new TL_updateReadChannelDiscussionOutbox(); - break; - case 0x6b171718: - result = new TL_updateChannelUserTyping(); + case 0xed85eab5: + result = new TL_updatePinnedMessages(); break; case 0x2661bf09: result = new TL_updatePhoneCallSignalingData(); @@ -25041,6 +26128,9 @@ public class TLRPC { case 0xfa0f3ca2: result = new TL_updatePinnedDialogs(); break; + case 0xb4afcfb0: + result = new TL_updatePeerLocated(); + break; case 0x9a422c20: result = new TL_updateRecentStickers(); break; @@ -25056,33 +26146,27 @@ public class TLRPC { case 0x7084a7be: result = new TL_updateContactsReset(); break; - case 0xb6d45656: + case 0x635b4c09: result = new TL_updateChannel(); break; - case 0x40771900: + case 0x2f2ba99f: result = new TL_updateChannelWebPage(); break; case 0x90866cee: result = new TL_updateDeleteScheduledMessages(); break; - case 0x6e8a84df: + case 0xd29a27f4: result = new TL_updateChannelMessageForwards(); break; - case 0xc37521c9: + case 0xc32d5b12: result = new TL_updateDeleteChannelMessages(); break; - case 0x95313b0c: + case 0xf227868c: result = new TL_updateUserPhoto(); break; case 0x3504914f: result = new TL_updateDialogFilters(); break; - case 0x246a4b22: - result = new TL_updatePeerBlocked(); - break; - case 0xed85eab5: - result = new TL_updatePinnedMessages(); - break; case 0x8e5e9873: result = new TL_updateDcOptions(); break; @@ -25092,19 +26176,19 @@ public class TLRPC { case 0x688a30aa: result = new TL_updateNewStickerSet(); break; - case 0x46560264: - result = new TL_updateLangPackTooLong(); - break; case 0x8216fba3: result = new TL_updateTheme(); break; + case 0x46560264: + result = new TL_updateLangPackTooLong(); + break; case 0x38fe25b7: result = new TL_updateEncryptedMessagesRead(); break; case 0xbb2d201: result = new TL_updateStickerSetsOrder(); break; - case 0x330b5424: + case 0x922e6e10: result = new TL_updateReadChannelInbox(); break; case 0x68c13933: @@ -25127,6 +26211,74 @@ public class TLRPC { } } + public static class TL_updateMessagePoll extends Update { + public static int constructor = 0xaca1657b; + + public int flags; + public long poll_id; + public Poll poll; + public PollResults results; + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + poll_id = stream.readInt64(exception); + if ((flags & 1) != 0) { + poll = Poll.TLdeserialize(stream, stream.readInt32(exception), exception); + } + results = PollResults.TLdeserialize(stream, stream.readInt32(exception), exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt64(poll_id); + if ((flags & 1) != 0) { + poll.serializeToStream(stream); + } + results.serializeToStream(stream); + } + } + + public static class TL_updatePeerHistoryTTL extends Update { + public static int constructor = 0xbb9bb9a5; + + public int flags; + public Peer peer; + public int ttl_period; + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 1) != 0) { + ttl_period = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + peer.serializeToStream(stream); + if ((flags & 1) != 0) { + stream.writeInt32(ttl_period); + } + } + } + + public static class TL_updateChat extends Update { + public static int constructor = 0xf89a6a4e; + + public long chat_id; + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + } + } + public static class TL_updateDeleteMessages extends Update { public static int constructor = 0xa20db0e5; @@ -25164,11 +26316,11 @@ public class TLRPC { } public static class TL_updatePinnedChannelMessages extends Update { - public static int constructor = 0x8588878b; + public static int constructor = 0x5bb98608; public int flags; public boolean pinned; - public int channel_id; + public long channel_id; public ArrayList messages = new ArrayList<>(); public int pts; public int pts_count; @@ -25176,7 +26328,7 @@ public class TLRPC { public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 1) != 0; - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -25196,7 +26348,7 @@ public class TLRPC { stream.writeInt32(constructor); flags = pinned ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(0x1cb5c415); int count = messages.size(); stream.writeInt32(count); @@ -25272,24 +26424,41 @@ public class TLRPC { } } - public static class TL_updateNewChannelMessage extends Update { - public static int constructor = 0x62ba04d9; + public static class TL_updateReadChannelDiscussionInbox extends Update { + public static int constructor = 0xd6b19546; - public Message message; - public int pts; - public int pts_count; + public int flags; + public long channel_id; + public int top_msg_id; + public int read_max_id; + public long broadcast_id; + public int broadcast_post; public void readParams(AbstractSerializedData stream, boolean exception) { - message = Message.TLdeserialize(stream, stream.readInt32(exception), exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); + flags = stream.readInt32(exception); + channel_id = stream.readInt64(exception); + top_msg_id = stream.readInt32(exception); + read_max_id = stream.readInt32(exception); + if ((flags & 1) != 0) { + broadcast_id = stream.readInt64(exception); + } + if ((flags & 1) != 0) { + broadcast_post = stream.readInt32(exception); + } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - message.serializeToStream(stream); - stream.writeInt32(pts); - stream.writeInt32(pts_count); + stream.writeInt32(flags); + stream.writeInt64(channel_id); + stream.writeInt32(top_msg_id); + stream.writeInt32(read_max_id); + if ((flags & 1) != 0) { + stream.writeInt64(broadcast_id); + } + if ((flags & 1) != 0) { + stream.writeInt32(broadcast_post); + } } } @@ -25317,6 +26486,27 @@ public class TLRPC { } } + public static class TL_updateNewChannelMessage extends Update { + public static int constructor = 0x62ba04d9; + + public Message message; + public int pts; + public int pts_count; + + public void readParams(AbstractSerializedData stream, boolean exception) { + message = Message.TLdeserialize(stream, stream.readInt32(exception), exception); + pts = stream.readInt32(exception); + pts_count = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + message.serializeToStream(stream); + stream.writeInt32(pts); + stream.writeInt32(pts_count); + } + } + public static class TL_updateDialogPinned extends Update { public static int constructor = 0x6e6fe51c; @@ -25364,19 +26554,19 @@ public class TLRPC { } public static class TL_updateUserPhone extends Update { - public static int constructor = 0x12b9417b; + public static int constructor = 0x5492a13; - public int user_id; + public long user_id; public String phone; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); phone = stream.readString(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeString(phone); } } @@ -25400,23 +26590,54 @@ public class TLRPC { } public static class TL_updateReadChannelOutbox extends Update { - public static int constructor = 0x25d6c9c7; + public static int constructor = 0xb75f99a9; - public int channel_id; + public long channel_id; public int max_id; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); max_id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(max_id); } } + public static class TL_updateChannelUserTyping extends Update { + public static int constructor = 0x8c88c923; + + public int flags; + public long channel_id; + public int top_msg_id; + public Peer from_id; + public SendMessageAction action; + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + channel_id = stream.readInt64(exception); + if ((flags & 1) != 0) { + top_msg_id = stream.readInt32(exception); + } + from_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + action = SendMessageAction.TLdeserialize(stream, stream.readInt32(exception), exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt64(channel_id); + if ((flags & 1) != 0) { + stream.writeInt32(top_msg_id); + } + from_id.serializeToStream(stream); + action.serializeToStream(stream); + } + } + public static class TL_updateStickerSets extends Update { public static int constructor = 0x43ae3dec; @@ -25521,39 +26742,39 @@ public class TLRPC { } public static class TL_updateUserStatus extends Update { - public static int constructor = 0x1bfbd823; + public static int constructor = 0xe5bdf8de; - public int user_id; + public long user_id; public UserStatus status; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); status = UserStatus.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); status.serializeToStream(stream); } } public static class TL_updateChannelMessageViews extends Update { - public static int constructor = 0x98a12b4b; + public static int constructor = 0xf226ac08; - public int channel_id; + public long channel_id; public int id; public int views; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); id = stream.readInt32(exception); views = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(id); stream.writeInt32(views); } @@ -25581,15 +26802,15 @@ public class TLRPC { } public static class TL_updateBotCommands extends Update { - public static int constructor = 0xcf7e0873; + public static int constructor = 0x4d712f2e; public Peer peer; - public int bot_id; + public long bot_id; public ArrayList commands = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - bot_id = stream.readInt32(exception); + bot_id = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -25610,7 +26831,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); - stream.writeInt32(bot_id); + stream.writeInt64(bot_id); stream.writeInt32(0x1cb5c415); int count = commands.size(); stream.writeInt32(count); @@ -25657,63 +26878,94 @@ public class TLRPC { } public static class TL_updateChannelParticipant extends Update { - public static int constructor = 0x65d2b464; + public static int constructor = 0x985d3abb; public int flags; - public int channel_id; + public long channel_id; public int date; - public int user_id; + public long actor_id; + public long user_id; public ChannelParticipant prev_participant; public ChannelParticipant new_participant; + public ExportedChatInvite invite; public int qts; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); date = stream.readInt32(exception); - user_id = stream.readInt32(exception); + actor_id = stream.readInt64(exception); + user_id = stream.readInt64(exception); if ((flags & 1) != 0) { prev_participant = ChannelParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 2) != 0) { new_participant = ChannelParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); } + if ((flags & 4) != 0) { + invite = ExportedChatInvite.TLdeserialize(stream, stream.readInt32(exception), exception); + } qts = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(date); - stream.writeInt32(user_id); + stream.writeInt64(actor_id); + stream.writeInt64(user_id); if ((flags & 1) != 0) { prev_participant.serializeToStream(stream); } if ((flags & 2) != 0) { new_participant.serializeToStream(stream); } + if ((flags & 4) != 0) { + invite.serializeToStream(stream); + } stream.writeInt32(qts); } } - public static class TL_updateChatParticipantDelete extends Update { - public static int constructor = 0x6e5f8c22; + public static class TL_updateReadChannelDiscussionOutbox extends Update { + public static int constructor = 0x695c9e7c; - public int chat_id; - public int user_id; + public long channel_id; + public int top_msg_id; + public int read_max_id; + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + top_msg_id = stream.readInt32(exception); + read_max_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + stream.writeInt32(top_msg_id); + stream.writeInt32(read_max_id); + } + } + + public static class TL_updateChatParticipantDelete extends Update { + public static int constructor = 0xe32f3d77; + + public long chat_id; + public long user_id; public int version; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - user_id = stream.readInt32(exception); + chat_id = stream.readInt64(exception); + user_id = stream.readInt64(exception); version = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(user_id); + stream.writeInt64(chat_id); + stream.writeInt64(user_id); stream.writeInt32(version); } } @@ -25769,151 +27021,49 @@ public class TLRPC { } } - public static class TL_updatePeerLocated extends Update { - public static int constructor = 0xb4afcfb0; - - public ArrayList peers = new ArrayList<>(); - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - PeerLocated object = PeerLocated.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - peers.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = peers.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - peers.get(a).serializeToStream(stream); - } - } - } - public static class TL_updateChatParticipantAdd extends Update { - public static int constructor = 0xea4b0e5c; + public static int constructor = 0x3dda5451; - public int chat_id; - public int user_id; - public int inviter_id; + public long chat_id; + public long user_id; + public long inviter_id; public int date; public int version; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - user_id = stream.readInt32(exception); - inviter_id = stream.readInt32(exception); + chat_id = stream.readInt64(exception); + user_id = stream.readInt64(exception); + inviter_id = stream.readInt64(exception); date = stream.readInt32(exception); version = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(user_id); - stream.writeInt32(inviter_id); + stream.writeInt64(chat_id); + stream.writeInt64(user_id); + stream.writeInt64(inviter_id); stream.writeInt32(date); stream.writeInt32(version); } } - public static class TL_updateMessagePoll extends Update { - public static int constructor = 0xaca1657b; - - public int flags; - public long poll_id; - public Poll poll; - public PollResults results; - - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - poll_id = stream.readInt64(exception); - if ((flags & 1) != 0) { - poll = Poll.TLdeserialize(stream, stream.readInt32(exception), exception); - } - results = PollResults.TLdeserialize(stream, stream.readInt32(exception), exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(flags); - stream.writeInt64(poll_id); - if ((flags & 1) != 0) { - poll.serializeToStream(stream); - } - results.serializeToStream(stream); - } - } - - public static class TL_updatePeerHistoryTTL extends Update { - public static int constructor = 0xbb9bb9a5; - - public int flags; - public Peer peer; - public int ttl_period; - - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - if ((flags & 1) != 0) { - ttl_period = stream.readInt32(exception); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(flags); - peer.serializeToStream(stream); - if ((flags & 1) != 0) { - stream.writeInt32(ttl_period); - } - } - } - - public static class TL_updateChat extends Update { - public static int constructor = 0x1330a196; - - public int chat_id; - - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - } - } - public static class TL_updateChatUserTyping extends Update { - public static int constructor = 0x86cadb6c; + public static int constructor = 0x83487af0; - public int chat_id; + public long chat_id; public Peer from_id; public SendMessageAction action; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); + chat_id = stream.readInt64(exception); from_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); action = SendMessageAction.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); from_id.serializeToStream(stream); action.serializeToStream(stream); } @@ -25947,33 +27097,33 @@ public class TLRPC { } public static class TL_updateGroupCall extends Update { - public static int constructor = 0xa45eb99b; + public static int constructor = 0x14b24500; - public int chat_id; + public long chat_id; public GroupCall call; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); + chat_id = stream.readInt64(exception); call = GroupCall.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); call.serializeToStream(stream); } } public static class TL_updateChannelTooLong extends Update { - public static int constructor = 0xeb0467fb; + public static int constructor = 0x108d941f; public int flags; - public int channel_id; + public long channel_id; public int pts; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); if ((flags & 1) != 0) { pts = stream.readInt32(exception); } @@ -25982,7 +27132,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); if ((flags & 1) != 0) { stream.writeInt32(pts); } @@ -25990,19 +27140,19 @@ public class TLRPC { } public static class TL_updateUserTyping extends Update { - public static int constructor = 0x5c486927; + public static int constructor = 0xc01e857f; - public int user_id; + public long user_id; public SendMessageAction action; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); action = SendMessageAction.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); action.serializeToStream(stream); } } @@ -26078,38 +27228,56 @@ public class TLRPC { } } - public static class TL_updateChatParticipantAdmin extends Update { - public static int constructor = 0xb6901959; + public static class TL_updateChannelAvailableMessages extends Update { + public static int constructor = 0xb23fc698; - public int chat_id; - public int user_id; + public long channel_id; + public int available_min_id; + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + available_min_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + stream.writeInt32(available_min_id); + } + } + + public static class TL_updateChatParticipantAdmin extends Update { + public static int constructor = 0xd7ca61a2; + + public long chat_id; + public long user_id; public boolean is_admin; public int version; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - user_id = stream.readInt32(exception); + chat_id = stream.readInt64(exception); + user_id = stream.readInt64(exception); is_admin = stream.readBool(exception); version = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(user_id); + stream.writeInt64(chat_id); + stream.writeInt64(user_id); stream.writeBool(is_admin); stream.writeInt32(version); } } public static class TL_updateChannelReadMessagesContents extends Update { - public static int constructor = 0x89893b45; + public static int constructor = 0x44bdd535; - public int channel_id; + public long channel_id; public ArrayList messages = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -26125,7 +27293,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(0x1cb5c415); int count = messages.size(); stream.writeInt32(count); @@ -26181,66 +27349,6 @@ public class TLRPC { } } - public static class TL_updateDraftMessage extends Update { - public static int constructor = 0xee2bb969; - - public Peer peer; - public DraftMessage draft; - - public void readParams(AbstractSerializedData stream, boolean exception) { - peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - draft = DraftMessage.TLdeserialize(stream, stream.readInt32(exception), exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - draft.serializeToStream(stream); - } - } - - public static class TL_updateUserName extends Update { - public static int constructor = 0xa7332b73; - - public int user_id; - public String first_name; - public String last_name; - public String username; - - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - first_name = stream.readString(exception); - last_name = stream.readString(exception); - username = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - stream.writeString(first_name); - stream.writeString(last_name); - stream.writeString(username); - } - } - - public static class TL_updateChannelAvailableMessages extends Update { - public static int constructor = 0x70db6837; - - public int channel_id; - public int available_min_id; - - public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); - available_min_id = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(channel_id); - stream.writeInt32(available_min_id); - } - } - public static class TL_updateDialogUnreadMark extends Update { public static int constructor = 0xe16459c3; @@ -26262,18 +27370,45 @@ public class TLRPC { } } - public static class TL_updatePhoneCall extends Update { - public static int constructor = 0xab0f6b1e; + public static class TL_updateDraftMessage extends Update { + public static int constructor = 0xee2bb969; - public PhoneCall phone_call; + public Peer peer; + public DraftMessage draft; public void readParams(AbstractSerializedData stream, boolean exception) { - phone_call = PhoneCall.TLdeserialize(stream, stream.readInt32(exception), exception); + peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + draft = DraftMessage.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - phone_call.serializeToStream(stream); + peer.serializeToStream(stream); + draft.serializeToStream(stream); + } + } + + public static class TL_updateUserName extends Update { + public static int constructor = 0xc3f202e0; + + public long user_id; + public String first_name; + public String last_name; + public String username; + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + first_name = stream.readString(exception); + last_name = stream.readString(exception); + username = stream.readString(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeString(first_name); + stream.writeString(last_name); + stream.writeString(username); } } @@ -26298,6 +27433,21 @@ public class TLRPC { } } + public static class TL_updatePhoneCall extends Update { + public static int constructor = 0xab0f6b1e; + + public PhoneCall phone_call; + + public void readParams(AbstractSerializedData stream, boolean exception) { + phone_call = PhoneCall.TLdeserialize(stream, stream.readInt32(exception), exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + phone_call.serializeToStream(stream); + } + } + public static class TL_updateDialogFilter extends Update { public static int constructor = 0x26ffde7d; @@ -26323,6 +27473,69 @@ public class TLRPC { } } + public static class TL_updatePeerBlocked extends Update { + public static int constructor = 0x246a4b22; + + public Peer peer_id; + public boolean blocked; + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + blocked = stream.readBool(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer_id.serializeToStream(stream); + stream.writeBool(blocked); + } + } + + public static class TL_updatePinnedMessages extends Update { + public static int constructor = 0xed85eab5; + + public int flags; + public boolean pinned; + public Peer peer; + public ArrayList messages = new ArrayList<>(); + public int pts; + public int pts_count; + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + pinned = (flags & 1) != 0; + peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + messages.add(stream.readInt32(exception)); + } + pts = stream.readInt32(exception); + pts_count = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = pinned ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + peer.serializeToStream(stream); + stream.writeInt32(0x1cb5c415); + int count = messages.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt32(messages.get(a)); + } + stream.writeInt32(pts); + stream.writeInt32(pts_count); + } + } + public static class TL_updatePhoneCallSignalingData extends Update { public static int constructor = 0x2661bf09; @@ -26389,93 +27602,37 @@ public class TLRPC { } } - public static class TL_updateReadChannelDiscussionInbox extends Update { - public static int constructor = 0x1cc7de54; + public static class TL_updatePeerLocated extends Update { + public static int constructor = 0xb4afcfb0; - public int flags; - public int channel_id; - public int top_msg_id; - public int read_max_id; - public int broadcast_id; - public int broadcast_post; + public ArrayList peers = new ArrayList<>(); public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - channel_id = stream.readInt32(exception); - top_msg_id = stream.readInt32(exception); - read_max_id = stream.readInt32(exception); - if ((flags & 1) != 0) { - broadcast_id = stream.readInt32(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; } - if ((flags & 1) != 0) { - broadcast_post = stream.readInt32(exception); + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + PeerLocated object = PeerLocated.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + peers.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(flags); - stream.writeInt32(channel_id); - stream.writeInt32(top_msg_id); - stream.writeInt32(read_max_id); - if ((flags & 1) != 0) { - stream.writeInt32(broadcast_id); + stream.writeInt32(0x1cb5c415); + int count = peers.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + peers.get(a).serializeToStream(stream); } - if ((flags & 1) != 0) { - stream.writeInt32(broadcast_post); - } - } - } - - public static class TL_updateReadChannelDiscussionOutbox extends Update { - public static int constructor = 0x4638a26c; - - public int channel_id; - public int top_msg_id; - public int read_max_id; - - public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); - top_msg_id = stream.readInt32(exception); - read_max_id = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(channel_id); - stream.writeInt32(top_msg_id); - stream.writeInt32(read_max_id); - } - } - - public static class TL_updateChannelUserTyping extends Update { - public static int constructor = 0x6b171718; - - public int flags; - public int channel_id; - public int top_msg_id; - public Peer from_id; - public SendMessageAction action; - - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - channel_id = stream.readInt32(exception); - if ((flags & 1) != 0) { - top_msg_id = stream.readInt32(exception); - } - from_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - action = SendMessageAction.TLdeserialize(stream, stream.readInt32(exception), exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(flags); - stream.writeInt32(channel_id); - if ((flags & 1) != 0) { - stream.writeInt32(top_msg_id); - } - from_id.serializeToStream(stream); - action.serializeToStream(stream); } } @@ -26574,30 +27731,30 @@ public class TLRPC { } public static class TL_updateChannel extends Update { - public static int constructor = 0xb6d45656; + public static int constructor = 0x635b4c09; - public int channel_id; + public long channel_id; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); } } public static class TL_updateChannelWebPage extends Update { - public static int constructor = 0x40771900; + public static int constructor = 0x2f2ba99f; - public int channel_id; + public long channel_id; public WebPage webpage; public int pts; public int pts_count; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); webpage = WebPage.TLdeserialize(stream, stream.readInt32(exception), exception); pts = stream.readInt32(exception); pts_count = stream.readInt32(exception); @@ -26605,7 +27762,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); webpage.serializeToStream(stream); stream.writeInt32(pts); stream.writeInt32(pts_count); @@ -26646,36 +27803,36 @@ public class TLRPC { } public static class TL_updateChannelMessageForwards extends Update { - public static int constructor = 0x6e8a84df; + public static int constructor = 0xd29a27f4; - public int channel_id; + public long channel_id; public int id; public int forwards; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); id = stream.readInt32(exception); forwards = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(id); stream.writeInt32(forwards); } } public static class TL_updateDeleteChannelMessages extends Update { - public static int constructor = 0xc37521c9; + public static int constructor = 0xc32d5b12; - public int channel_id; + public long channel_id; public ArrayList messages = new ArrayList<>(); public int pts; public int pts_count; public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { @@ -26693,7 +27850,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(0x1cb5c415); int count = messages.size(); stream.writeInt32(count); @@ -26706,15 +27863,15 @@ public class TLRPC { } public static class TL_updateUserPhoto extends Update { - public static int constructor = 0x95313b0c; + public static int constructor = 0xf227868c; - public int user_id; + public long user_id; public int date; public UserProfilePhoto photo; public boolean previous; public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); date = stream.readInt32(exception); photo = UserProfilePhoto.TLdeserialize(stream, stream.readInt32(exception), exception); previous = stream.readBool(exception); @@ -26722,7 +27879,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt64(user_id); stream.writeInt32(date); photo.serializeToStream(stream); stream.writeBool(previous); @@ -26738,69 +27895,6 @@ public class TLRPC { } } - public static class TL_updatePeerBlocked extends Update { - public static int constructor = 0x246a4b22; - - public Peer peer_id; - public boolean blocked; - - public void readParams(AbstractSerializedData stream, boolean exception) { - peer_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - blocked = stream.readBool(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer_id.serializeToStream(stream); - stream.writeBool(blocked); - } - } - - public static class TL_updatePinnedMessages extends Update { - public static int constructor = 0xed85eab5; - - public int flags; - public boolean pinned; - public Peer peer; - public ArrayList messages = new ArrayList<>(); - public int pts; - public int pts_count; - - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - pinned = (flags & 1) != 0; - peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - messages.add(stream.readInt32(exception)); - } - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = pinned ? (flags | 1) : (flags &~ 1); - stream.writeInt32(flags); - peer.serializeToStream(stream); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(messages.get(a)); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - public static class TL_updateDcOptions extends Update { public static int constructor = 0x8e5e9873; @@ -26871,21 +27965,6 @@ public class TLRPC { } } - public static class TL_updateLangPackTooLong extends Update { - public static int constructor = 0x46560264; - - public String lang_code; - - public void readParams(AbstractSerializedData stream, boolean exception) { - lang_code = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(lang_code); - } - } - public static class TL_updateTheme extends Update { public static int constructor = 0x8216fba3; @@ -26901,6 +27980,21 @@ public class TLRPC { } } + public static class TL_updateLangPackTooLong extends Update { + public static int constructor = 0x46560264; + + public String lang_code; + + public void readParams(AbstractSerializedData stream, boolean exception) { + lang_code = stream.readString(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(lang_code); + } + } + public static class TL_updateEncryptedMessagesRead extends Update { public static int constructor = 0x38fe25b7; @@ -26959,11 +28053,11 @@ public class TLRPC { } public static class TL_updateReadChannelInbox extends Update { - public static int constructor = 0x330b5424; + public static int constructor = 0x922e6e10; public int flags; public int folder_id; - public int channel_id; + public long channel_id; public int max_id; public int still_unread_count; public int pts; @@ -26973,7 +28067,7 @@ public class TLRPC { if ((flags & 1) != 0) { folder_id = stream.readInt32(exception); } - channel_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); max_id = stream.readInt32(exception); still_unread_count = stream.readInt32(exception); pts = stream.readInt32(exception); @@ -26985,7 +28079,7 @@ public class TLRPC { if ((flags & 1) != 0) { stream.writeInt32(folder_id); } - stream.writeInt32(channel_id); + stream.writeInt64(channel_id); stream.writeInt32(max_id); stream.writeInt32(still_unread_count); stream.writeInt32(pts); @@ -27200,9 +28294,9 @@ public class TLRPC { public static messages_AllStickers TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { messages_AllStickers result = null; switch (constructor) { - case 0xedfd405f: - result = new TL_messages_allStickers(); - break; + case 0xcdbbcebb: + result = new TL_messages_allStickers(); + break; case 0xe86602c3: result = new TL_messages_allStickersNotModified(); break; @@ -27217,41 +28311,41 @@ public class TLRPC { } } - public static class TL_messages_allStickers extends messages_AllStickers { - public static int constructor = 0xedfd405f; + public static class TL_messages_allStickers extends messages_AllStickers { + public static int constructor = 0xcdbbcebb; - public int hash; + public long hash; - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - StickerSet object = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - sets.add(object); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + StickerSet object = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + sets.add(object); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = sets.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - sets.get(a).serializeToStream(stream); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = sets.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + sets.get(a).serializeToStream(stream); + } + } + } public static class TL_messages_allStickersNotModified extends messages_AllStickers { public static int constructor = 0xe86602c3; @@ -27786,9 +28880,9 @@ public class TLRPC { } public static class TL_chatAdminWithInvites extends TLObject { - public static int constructor = 0xdfd2330f; + public static int constructor = 0xf2ecef23; - public int admin_id; + public long admin_id; public int invites_count; public int revoked_invites_count; @@ -27806,14 +28900,14 @@ public class TLRPC { } public void readParams(AbstractSerializedData stream, boolean exception) { - admin_id = stream.readInt32(exception); + admin_id = stream.readInt64(exception); invites_count = stream.readInt32(exception); revoked_invites_count = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(admin_id); + stream.writeInt64(admin_id); stream.writeInt32(invites_count); stream.writeInt32(revoked_invites_count); } @@ -28055,7 +29149,7 @@ public class TLRPC { result = new TL_messageEntityMention(); break; case 0x352dca58: - result = new TL_messageEntityMentionName(); + result = new TL_messageEntityMentionName_layer131(); break; case 0x208e68c9: result = new TL_inputMessageEntityMentionName(); @@ -28087,6 +29181,9 @@ public class TLRPC { case 0x9b69e34b: result = new TL_messageEntityPhone(); break; + case 0xdc7b1140: + result = new TL_messageEntityMentionName(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in MessageEntity", constructor)); @@ -28230,10 +29327,9 @@ public class TLRPC { } } - public static class TL_messageEntityMentionName extends MessageEntity { + public static class TL_messageEntityMentionName_layer131 extends TL_messageEntityMentionName { public static int constructor = 0x352dca58; - public int user_id; public void readParams(AbstractSerializedData stream, boolean exception) { offset = stream.readInt32(exception); @@ -28245,7 +29341,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(offset); stream.writeInt32(length); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } @@ -28410,6 +29506,25 @@ public class TLRPC { } } + public static class TL_messageEntityMentionName extends MessageEntity { + public static int constructor = 0xdc7b1140; + + public long user_id; + + public void readParams(AbstractSerializedData stream, boolean exception) { + offset = stream.readInt32(exception); + length = stream.readInt32(exception); + user_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(offset); + stream.writeInt32(length); + stream.writeInt64(user_id); + } + } + public static abstract class ChannelLocation extends TLObject { public static ChannelLocation TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -28470,7 +29585,7 @@ public class TLRPC { public ArrayList sizes = new ArrayList<>(); public ArrayList video_sizes = new ArrayList<>(); public int dc_id; - public int user_id; + public long user_id; public GeoPoint geo; public String caption; @@ -28627,7 +29742,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); geo.serializeToStream(stream); stream.writeInt32(0x1cb5c415); @@ -28685,7 +29800,7 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt64(access_hash); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt32(date); stream.writeString(caption); geo.serializeToStream(stream); @@ -28860,7 +29975,7 @@ public class TLRPC { } } - public static class TL_encryptedChatRequested extends EncryptedChat { + public static class TL_encryptedChatRequested_layer131 extends TL_encryptedChatRequested { public static int constructor = 0x62718a82; @@ -28886,8 +30001,8 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); stream.writeByteArray(g_a); } } @@ -28911,8 +30026,8 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); stream.writeByteArray(g_a); stream.writeByteArray(nonce); } @@ -28936,13 +30051,13 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); stream.writeByteArray(g_a); } } - public static class TL_encryptedChat extends EncryptedChat { + public static class TL_encryptedChat_layer131 extends TL_encryptedChat { public static int constructor = 0xfa56ce36; @@ -28961,8 +30076,8 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); stream.writeByteArray(g_a_or_b); stream.writeInt64(key_fingerprint); } @@ -28988,8 +30103,8 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); stream.writeByteArray(g_a_or_b); stream.writeByteArray(nonce); stream.writeInt64(key_fingerprint); @@ -29010,7 +30125,7 @@ public class TLRPC { } } - public static class TL_encryptedChatWaiting extends EncryptedChat { + public static class TL_encryptedChatWaiting_layer131 extends TL_encryptedChatWaiting { public static int constructor = 0x3bf703dc; @@ -29027,8 +30142,8 @@ public class TLRPC { stream.writeInt32(id); stream.writeInt64(access_hash); stream.writeInt32(date); - stream.writeInt32(admin_id); - stream.writeInt32(participant_id); + stream.writeInt32((int) admin_id); + stream.writeInt32((int) participant_id); } } @@ -29064,7 +30179,87 @@ public class TLRPC { } } - public static abstract class messages_FoundStickerSets extends TLObject { + public static class TL_encryptedChat extends EncryptedChat { + public static int constructor = 0x61f0d4c7; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt32(exception); + access_hash = stream.readInt64(exception); + date = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); + g_a_or_b = stream.readByteArray(exception); + key_fingerprint = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(id); + stream.writeInt64(access_hash); + stream.writeInt32(date); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); + stream.writeByteArray(g_a_or_b); + stream.writeInt64(key_fingerprint); + } + } + + public static class TL_encryptedChatRequested extends EncryptedChat { + public static int constructor = 0x48f1d94c; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + if ((flags & 1) != 0) { + folder_id = stream.readInt32(exception); + } + id = stream.readInt32(exception); + access_hash = stream.readInt64(exception); + date = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); + g_a = stream.readByteArray(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + if ((flags & 1) != 0) { + stream.writeInt32(folder_id); + } + stream.writeInt32(id); + stream.writeInt64(access_hash); + stream.writeInt32(date); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); + stream.writeByteArray(g_a); + } + } + + public static class TL_encryptedChatWaiting extends EncryptedChat { + public static int constructor = 0x66b25953; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt32(exception); + access_hash = stream.readInt64(exception); + date = stream.readInt32(exception); + admin_id = stream.readInt64(exception); + participant_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(id); + stream.writeInt64(access_hash); + stream.writeInt32(date); + stream.writeInt64(admin_id); + stream.writeInt64(participant_id); + } + } + + public static abstract class messages_FoundStickerSets extends TLObject { public static messages_FoundStickerSets TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { messages_FoundStickerSets result = null; @@ -29072,9 +30267,9 @@ public class TLRPC { case 0xd54b65d: result = new TL_messages_foundStickerSetsNotModified(); break; - case 0x5108d648: - result = new TL_messages_foundStickerSets(); - break; + case 0x8af09dd2: + result = new TL_messages_foundStickerSets(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in messages_FoundStickerSets", constructor)); @@ -29095,73 +30290,73 @@ public class TLRPC { } } - public static class TL_messages_foundStickerSets extends messages_FoundStickerSets { - public static int constructor = 0x5108d648; + public static class TL_messages_foundStickerSets extends messages_FoundStickerSets { + public static int constructor = 0x8af09dd2; - public int hash; - public ArrayList sets = new ArrayList<>(); + public long hash; + public ArrayList sets = new ArrayList<>(); - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - StickerSetCovered object = StickerSetCovered.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - sets.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = sets.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - sets.get(a).serializeToStream(stream); - } - } - } - - public static class TL_contact extends TLObject { - public static int constructor = 0xf911c994; - - public int user_id; - public boolean mutual; - - public static TL_contact TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_contact.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_contact", constructor)); - } else { - return null; - } - } - TL_contact result = new TL_contact(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - mutual = stream.readBool(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + StickerSetCovered object = StickerSetCovered.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + sets.add(object); + } + } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); - stream.writeBool(mutual); - } - } + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = sets.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + sets.get(a).serializeToStream(stream); + } + } + } + + public static class TL_contact extends TLObject { + public static int constructor = 0x145ade0b; + + public long user_id; + public boolean mutual; + + public static TL_contact TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_contact.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_contact", constructor)); + } else { + return null; + } + } + TL_contact result = new TL_contact(); + result.readParams(stream, exception); + return result; + } + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + mutual = stream.readBool(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeBool(mutual); + } + } public static class TL_groupCallParticipantVideoSourceGroup extends TLObject { public static int constructor = 0xdcb118b7; @@ -29831,19 +31026,26 @@ public class TLRPC { } public static abstract class InputChannel extends TLObject { - public int channel_id; + + public long channel_id; public long access_hash; public static InputChannel TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { InputChannel result = null; switch (constructor) { + case 0x2a286531: + result = new TL_inputChannelFromMessage_layer131(); + break; + case 0xafeb712e: + result = new TL_inputChannel_layer131(); + break; + case 0xf35aec28: + result = new TL_inputChannel(); + break; case 0xee8c1e86: result = new TL_inputChannelEmpty(); break; - case 0xafeb712e: - result = new TL_inputChannel(); - break; - case 0x2a286531: + case 0x5b934f9d: result = new TL_inputChannelFromMessage(); break; } @@ -29857,36 +31059,9 @@ public class TLRPC { } } - public static class TL_inputChannelEmpty extends InputChannel { - public static int constructor = 0xee8c1e86; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_inputChannel extends InputChannel { - public static int constructor = 0xafeb712e; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); - access_hash = stream.readInt64(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(channel_id); - stream.writeInt64(access_hash); - } - } - - public static class TL_inputChannelFromMessage extends InputChannel { + public static class TL_inputChannelFromMessage_layer131 extends TL_inputChannelFromMessage { public static int constructor = 0x2a286531; - public InputPeer peer; - public int msg_id; public void readParams(AbstractSerializedData stream, boolean exception) { peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); @@ -29898,7 +31073,68 @@ public class TLRPC { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(msg_id); - stream.writeInt32(channel_id); + stream.writeInt32((int) channel_id); + } + } + + public static class TL_inputChannel_layer131 extends TL_inputChannel { + public static int constructor = 0xafeb712e; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt32(exception); + access_hash = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) channel_id); + stream.writeInt64(access_hash); + } + } + + public static class TL_inputChannel extends InputChannel { + public static int constructor = 0xf35aec28; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + access_hash = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + stream.writeInt64(access_hash); + } + } + + public static class TL_inputChannelEmpty extends InputChannel { + public static int constructor = 0xee8c1e86; + + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + } + } + + public static class TL_inputChannelFromMessage extends InputChannel { + public static int constructor = 0x5b934f9d; + + public InputPeer peer; + public int msg_id; + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); + msg_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(msg_id); + stream.writeInt64(channel_id); } } @@ -30589,7 +31825,7 @@ public class TLRPC { public String slug; public String title; public Document document; - public TL_themeSettings settings; + public ThemeSettings settings; public int installs_count; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -30605,7 +31841,7 @@ public class TLRPC { document = Document.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 8) != 0) { - settings = TL_themeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); + settings = ThemeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 16) != 0) { installs_count = stream.readInt32(exception); @@ -30650,7 +31886,7 @@ public class TLRPC { document = Document.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 8) != 0) { - settings = TL_themeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); + settings = ThemeSettings.TLdeserialize(stream, stream.readInt32(exception), exception); } installs_count = stream.readInt32(exception); } @@ -31798,15 +33034,15 @@ public class TLRPC { public static abstract class ChannelParticipant extends TLObject { public Peer peer; - public int kicked_by; + public long kicked_by; public int date; public TL_channelBannedRights_layer92 banned_rights_layer92; - public int inviter_id; + public long inviter_id; public int flags; public boolean can_edit; public boolean self; public boolean left; - public int promoted_by; + public long promoted_by; public TL_channelAdminRights_layer92 admin_rights_layer92; public TL_chatAdminRights admin_rights; public TL_chatBannedRights banned_rights; @@ -31815,53 +33051,68 @@ public class TLRPC { public static ChannelParticipant TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { ChannelParticipant result = null; switch (constructor) { - case 0x1c0facaf: - result = new TL_channelParticipantBanned_layer125(); + case 0x222c1886: + result = new TL_channelParticipantBanned_layer92(); break; - case 0x1b03f006: - result = new TL_channelParticipantLeft(); - break; - case 0xc3c6796b: - result = new TL_channelParticipantLeft_layer125(); - break; - case 0x222c1886: - result = new TL_channelParticipantBanned_layer92(); - break; - case 0xe3e2e1f9: - result = new TL_channelParticipantCreator_layer103(); - break; - case 0x15ebac1d: - result = new TL_channelParticipant(); - break; - case 0x8cc5e69a: - result = new TL_channelParticipantKicked_layer67(); - break; - case 0xa3289a6d: - result = new TL_channelParticipantSelf(); - break; - case 0xccbebbaf: - result = new TL_channelParticipantAdmin(); + case 0x15ebac1d: + result = new TL_channelParticipant_layer131(); break; case 0x808d15a4: result = new TL_channelParticipantCreator_layer118(); break; - case 0x91057fef: - result = new TL_channelParticipantModerator_layer67(); - break; - case 0x98192d61: - result = new TL_channelParticipantEditor_layer67(); - break; case 0x447dca4b: + result = new TL_channelParticipantCreator_layer131(); + break; + case 0xe3e2e1f9: + result = new TL_channelParticipantCreator_layer103(); + break; + case 0xa3289a6d: + result = new TL_channelParticipantSelf_layer131(); + break; + case 0x6df8014e: + result = new TL_channelParticipantBanned(); + break; + case 0x34c3bb53: + result = new TL_channelParticipantAdmin(); + break; + case 0xc00c07c0: + result = new TL_channelParticipant(); + break; + case 0x2fe601d3: result = new TL_channelParticipantCreator(); break; - case 0xa82fa898: - result = new TL_channelParticipantAdmin_layer92(); - break; + case 0xccbebbaf: + result = new TL_channelParticipantAdmin_layer131(); + break; + case 0xa82fa898: + result = new TL_channelParticipantAdmin_layer92(); + break; + case 0x28a8bc67: + result = new TL_channelParticipantSelf(); + break; + case 0x50a1dfd6: + result = new TL_channelParticipantBanned_layer131(); + break; + case 0x98192d61: + result = new TL_channelParticipantEditor_layer67(); + break; + case 0x1b03f006: + result = new TL_channelParticipantLeft(); + break; + case 0x1c0facaf: + result = new TL_channelParticipantBanned_layer125(); + break; case 0x5daa6e23: result = new TL_channelParticipantAdmin_layer103(); break; - case 0x50a1dfd6: - result = new TL_channelParticipantBanned(); + case 0xc3c6796b: + result = new TL_channelParticipantLeft_layer125(); + break; + case 0x91057fef: + result = new TL_channelParticipantModerator_layer67(); + break; + case 0x8cc5e69a: + result = new TL_channelParticipantKicked_layer67(); break; } if (result == null && exception) { @@ -31874,6 +33125,130 @@ public class TLRPC { } } + public static class TL_channelParticipant extends ChannelParticipant { + public static int constructor = 0xc00c07c0; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer = new TLRPC.TL_peerUser(); + peer.user_id = stream.readInt64(exception); + date = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(peer.user_id); + stream.writeInt32(date); + } + } + + public static class TL_channelParticipantSelf extends ChannelParticipant { + public static int constructor = 0x28a8bc67; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer = new TLRPC.TL_peerUser(); + peer.user_id = stream.readInt64(exception); + inviter_id = stream.readInt64(exception); + date = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(peer.user_id); + stream.writeInt64(inviter_id); + stream.writeInt32(date); + } + } + + public static class TL_channelParticipantCreator extends ChannelParticipant { + public static int constructor = 0x2fe601d3; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + peer = new TLRPC.TL_peerUser(); + peer.user_id = stream.readInt64(exception); + admin_rights = TL_chatAdminRights.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 1) != 0) { + rank = stream.readString(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt64(peer.user_id); + admin_rights.serializeToStream(stream); + if ((flags & 1) != 0) { + stream.writeString(rank); + } + } + } + + public static class TL_channelParticipantAdmin extends ChannelParticipant { + public static int constructor = 0x34c3bb53; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + can_edit = (flags & 1) != 0; + self = (flags & 2) != 0; + peer = new TLRPC.TL_peerUser(); + peer.user_id = stream.readInt64(exception); + if ((flags & 2) != 0) { + inviter_id = stream.readInt64(exception); + } + promoted_by = stream.readInt64(exception); + date = stream.readInt32(exception); + admin_rights = TL_chatAdminRights.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 4) != 0) { + rank = stream.readString(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = can_edit ? (flags | 1) : (flags &~ 1); + flags = self ? (flags | 2) : (flags &~ 2); + stream.writeInt32(flags); + stream.writeInt64(peer.user_id); + if ((flags & 2) != 0) { + stream.writeInt64(inviter_id); + } + stream.writeInt64(promoted_by); + stream.writeInt32(date); + admin_rights.serializeToStream(stream); + if ((flags & 4) != 0) { + stream.writeString(rank); + } + } + } + + public static class TL_channelParticipantBanned extends ChannelParticipant { + public static int constructor = 0x6df8014e; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + left = (flags & 1) != 0; + peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + kicked_by = stream.readInt64(exception); + date = stream.readInt32(exception); + banned_rights = TL_chatBannedRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = left ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + peer.serializeToStream(stream); + stream.writeInt64(kicked_by); + stream.writeInt32(date); + banned_rights.serializeToStream(stream); + } + } + public static class TL_channelParticipantBanned_layer125 extends TL_channelParticipantBanned { public static int constructor = 0x1c0facaf; @@ -31892,8 +33267,8 @@ public class TLRPC { stream.writeInt32(constructor); flags = left ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); - stream.writeInt32(kicked_by); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) kicked_by); stream.writeInt32(date); banned_rights.serializeToStream(stream); } @@ -31924,11 +33299,11 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); } } - public static class TL_channelParticipantBanned extends ChannelParticipant { + public static class TL_channelParticipantBanned_layer131 extends TL_channelParticipantBanned { public static int constructor = 0x50a1dfd6; @@ -31946,7 +33321,7 @@ public class TLRPC { flags = left ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); peer.serializeToStream(stream); - stream.writeInt32(kicked_by); + stream.writeInt32((int) kicked_by); stream.writeInt32(date); banned_rights.serializeToStream(stream); } @@ -31963,11 +33338,11 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); } } - public static class TL_channelParticipant extends ChannelParticipant { + public static class TL_channelParticipant_layer131 extends TL_channelParticipant { public static int constructor = 0x15ebac1d; @@ -31979,7 +33354,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); stream.writeInt32(date); } } @@ -31997,13 +33372,13 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); - stream.writeInt32(kicked_by); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) kicked_by); stream.writeInt32(date); } } - public static class TL_channelParticipantSelf extends ChannelParticipant { + public static class TL_channelParticipantSelf_layer131 extends TL_channelParticipantSelf { public static int constructor = 0xa3289a6d; @@ -32016,13 +33391,13 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); - stream.writeInt32(inviter_id); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) inviter_id); stream.writeInt32(date); } } - public static class TL_channelParticipantAdmin extends ChannelParticipant { + public static class TL_channelParticipantAdmin_layer131 extends TL_channelParticipantAdmin { public static int constructor = 0xccbebbaf; @@ -32048,11 +33423,11 @@ public class TLRPC { flags = can_edit ? (flags | 1) : (flags &~ 1); flags = self ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); if ((flags & 2) != 0) { - stream.writeInt32(inviter_id); + stream.writeInt32((int) inviter_id); } - stream.writeInt32(promoted_by); + stream.writeInt32((int) promoted_by); stream.writeInt32(date); admin_rights.serializeToStream(stream); if ((flags & 4) != 0) { @@ -32077,14 +33452,14 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); if ((flags & 1) != 0) { stream.writeString(rank); } } } - public static class TL_channelParticipantCreator extends ChannelParticipant { + public static class TL_channelParticipantCreator_layer131 extends TL_channelParticipantCreator { public static int constructor = 0x447dca4b; @@ -32101,7 +33476,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); admin_rights.serializeToStream(stream); if ((flags & 1) != 0) { stream.writeString(rank); @@ -32122,8 +33497,8 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); - stream.writeInt32(inviter_id); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) inviter_id); stream.writeInt32(date); } } @@ -32141,8 +33516,8 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(peer.user_id); - stream.writeInt32(inviter_id); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) inviter_id); stream.writeInt32(date); } } @@ -32167,9 +33542,9 @@ public class TLRPC { stream.writeInt32(constructor); flags = can_edit ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); - stream.writeInt32(inviter_id); - stream.writeInt32(promoted_by); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) inviter_id); + stream.writeInt32((int) promoted_by); stream.writeInt32(date); admin_rights_layer92.serializeToStream(stream); } @@ -32198,11 +33573,11 @@ public class TLRPC { flags = can_edit ? (flags | 1) : (flags &~ 1); flags = self ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); + stream.writeInt32((int) peer.user_id); if ((flags & 2) != 0) { - stream.writeInt32(inviter_id); + stream.writeInt32((int) inviter_id); } - stream.writeInt32(promoted_by); + stream.writeInt32((int) promoted_by); stream.writeInt32(date); admin_rights.serializeToStream(stream); } @@ -32651,27 +34026,33 @@ public class TLRPC { public static abstract class ChatParticipants extends TLObject { public int flags; - public int chat_id; + public long chat_id; public ChatParticipant self_participant; public ArrayList participants = new ArrayList<>(); public int version; - public int admin_id; + public long admin_id; public static ChatParticipants TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { ChatParticipants result = null; switch (constructor) { - case 0xfc900c2b: - result = new TL_chatParticipantsForbidden(); - break; - case 0x3f460fed: - result = new TL_chatParticipants(); - break; - case 0x7841b415: - result = new TL_chatParticipants_old(); - break; - case 0xfd2bb8a: - result = new TL_chatParticipantsForbidden_old(); - break; + case 0xfc900c2b: + result = new TL_chatParticipantsForbidden_layer131(); + break; + case 0x3f460fed: + result = new TL_chatParticipants_layer131(); + break; + case 0x8763d3e1: + result = new TL_chatParticipantsForbidden(); + break; + case 0x3cbc93f8: + result = new TL_chatParticipants(); + break; + case 0x7841b415: + result = new TL_chatParticipants_old(); + break; + case 0xfd2bb8a: + result = new TL_chatParticipantsForbidden_old(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in ChatParticipants", constructor)); @@ -32683,117 +34064,176 @@ public class TLRPC { } } - public static class TL_chatParticipantsForbidden extends ChatParticipants { - public static int constructor = 0xfc900c2b; + public static class TL_chatParticipantsForbidden_layer131 extends TL_chatParticipantsForbidden { + public static int constructor = 0xfc900c2b; - public void readParams(AbstractSerializedData stream, boolean exception) { - flags = stream.readInt32(exception); - chat_id = stream.readInt32(exception); - if ((flags & 1) != 0) { - self_participant = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + chat_id = stream.readInt32(exception); + if ((flags & 1) != 0) { + self_participant = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(flags); - stream.writeInt32(chat_id); - if ((flags & 1) != 0) { - self_participant.serializeToStream(stream); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt32((int) chat_id); + if ((flags & 1) != 0) { + self_participant.serializeToStream(stream); + } + } + } - public static class TL_chatParticipants extends ChatParticipants { - public static int constructor = 0x3f460fed; + public static class TL_chatParticipants_layer131 extends TL_chatParticipants { + public static int constructor = 0x3f460fed; - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - ChatParticipant object = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - participants.add(object); - } - version = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt32(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + ChatParticipant object = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + participants.add(object); + } + version = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(0x1cb5c415); - int count = participants.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - participants.get(a).serializeToStream(stream); - } - stream.writeInt32(version); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) chat_id); + stream.writeInt32(0x1cb5c415); + int count = participants.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + participants.get(a).serializeToStream(stream); + } + stream.writeInt32(version); + } + } - public static class TL_chatParticipants_old extends TL_chatParticipants { - public static int constructor = 0x7841b415; + public static class TL_chatParticipantsForbidden extends ChatParticipants { + public static int constructor = 0x8763d3e1; - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - admin_id = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - ChatParticipant object = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - participants.add(object); - } - version = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + chat_id = stream.readInt64(exception); + if ((flags & 1) != 0) { + self_participant = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - stream.writeInt32(admin_id); - stream.writeInt32(0x1cb5c415); - int count = participants.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - participants.get(a).serializeToStream(stream); - } - stream.writeInt32(version); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(flags); + stream.writeInt64(chat_id); + if ((flags & 1) != 0) { + self_participant.serializeToStream(stream); + } + } + } - public static class TL_chatParticipantsForbidden_old extends TL_chatParticipantsForbidden { - public static int constructor = 0xfd2bb8a; + public static class TL_chatParticipants extends ChatParticipants { + public static int constructor = 0x3cbc93f8; - public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + ChatParticipant object = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + participants.add(object); + } + version = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + stream.writeInt32(0x1cb5c415); + int count = participants.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + participants.get(a).serializeToStream(stream); + } + stream.writeInt32(version); + } + } + + public static class TL_chatParticipants_old extends TL_chatParticipants { + public static int constructor = 0x7841b415; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt32(exception); + admin_id = stream.readInt32(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + ChatParticipant object = ChatParticipant.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + participants.add(object); + } + version = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) chat_id); + stream.writeInt32((int) admin_id); + stream.writeInt32(0x1cb5c415); + int count = participants.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + participants.get(a).serializeToStream(stream); + } + stream.writeInt32(version); + } + } + + public static class TL_chatParticipantsForbidden_old extends TL_chatParticipantsForbidden { + public static int constructor = 0xfd2bb8a; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) chat_id); + } + } public static class TL_game extends TLObject { public static int constructor = 0xbdf9653b; @@ -32859,7 +34299,7 @@ public class TLRPC { public String phone_number; public String first_name; public String last_name; - public int user_id; + public long user_id; public int thumb_w; public int thumb_h; public ArrayList attributes = new ArrayList<>(); @@ -32990,7 +34430,7 @@ public class TLRPC { stream.writeString(phone_number); stream.writeString(first_name); stream.writeString(last_name); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); } } @@ -33470,22 +34910,32 @@ public class TLRPC { } public static abstract class ChatParticipant extends TLObject { - public int user_id; - public int inviter_id; + + public long user_id; + public long inviter_id; public int date; public static ChatParticipant TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { ChatParticipant result = null; switch (constructor) { - case 0xc8d7493e: - result = new TL_chatParticipant(); - break; - case 0xda13538a: - result = new TL_chatParticipantCreator(); - break; - case 0xe2d6e436: - result = new TL_chatParticipantAdmin(); - break; + case 0xe2d6e436: + result = new TL_chatParticipantAdmin_layer131(); + break; + case 0xa0933f5b: + result = new TL_chatParticipantAdmin(); + break; + case 0xc8d7493e: + result = new TL_chatParticipant_layer131(); + break; + case 0xda13538a: + result = new TL_chatParticipantCreator_layer131(); + break; + case 0xc02d4007: + result = new TL_chatParticipant(); + break; + case 0xe46bcee4: + result = new TL_chatParticipantCreator(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in ChatParticipant", constructor)); @@ -33497,107 +34947,157 @@ public class TLRPC { } } - public static class TL_chatParticipant extends ChatParticipant { - public static int constructor = 0xc8d7493e; + public static class TL_chatParticipantAdmin_layer131 extends TL_chatParticipantAdmin { + public static int constructor = 0xe2d6e436; - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - inviter_id = stream.readInt32(exception); - date = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt32(exception); + inviter_id = stream.readInt32(exception); + date = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - stream.writeInt32(inviter_id); - stream.writeInt32(date); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) user_id); + stream.writeInt32((int) inviter_id); + stream.writeInt32(date); + } + } - public static class TL_chatParticipantCreator extends ChatParticipant { - public static int constructor = 0xda13538a; + public static class TL_chatParticipantAdmin extends ChatParticipant { + public static int constructor = 0xa0933f5b; - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + inviter_id = stream.readInt64(exception); + date = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeInt64(inviter_id); + stream.writeInt32(date); + } + } - public static class TL_chatParticipantAdmin extends ChatParticipant { - public static int constructor = 0xe2d6e436; + public static class TL_chatParticipant_layer131 extends TL_chatParticipant { + public static int constructor = 0xc8d7493e; - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - inviter_id = stream.readInt32(exception); - date = stream.readInt32(exception); - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt32(exception); + inviter_id = stream.readInt32(exception); + date = stream.readInt32(exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - stream.writeInt32(inviter_id); - stream.writeInt32(date); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) user_id); + stream.writeInt32((int) inviter_id); + stream.writeInt32(date); + } + } - public static class TL_webAuthorization extends TLObject { - public static int constructor = 0xcac943f2; + public static class TL_chatParticipantCreator_layer131 extends TL_chatParticipantCreator { + public static int constructor = 0xda13538a; - public long hash; - public int bot_id; - public String domain; - public String browser; - public String platform; - public int date_created; - public int date_active; - public String ip; - public String region; - public static TL_webAuthorization TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_webAuthorization.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_webAuthorization", constructor)); - } else { - return null; - } - } - TL_webAuthorization result = new TL_webAuthorization(); - result.readParams(stream, exception); - return result; - } + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt32(exception); + } - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt64(exception); - bot_id = stream.readInt32(exception); - domain = stream.readString(exception); - browser = stream.readString(exception); - platform = stream.readString(exception); - date_created = stream.readInt32(exception); - date_active = stream.readInt32(exception); - ip = stream.readString(exception); - region = stream.readString(exception); - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) user_id); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(hash); - stream.writeInt32(bot_id); - stream.writeString(domain); - stream.writeString(browser); - stream.writeString(platform); - stream.writeInt32(date_created); - stream.writeInt32(date_active); - stream.writeString(ip); - stream.writeString(region); - } - } + public static class TL_chatParticipant extends ChatParticipant { + public static int constructor = 0xc02d4007; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + inviter_id = stream.readInt64(exception); + date = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeInt64(inviter_id); + stream.writeInt32(date); + } + } + + public static class TL_chatParticipantCreator extends ChatParticipant { + public static int constructor = 0xe46bcee4; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + } + } + + public static class TL_webAuthorization extends TLObject { + public static int constructor = 0xa6f8f452; + + public long hash; + public long bot_id; + public String domain; + public String browser; + public String platform; + public int date_created; + public int date_active; + public String ip; + public String region; + + public static TL_webAuthorization TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_webAuthorization.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_webAuthorization", constructor)); + } else { + return null; + } + } + TL_webAuthorization result = new TL_webAuthorization(); + result.readParams(stream, exception); + return result; + } + + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + bot_id = stream.readInt64(exception); + domain = stream.readString(exception); + browser = stream.readString(exception); + platform = stream.readString(exception); + date_created = stream.readInt32(exception); + date_active = stream.readInt32(exception); + ip = stream.readString(exception); + region = stream.readString(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt64(bot_id); + stream.writeString(domain); + stream.writeString(browser); + stream.writeString(platform); + stream.writeInt32(date_created); + stream.writeInt32(date_active); + stream.writeString(ip); + stream.writeString(region); + } + } public static abstract class InputSecureFile extends TLObject { @@ -33795,7 +35295,7 @@ public class TLRPC { case 0x23209745: result = new TL_channelAdminLogEventActionStartGroupCall(); break; - case 0xa26f881b: + case 0x50c7ac8: result = new TL_channelAdminLogEventActionChangeLinkedChat(); break; case 0x1b7907ae: @@ -34254,20 +35754,20 @@ public class TLRPC { } public static class TL_channelAdminLogEventActionChangeLinkedChat extends ChannelAdminLogEventAction { - public static int constructor = 0xa26f881b; + public static int constructor = 0x50c7ac8; - public int prev_value; - public int new_value; + public long prev_value; + public long new_value; public void readParams(AbstractSerializedData stream, boolean exception) { - prev_value = stream.readInt32(exception); - new_value = stream.readInt32(exception); + prev_value = stream.readInt64(exception); + new_value = stream.readInt64(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(prev_value); - stream.writeInt32(new_value); + stream.writeInt64(prev_value); + stream.writeInt64(new_value); } } @@ -34737,7 +36237,7 @@ public class TLRPC { } public static abstract class Chat extends TLObject { - public int id; + public long id; public String title; public int date; public int flags; @@ -34775,72 +36275,87 @@ public class TLRPC { public TL_chatBannedRights default_banned_rights; public InputChannel migrated_to; - public static Chat TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - Chat result = null; - switch (constructor) { - case 0xfb0ccc41: - result = new TL_chatForbidden_old(); - break; - case 0x7312bc48: - result = new TL_chat_old2(); - break; - case 0x3bda1bde: - result = new TL_chat(); + public static Chat TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + Chat result = null; + switch (constructor) { + case 0x2d85832c: + result = new TL_channelForbidden_layer52(); + break; + case 0x9ba2d800: + result = new TL_chatEmpty_layer131(); + break; + case 0x7328bdb: + result = new TL_chatForbidden_layer131(); break; - case 0x289da732: - result = new TL_channelForbidden(); - break; - case 0x8537784f: - result = new TL_channelForbidden_layer67(); - break; - case 0x4b1b7506: - result = new TL_channel_layer48(); - break; - case 0x2d85832c: - result = new TL_channelForbidden_layer52(); - break; - case 0x7328bdb: - result = new TL_chatForbidden(); - break; - case 0xa14dca52: - result = new TL_channel_layer67(); - break; - case 0x678e9587: - result = new TL_channel_old(); - break; - case 0x6e9c9bc7: - result = new TL_chat_old(); - break; - case 0x9ba2d800: - result = new TL_chatEmpty(); - break; - case 0xcb44b1c: - result = new TL_channel_layer72(); - break; - case 0x450b7115: - result = new TL_channel_layer77(); - break; case 0x4df30834: result = new TL_channel_layer104(); break; + case 0x450b7115: + result = new TL_channel_layer77(); + break; + case 0x29562865: + result = new TL_chatEmpty(); + break; + case 0x41cbf256: + result = new TL_chat(); + break; case 0xd31a961e: + result = new TL_channel_layer131(); + break; + case 0x4b1b7506: + result = new TL_channel_layer48(); + break; + case 0x678e9587: + result = new TL_channel_old(); + break; + case 0xcb44b1c: + result = new TL_channel_layer72(); + break; + case 0x8537784f: + result = new TL_channelForbidden_layer67(); + break; + case 0xd91cdd54: + result = new TL_chat_layer92(); + break; + case 0xc88974ac: + result = new TL_channel_layer92(); + break; + case 0x17d493d5: + result = new TL_channelForbidden(); + break; + case 0x3bda1bde: + result = new TL_chat_layer131(); + break; + case 0x289da732: + result = new TL_channelForbidden_layer131(); + break; + case 0x7312bc48: + result = new TL_chat_old2(); + break; + case 0xa14dca52: + result = new TL_channel_layer67(); + break; + case 0x8261ac61: result = new TL_channel(); break; - case 0xc88974ac: - result = new TL_channel_layer92(); - break; - case 0xd91cdd54: - result = new TL_chat_layer92(); - break; - } - if (result == null && exception) { - throw new RuntimeException(String.format("can't parse magic %x in Chat", constructor)); - } - if (result != null) { - result.readParams(stream, exception); - } - return result; - } + case 0xfb0ccc41: + result = new TL_chatForbidden_old(); + break; + case 0x6e9c9bc7: + result = new TL_chat_old(); + break; + case 0x6592a1a7: + result = new TL_chatForbidden(); + break; + } + if (result == null && exception) { + throw new RuntimeException(String.format("can't parse magic %x in Chat", constructor)); + } + if (result != null) { + result.readParams(stream, exception); + } + return result; + } protected static TL_chatBannedRights mergeBannedRights(TL_channelBannedRights_layer92 rights) { if (rights == null) { @@ -34892,7 +36407,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); stream.writeInt32(date); } @@ -34922,7 +36437,7 @@ public class TLRPC { flags = left ? (flags | 4) : (flags &~ 4); flags = deactivated ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); photo.serializeToStream(stream); stream.writeInt32(participants_count); @@ -34932,6 +36447,62 @@ public class TLRPC { } public static class TL_chat extends Chat { + public static int constructor = 0x41cbf256; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + creator = (flags & 1) != 0; + kicked = (flags & 2) != 0; + left = (flags & 4) != 0; + deactivated = (flags & 32) != 0; + call_active = (flags & 8388608) != 0; + call_not_empty = (flags & 16777216) != 0; + id = stream.readInt64(exception); + title = stream.readString(exception); + photo = ChatPhoto.TLdeserialize(stream, stream.readInt32(exception), exception); + participants_count = stream.readInt32(exception); + date = stream.readInt32(exception); + version = stream.readInt32(exception); + if ((flags & 64) != 0) { + migrated_to = InputChannel.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 16384) != 0) { + admin_rights = TL_chatAdminRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 262144) != 0) { + default_banned_rights = TL_chatBannedRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = creator ? (flags | 1) : (flags &~ 1); + flags = kicked ? (flags | 2) : (flags &~ 2); + flags = left ? (flags | 4) : (flags &~ 4); + flags = deactivated ? (flags | 32) : (flags &~ 32); + flags = call_active ? (flags | 8388608) : (flags &~ 8388608); + flags = call_not_empty ? (flags | 16777216) : (flags &~ 16777216); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeString(title); + photo.serializeToStream(stream); + stream.writeInt32(participants_count); + stream.writeInt32(date); + stream.writeInt32(version); + if ((flags & 64) != 0) { + migrated_to.serializeToStream(stream); + } + if ((flags & 16384) != 0) { + admin_rights.serializeToStream(stream); + } + if ((flags & 262144) != 0) { + default_banned_rights.serializeToStream(stream); + } + } + } + + public static class TL_chat_layer131 extends TL_chat { public static int constructor = 0x3bda1bde; @@ -34969,7 +36540,7 @@ public class TLRPC { flags = call_active ? (flags | 8388608) : (flags &~ 8388608); flags = call_not_empty ? (flags | 16777216) : (flags &~ 16777216); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); photo.serializeToStream(stream); stream.writeInt32(participants_count); @@ -34987,7 +36558,37 @@ public class TLRPC { } } - public static class TL_channelForbidden extends Chat { + public static class TL_channelForbidden extends Chat { + public static int constructor = 0x17d493d5; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + broadcast = (flags & 32) != 0; + megagroup = (flags & 256) != 0; + id = stream.readInt64(exception); + access_hash = stream.readInt64(exception); + title = stream.readString(exception); + if ((flags & 65536) != 0) { + until_date = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = broadcast ? (flags | 32) : (flags &~ 32); + flags = megagroup ? (flags | 256) : (flags &~ 256); + stream.writeInt32(flags); + stream.writeInt64(id); + stream.writeInt64(access_hash); + stream.writeString(title); + if ((flags & 65536) != 0) { + stream.writeInt32(until_date); + } + } + } + + public static class TL_channelForbidden_layer131 extends TL_channelForbidden { public static int constructor = 0x289da732; @@ -35008,7 +36609,7 @@ public class TLRPC { flags = broadcast ? (flags | 32) : (flags &~ 32); flags = megagroup ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeInt64(access_hash); stream.writeString(title); if ((flags & 65536) != 0) { @@ -35035,7 +36636,7 @@ public class TLRPC { flags = broadcast ? (flags | 32) : (flags &~ 32); flags = megagroup ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeInt64(access_hash); stream.writeString(title); } @@ -35081,7 +36682,7 @@ public class TLRPC { flags = restricted ? (flags | 512) : (flags &~ 512); flags = signatures ? (flags | 2048) : (flags &~ 2048); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeInt64(access_hash); stream.writeString(title); if ((flags & 64) != 0) { @@ -35108,13 +36709,144 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeInt64(access_hash); stream.writeString(title); } } - public static class TL_chatForbidden extends Chat { + public static class TL_channel extends Chat { + public static int constructor = 0x8261ac61; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + creator = (flags & 1) != 0; + left = (flags & 4) != 0; + broadcast = (flags & 32) != 0; + verified = (flags & 128) != 0; + megagroup = (flags & 256) != 0; + restricted = (flags & 512) != 0; + signatures = (flags & 2048) != 0; + min = (flags & 4096) != 0; + scam = (flags & 524288) != 0; + has_link = (flags & 1048576) != 0; + has_geo = (flags & 2097152) != 0; + slowmode_enabled = (flags & 4194304) != 0; + call_active = (flags & 8388608) != 0; + call_not_empty = (flags & 16777216) != 0; + fake = (flags & 33554432) != 0; + gigagroup = (flags & 67108864) != 0; + id = stream.readInt64(exception); + if ((flags & 8192) != 0) { + access_hash = stream.readInt64(exception); + } + title = stream.readString(exception); + if ((flags & 64) != 0) { + username = stream.readString(exception); + } + photo = ChatPhoto.TLdeserialize(stream, stream.readInt32(exception), exception); + date = stream.readInt32(exception); + if ((flags & 512) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_restrictionReason object = TL_restrictionReason.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + restriction_reason.add(object); + } + } + if ((flags & 16384) != 0) { + admin_rights = TL_chatAdminRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 32768) != 0) { + banned_rights = TL_chatBannedRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 262144) != 0) { + default_banned_rights = TL_chatBannedRights.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 131072) != 0) { + participants_count = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = creator ? (flags | 1) : (flags &~ 1); + flags = left ? (flags | 4) : (flags &~ 4); + flags = broadcast ? (flags | 32) : (flags &~ 32); + flags = verified ? (flags | 128) : (flags &~ 128); + flags = megagroup ? (flags | 256) : (flags &~ 256); + flags = restricted ? (flags | 512) : (flags &~ 512); + flags = signatures ? (flags | 2048) : (flags &~ 2048); + flags = min ? (flags | 4096) : (flags &~ 4096); + flags = scam ? (flags | 524288) : (flags &~ 524288); + flags = has_link ? (flags | 1048576) : (flags &~ 1048576); + flags = has_geo ? (flags | 2097152) : (flags &~ 2097152); + flags = slowmode_enabled ? (flags | 4194304) : (flags &~ 4194304); + flags = call_active ? (flags | 8388608) : (flags &~ 8388608); + flags = call_not_empty ? (flags | 16777216) : (flags &~ 16777216); + flags = fake ? (flags | 33554432) : (flags &~ 33554432); + flags = gigagroup ? (flags | 67108864) : (flags &~ 67108864); + stream.writeInt32(flags); + stream.writeInt64(id); + if ((flags & 8192) != 0) { + stream.writeInt64(access_hash); + } + stream.writeString(title); + if ((flags & 64) != 0) { + stream.writeString(username); + } + photo.serializeToStream(stream); + stream.writeInt32(date); + if ((flags & 512) != 0) { + stream.writeInt32(0x1cb5c415); + int count = restriction_reason.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + restriction_reason.get(a).serializeToStream(stream); + } + } + if ((flags & 16384) != 0) { + admin_rights.serializeToStream(stream); + } + if ((flags & 32768) != 0) { + banned_rights.serializeToStream(stream); + } + if ((flags & 262144) != 0) { + default_banned_rights.serializeToStream(stream); + } + if ((flags & 131072) != 0) { + stream.writeInt32(participants_count); + } + } + } + + public static class TL_chatForbidden extends Chat { + public static int constructor = 0x6592a1a7; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt64(exception); + title = stream.readString(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(id); + stream.writeString(title); + } + } + + public static class TL_chatForbidden_layer131 extends TL_chatForbidden { public static int constructor = 0x7328bdb; @@ -35125,7 +36857,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); } } @@ -35174,7 +36906,7 @@ public class TLRPC { flags = signatures ? (flags | 2048) : (flags &~ 2048); flags = min ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35226,7 +36958,7 @@ public class TLRPC { flags = megagroup ? (flags | 256) : (flags &~ 256); flags = explicit_content ? (flags | 512) : (flags &~ 512); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeInt64(access_hash); stream.writeString(title); if ((flags & 64) != 0) { @@ -35253,7 +36985,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); photo.serializeToStream(stream); stream.writeInt32(participants_count); @@ -35263,7 +36995,7 @@ public class TLRPC { } } - public static class TL_channel extends Chat { + public static class TL_channel_layer131 extends TL_channel { public static int constructor = 0xd31a961e; @@ -35346,7 +37078,7 @@ public class TLRPC { flags = fake ? (flags | 33554432) : (flags &~ 33554432); flags = gigagroup ? (flags | 67108864) : (flags &~ 67108864); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35441,7 +37173,7 @@ public class TLRPC { flags = has_geo ? (flags | 2097152) : (flags &~ 2097152); flags = slowmode_enabled ? (flags | 4194304) : (flags &~ 4194304); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35489,8 +37221,8 @@ public class TLRPC { stream.writeInt32(constructor); flags = left ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); - stream.writeInt32(peer.user_id); - stream.writeInt32(kicked_by); + stream.writeInt32((int) peer.user_id); + stream.writeInt32((int) kicked_by); stream.writeInt32(date); banned_rights_layer92.serializeToStream(stream); } @@ -35547,7 +37279,7 @@ public class TLRPC { flags = signatures ? (flags | 2048) : (flags &~ 2048); flags = min ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35622,7 +37354,7 @@ public class TLRPC { flags = signatures ? (flags | 2048) : (flags &~ 2048); flags = min ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35696,7 +37428,7 @@ public class TLRPC { flags = signatures ? (flags | 2048) : (flags &~ 2048); flags = min ? (flags | 4096) : (flags &~ 4096); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); if ((flags & 8192) != 0) { stream.writeInt64(access_hash); } @@ -35749,7 +37481,7 @@ public class TLRPC { flags = left ? (flags | 4) : (flags &~ 4); flags = deactivated ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); - stream.writeInt32(id); + stream.writeInt32((int) id); stream.writeString(title); photo.serializeToStream(stream); stream.writeInt32(participants_count); @@ -36922,11 +38654,11 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } stream.writeInt32(date); if ((flags & 2) != 0) { - stream.writeInt32(from_id.channel_id); + stream.writeInt32((int) from_id.channel_id); } if ((flags & 4) != 0) { stream.writeInt32(channel_post); @@ -37033,14 +38765,14 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } if ((flags & 32) != 0) { stream.writeString(from_name); } stream.writeInt32(date); if ((flags & 2) != 0) { - stream.writeInt32(from_id.channel_id); + stream.writeInt32((int) from_id.channel_id); } if ((flags & 4) != 0) { stream.writeInt32(channel_post); @@ -37096,14 +38828,14 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } if ((flags & 32) != 0) { stream.writeString(from_name); } stream.writeInt32(date); if ((flags & 2) != 0) { - stream.writeInt32(from_id.channel_id); + stream.writeInt32((int) from_id.channel_id); } if ((flags & 4) != 0) { stream.writeInt32(channel_post); @@ -37147,11 +38879,11 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } stream.writeInt32(date); if ((flags & 2) != 0) { - stream.writeInt32(from_id.channel_id); + stream.writeInt32((int) from_id.channel_id); } if ((flags & 4) != 0) { stream.writeInt32(channel_post); @@ -37195,11 +38927,11 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } stream.writeInt32(date); if ((flags & 2) != 0) { - stream.writeInt32(from_id.channel_id); + stream.writeInt32((int) from_id.channel_id); } if ((flags & 4) != 0) { stream.writeInt32(channel_post); @@ -37356,7 +39088,7 @@ public class TLRPC { } public static abstract class messages_SavedGifs extends TLObject { - public int hash; + public long hash; public ArrayList gifs = new ArrayList<>(); public static messages_SavedGifs TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -37365,9 +39097,9 @@ public class TLRPC { case 0xe8025ca2: result = new TL_messages_savedGifsNotModified(); break; - case 0x2e0709a5: - result = new TL_messages_savedGifs(); - break; + case 0x84a02a0d: + result = new TL_messages_savedGifs(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in messages_SavedGifs", constructor)); @@ -37388,40 +39120,40 @@ public class TLRPC { } } - public static class TL_messages_savedGifs extends messages_SavedGifs { - public static int constructor = 0x2e0709a5; + public static class TL_messages_savedGifs extends messages_SavedGifs { + public static int constructor = 0x84a02a0d; - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - gifs.add(object); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + gifs.add(object); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = gifs.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - gifs.get(a).serializeToStream(stream); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = gifs.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + gifs.get(a).serializeToStream(stream); + } + } + } public static abstract class PhotoSize extends TLObject { public String type; @@ -37684,44 +39416,19 @@ public class TLRPC { } } - public static class TL_contactFound extends TLObject { - public static int constructor = 0xea879f95; - - public int user_id; - - public static TL_contactFound TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_contactFound.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_contactFound", constructor)); - } else { - return null; - } - } - TL_contactFound result = new TL_contactFound(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - } - } - public static abstract class ExportedChatInvite extends TLObject { public static ExportedChatInvite TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { ExportedChatInvite result = null; switch (constructor) { + case 0xb18105e8: + result = new TL_chatInviteExported(); + break; case 0x69df3769: result = new TL_chatInviteEmpty_layer122(); break; case 0x6e24fc9d: - result = new TL_chatInviteExported(); + result = new TL_chatInviteExported_layer131(); break; case 0xfc2e05bc: result = new TL_chatInviteExported_layer122(); @@ -37737,6 +39444,66 @@ public class TLRPC { } } + public static class TL_chatInviteExported extends ExportedChatInvite { + public static int constructor = 0xb18105e8; + + public int flags; + public boolean revoked; + public boolean permanent; + public String link; + public long admin_id; + public int date; + public int start_date; + public int expire_date; + public int usage_limit; + public int usage; + public ArrayList importers; //custom + public boolean expired; //custom + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + revoked = (flags & 1) != 0; + permanent = (flags & 32) != 0; + link = stream.readString(exception); + admin_id = stream.readInt64(exception); + date = stream.readInt32(exception); + if ((flags & 16) != 0) { + start_date = stream.readInt32(exception); + } + if ((flags & 2) != 0) { + expire_date = stream.readInt32(exception); + } + if ((flags & 4) != 0) { + usage_limit = stream.readInt32(exception); + } + if ((flags & 8) != 0) { + usage = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = revoked ? (flags | 1) : (flags &~ 1); + flags = permanent ? (flags | 32) : (flags &~ 32); + stream.writeInt32(flags); + stream.writeString(link); + stream.writeInt64(admin_id); + stream.writeInt32(date); + if ((flags & 16) != 0) { + stream.writeInt32(start_date); + } + if ((flags & 2) != 0) { + stream.writeInt32(expire_date); + } + if ((flags & 4) != 0) { + stream.writeInt32(usage_limit); + } + if ((flags & 8) != 0) { + stream.writeInt32(usage); + } + } + } + public static class TL_chatInviteEmpty_layer122 extends ExportedChatInvite { public static int constructor = 0x69df3769; @@ -37746,21 +39513,9 @@ public class TLRPC { } } - public static class TL_chatInviteExported extends ExportedChatInvite { + public static class TL_chatInviteExported_layer131 extends TL_chatInviteExported { public static int constructor = 0x6e24fc9d; - public int flags; - public boolean revoked; - public boolean permanent; - public String link; - public int admin_id; - public int date; - public int start_date; - public int expire_date; - public int usage_limit; - public int usage; - public ArrayList importers; //custom - public boolean expired; //custom public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); @@ -37789,7 +39544,7 @@ public class TLRPC { flags = permanent ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeString(link); - stream.writeInt32(admin_id); + stream.writeInt32((int) admin_id); stream.writeInt32(date); if ((flags & 16) != 0) { stream.writeInt32(start_date); @@ -38416,18 +40171,18 @@ public class TLRPC { public boolean media_unread; public boolean silent; public int id; - public int user_id; + public long user_id; public String message; public int pts; public int pts_count; public MessageFwdHeader fwd_from; - public int via_bot_id; + public long via_bot_id; public TL_messageReplyHeader reply_to; public ArrayList entities = new ArrayList<>(); public MessageMedia media; public Update update; - public int from_id; - public int chat_id; + public long from_id; + public long chat_id; public int seq_start; public int ttl_period; @@ -38437,7 +40192,7 @@ public class TLRPC { case 0x74ae4240: result = new TL_updates(); break; - case 0xfaeff833: + case 0x313bc7f8: result = new TL_updateShortMessage(); break; case 0x9015e101: @@ -38446,7 +40201,7 @@ public class TLRPC { case 0x78d4dec1: result = new TL_updateShort(); break; - case 0x1157b858: + case 0x4d6deea5: result = new TL_updateShortChatMessage(); break; case 0x725b04c3: @@ -38522,7 +40277,7 @@ public class TLRPC { } public static class TL_updateShortMessage extends Updates { - public static int constructor = 0xfaeff833; + public static int constructor = 0x313bc7f8; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -38532,7 +40287,7 @@ public class TLRPC { media_unread = (flags & 32) != 0; silent = (flags & 8192) != 0; id = stream.readInt32(exception); - user_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); message = stream.readString(exception); pts = stream.readInt32(exception); pts_count = stream.readInt32(exception); @@ -38541,7 +40296,7 @@ public class TLRPC { fwd_from = MessageFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 2048) != 0) { - via_bot_id = stream.readInt32(exception); + via_bot_id = stream.readInt64(exception); } if ((flags & 8) != 0) { reply_to = TL_messageReplyHeader.TLdeserialize(stream, stream.readInt32(exception), exception); @@ -38617,7 +40372,7 @@ public class TLRPC { } public static class TL_updateShortChatMessage extends Updates { - public static int constructor = 0x1157b858; + public static int constructor = 0x4d6deea5; public void readParams(AbstractSerializedData stream, boolean exception) { @@ -38627,8 +40382,8 @@ public class TLRPC { media_unread = (flags & 32) != 0; silent = (flags & 8192) != 0; id = stream.readInt32(exception); - from_id = stream.readInt32(exception); - chat_id = stream.readInt32(exception); + from_id = stream.readInt64(exception); + chat_id = stream.readInt64(exception); message = stream.readString(exception); pts = stream.readInt32(exception); pts_count = stream.readInt32(exception); @@ -38637,7 +40392,7 @@ public class TLRPC { fwd_from = MessageFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 2048) != 0) { - via_bot_id = stream.readInt32(exception); + via_bot_id = stream.readInt64(exception); } if ((flags & 8) != 0) { reply_to = TL_messageReplyHeader.TLdeserialize(stream, stream.readInt32(exception), exception); @@ -39264,36 +41019,36 @@ public class TLRPC { } } - public static class TL_importedContact extends TLObject { - public static int constructor = 0xd0028438; + public static class TL_importedContact extends TLObject { + public static int constructor = 0xc13e3c50; - public int user_id; - public long client_id; + public long user_id; + public long client_id; - public static TL_importedContact TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_importedContact.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_importedContact", constructor)); - } else { - return null; - } - } - TL_importedContact result = new TL_importedContact(); - result.readParams(stream, exception); - return result; + public static TL_importedContact TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { + if (TL_importedContact.constructor != constructor) { + if (exception) { + throw new RuntimeException(String.format("can't parse magic %x in TL_importedContact", constructor)); + } else { + return null; + } + } + TL_importedContact result = new TL_importedContact(); + result.readParams(stream, exception); + return result; } public void readParams(AbstractSerializedData stream, boolean exception) { - user_id = stream.readInt32(exception); - client_id = stream.readInt64(exception); - } + user_id = stream.readInt64(exception); + client_id = stream.readInt64(exception); + } public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(user_id); - stream.writeInt64(client_id); - } - } + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeInt64(client_id); + } + } public static class TL_chatOnlines extends TLObject { public static int constructor = 0xf041e250; @@ -39328,9 +41083,9 @@ public class TLRPC { public static messages_RecentStickers TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { messages_RecentStickers result = null; switch (constructor) { - case 0x22f3afb3: - result = new TL_messages_recentStickers(); - break; + case 0x88d37c56: + result = new TL_messages_recentStickers(); + break; case 0xb17f890: result = new TL_messages_recentStickersNotModified(); break; @@ -39345,82 +41100,82 @@ public class TLRPC { } } - public static class TL_messages_recentStickers extends messages_RecentStickers { - public static int constructor = 0x22f3afb3; + public static class TL_messages_recentStickers extends messages_RecentStickers { + public static int constructor = 0x88d37c56; - public int hash; - public ArrayList packs = new ArrayList<>(); - public ArrayList stickers = new ArrayList<>(); - public ArrayList dates = new ArrayList<>(); + public long hash; + public ArrayList packs = new ArrayList<>(); + public ArrayList stickers = new ArrayList<>(); + public ArrayList dates = new ArrayList<>(); - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - TL_stickerPack object = TL_stickerPack.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - packs.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - stickers.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - dates.add(stream.readInt32(exception)); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_stickerPack object = TL_stickerPack.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + packs.add(object); + } + magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + stickers.add(object); + } + magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + dates.add(stream.readInt32(exception)); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = packs.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - packs.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = stickers.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stickers.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = dates.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(dates.get(a)); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = packs.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + packs.get(a).serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + count = stickers.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stickers.get(a).serializeToStream(stream); + } + stream.writeInt32(0x1cb5c415); + count = dates.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt32(dates.get(a)); + } + } + } public static class TL_messages_recentStickersNotModified extends messages_RecentStickers { public static int constructor = 0xb17f890; @@ -39536,9 +41291,9 @@ public class TLRPC { case 0xf1749a22: result = new TL_messages_stickersNotModified(); break; - case 0xe4599bbd: - result = new TL_messages_stickers(); - break; + case 0x30a6ec7e: + result = new TL_messages_stickers(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in messages_Stickers", constructor)); @@ -39559,48 +41314,50 @@ public class TLRPC { } } - public static class TL_messages_stickers extends messages_Stickers { - public static int constructor = 0xe4599bbd; + public static class TL_messages_stickers extends messages_Stickers { + public static int constructor = 0x30a6ec7e; - public int hash; - public ArrayList stickers = new ArrayList<>(); + public long hash; + public ArrayList stickers = new ArrayList<>(); - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - stickers.add(object); - } - } + public void readParams(AbstractSerializedData stream, boolean exception) { + hash = stream.readInt64(exception); + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + stickers.add(object); + } + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = stickers.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stickers.get(a).serializeToStream(stream); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + stream.writeInt32(0x1cb5c415); + int count = stickers.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stickers.get(a).serializeToStream(stream); + } + } + } public static abstract class InputPeer extends TLObject { - public int user_id; - public int chat_id; - public int channel_id; + public InputPeer peer; + public int msg_id; + public long user_id; + public long channel_id; + public long chat_id; public long access_hash; public static InputPeer TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -39609,24 +41366,39 @@ public class TLRPC { case 0x7da07ec9: result = new TL_inputPeerSelf(); break; - case 0x7b8e7de6: + case 0xa87b0a1c: + result = new TL_inputPeerUserFromMessage(); + break; + case 0xdde8a54c: result = new TL_inputPeerUser(); break; case 0x179be863: - result = new TL_inputPeerChat(); + result = new TL_inputPeerChat_layer131(); break; - case 0x17bae2e6: - result = new TL_inputPeerUserFromMessage(); - break; - case 0x9c95f7bb: - result = new TL_inputPeerChannelFromMessage(); - break; - case 0x20adaef8: + case 0x27bcbbfc: result = new TL_inputPeerChannel(); break; + case 0x7b8e7de6: + result = new TL_inputPeerUser_layer131(); + break; case 0x7f3b18ea: result = new TL_inputPeerEmpty(); break; + case 0xbd2a0840: + result = new TL_inputPeerChannelFromMessage(); + break; + case 0x35a95cb9: + result = new TL_inputPeerChat(); + break; + case 0x20adaef8: + result = new TL_inputPeerChannel_layer131(); + break; + case 0x9c95f7bb: + result = new TL_inputPeerChannelFromMessage_layer131(); + break; + case 0x17bae2e6: + result = new TL_inputPeerUserFromMessage_layer131(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in InputPeer", constructor)); @@ -39647,7 +41419,71 @@ public class TLRPC { } } + public static class TL_inputPeerUserFromMessage extends InputPeer { + public static int constructor = 0xa87b0a1c; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); + msg_id = stream.readInt32(exception); + user_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(msg_id); + stream.writeInt64(user_id); + } + } + public static class TL_inputPeerUser extends InputPeer { + public static int constructor = 0xdde8a54c; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + user_id = stream.readInt64(exception); + access_hash = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(user_id); + stream.writeInt64(access_hash); + } + } + + public static class TL_inputPeerChat_layer131 extends TL_inputPeerChat { + public static int constructor = 0x179be863; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) chat_id); + } + } + + public static class TL_inputPeerChannel extends InputPeer { + public static int constructor = 0x27bcbbfc; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt64(exception); + access_hash = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(channel_id); + stream.writeInt64(access_hash); + } + } + + public static class TL_inputPeerUser_layer131 extends TL_inputPeerUser { public static int constructor = 0x7b8e7de6; @@ -39658,30 +41494,89 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(user_id); + stream.writeInt32((int) user_id); stream.writeInt64(access_hash); } } - public static class TL_inputPeerChat extends InputPeer { - public static int constructor = 0x179be863; + public static class TL_inputPeerEmpty extends InputPeer { + public static int constructor = 0x7f3b18ea; + + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + } + } + + public static class TL_inputPeerChannelFromMessage extends InputPeer { + public static int constructor = 0xbd2a0840; public void readParams(AbstractSerializedData stream, boolean exception) { - chat_id = stream.readInt32(exception); + peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); + msg_id = stream.readInt32(exception); + channel_id = stream.readInt64(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + peer.serializeToStream(stream); + stream.writeInt32(msg_id); + stream.writeInt64(channel_id); } } - public static class TL_inputPeerUserFromMessage extends InputPeer { + public static class TL_inputPeerChat extends InputPeer { + public static int constructor = 0x35a95cb9; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + chat_id = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + } + } + + public static class TL_inputPeerChannel_layer131 extends TL_inputPeerChannel { + public static int constructor = 0x20adaef8; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + channel_id = stream.readInt32(exception); + access_hash = stream.readInt64(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32((int) channel_id); + stream.writeInt64(access_hash); + } + } + + public static class TL_inputPeerChannelFromMessage_layer131 extends TL_inputPeerChannelFromMessage { + public static int constructor = 0x9c95f7bb; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); + msg_id = stream.readInt32(exception); + channel_id = stream.readInt32(exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(msg_id); + stream.writeInt32((int) channel_id); + } + } + + public static class TL_inputPeerUserFromMessage_layer131 extends TL_inputPeerUserFromMessage { public static int constructor = 0x17bae2e6; - public InputPeer peer; - public int msg_id; public void readParams(AbstractSerializedData stream, boolean exception) { peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); @@ -39693,52 +41588,7 @@ public class TLRPC { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(msg_id); - stream.writeInt32(user_id); - } - } - - public static class TL_inputPeerChannelFromMessage extends InputPeer { - public static int constructor = 0x9c95f7bb; - - public InputPeer peer; - public int msg_id; - - public void readParams(AbstractSerializedData stream, boolean exception) { - peer = InputPeer.TLdeserialize(stream, stream.readInt32(exception), exception); - msg_id = stream.readInt32(exception); - channel_id = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(msg_id); - stream.writeInt32(channel_id); - } - } - - public static class TL_inputPeerChannel extends InputPeer { - public static int constructor = 0x20adaef8; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - channel_id = stream.readInt32(exception); - access_hash = stream.readInt64(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(channel_id); - stream.writeInt64(access_hash); - } - } - - public static class TL_inputPeerEmpty extends InputPeer { - public static int constructor = 0x7f3b18ea; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); + stream.writeInt32((int) user_id); } } @@ -40865,29 +42715,29 @@ public class TLRPC { } } - public static class TL_auth_importAuthorization extends TLObject { - public static int constructor = 0xe3ef9613; + public static class TL_auth_importAuthorization extends TLObject { + public static int constructor = 0xa57a7dad; - public int id; - public byte[] bytes; + public long id; + public byte[] bytes; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return auth_Authorization.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return auth_Authorization.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { + public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); - stream.writeByteArray(bytes); - } - } + stream.writeInt64(id); + stream.writeByteArray(bytes); + } + } public static class TL_auth_exportLoginToken extends TLObject { - public static int constructor = 0xb1b41517; + public static int constructor = 0xb7e085fe; public int api_id; public String api_hash; - public ArrayList except_ids = new ArrayList<>(); + public ArrayList except_ids = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return auth_LoginToken.TLdeserialize(stream, constructor, exception); @@ -40901,7 +42751,7 @@ public class TLRPC { int count = except_ids.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(except_ids.get(a)); + stream.writeInt64(except_ids.get(a)); } } } @@ -40952,7 +42802,7 @@ public class TLRPC { } public static class TL_account_registerDevice extends TLObject { - public static int constructor = 0x68976c6f; + public static int constructor = 0xec86017a; public int flags; public boolean no_muted; @@ -40960,7 +42810,7 @@ public class TLRPC { public String token; public boolean app_sandbox; public byte[] secret; - public ArrayList other_uids = new ArrayList<>(); + public ArrayList other_uids = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return Bool.TLdeserialize(stream, constructor, exception); @@ -40978,34 +42828,34 @@ public class TLRPC { int count = other_uids.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(other_uids.get(a)); + stream.writeInt64(other_uids.get(a)); } } } - public static class TL_account_unregisterDevice extends TLObject { - public static int constructor = 0x3076c4bf; + public static class TL_account_unregisterDevice extends TLObject { + public static int constructor = 0x6a0d3206; - public int token_type; - public String token; - public ArrayList other_uids = new ArrayList<>(); + public int token_type; + public String token; + public ArrayList other_uids = new ArrayList<>(); - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return Bool.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(token_type); - stream.writeString(token); - stream.writeInt32(0x1cb5c415); - int count = other_uids.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(other_uids.get(a)); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(token_type); + stream.writeString(token); + stream.writeInt32(0x1cb5c415); + int count = other_uids.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(other_uids.get(a)); + } + } + } public static class TL_account_updateNotifySettings extends TLObject { public static int constructor = 0x84be5b93; @@ -41095,9 +42945,9 @@ public class TLRPC { } public static class TL_account_getWallPapers extends TLObject { - public static int constructor = 0xaabb1763; + public static int constructor = 0x7967d36; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return account_WallPapers.TLdeserialize(stream, constructor, exception); @@ -41105,7 +42955,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(hash); + stream.writeInt64(hash); } } @@ -41235,20 +43085,20 @@ public class TLRPC { } } - public static class TL_contacts_getContacts extends TLObject { - public static int constructor = 0xc023849f; + public static class TL_contacts_getContacts extends TLObject { + public static int constructor = 0x5dd69e12; - public int hash; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return contacts_Contacts.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return contacts_Contacts.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_contacts_importContacts extends TLObject { public static int constructor = 0x2c800be5; @@ -41530,7 +43380,7 @@ public class TLRPC { } public static class TL_messages_getDialogs extends TLObject { - public static int constructor = 0xa0ee3b73; + public static int constructor = 0xa0f4cb4f; public int flags; public boolean exclude_pinned; @@ -41539,7 +43389,7 @@ public class TLRPC { public int offset_id; public InputPeer offset_peer; public int limit; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return messages_Dialogs.TLdeserialize(stream, constructor, exception); @@ -41556,39 +43406,41 @@ public class TLRPC { stream.writeInt32(offset_id); offset_peer.serializeToStream(stream); stream.writeInt32(limit); - stream.writeInt32(hash); + stream.writeInt64(hash); } } - public static class TL_messages_getHistory extends TLObject { - public static int constructor = 0xafa92846; + public static class TL_messages_getHistory extends TLObject { + public static int constructor = 0x4423e6c5; - public InputPeer peer; - public int offset_id; - public int offset_date; - public int add_offset; - public int limit; - public int max_id; - public int min_id; + public InputPeer peer; + public int offset_id; + public int offset_date; + public int add_offset; + public int limit; + public int max_id; + public int min_id; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_Messages.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_Messages.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(offset_id); - stream.writeInt32(offset_date); - stream.writeInt32(add_offset); - stream.writeInt32(limit); - stream.writeInt32(max_id); - stream.writeInt32(min_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(offset_id); + stream.writeInt32(offset_date); + stream.writeInt32(add_offset); + stream.writeInt32(limit); + stream.writeInt32(max_id); + stream.writeInt32(min_id); + stream.writeInt64(hash); + } + } public static class TL_messages_search extends TLObject { - public static int constructor = 0xc352eec; + public static int constructor = 0xa0fda762; public int flags; public InputPeer peer; @@ -41603,7 +43455,7 @@ public class TLRPC { public int limit; public int max_id; public int min_id; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return messages_Messages.TLdeserialize(stream, constructor, exception); @@ -41628,7 +43480,7 @@ public class TLRPC { stream.writeInt32(limit); stream.writeInt32(max_id); stream.writeInt32(min_id); - stream.writeInt32(hash); + stream.writeInt64(hash); } } @@ -41914,39 +43766,39 @@ public class TLRPC { } } - public static class TL_messages_editChatAdmin extends TLObject { - public static int constructor = 0xa9e69f2e; + public static class TL_messages_editChatAdmin extends TLObject { + public static int constructor = 0xa85bd1c2; - public int chat_id; - public InputUser user_id; - public boolean is_admin; + public long chat_id; + public InputUser user_id; + public boolean is_admin; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return Bool.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - user_id.serializeToStream(stream); - stream.writeBool(is_admin); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + user_id.serializeToStream(stream); + stream.writeBool(is_admin); + } + } - public static class TL_messages_migrateChat extends TLObject { - public static int constructor = 0x15a3b8e3; + public static class TL_messages_migrateChat extends TLObject { + public static int constructor = 0xa2875319; - public int chat_id; + public long chat_id; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Updates.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return Updates.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(chat_id); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(chat_id); + } + } public static class TL_messages_searchGlobal extends TLObject { public static int constructor = 0x4bc6589a; @@ -42289,12 +44141,12 @@ public class TLRPC { } public static class TL_messages_getChats extends TLObject { - public static int constructor = 0x3c6aa187; + public static int constructor = 0x49e9528f; - public ArrayList id = new ArrayList<>(); + public ArrayList id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_messages_chats.TLdeserialize(stream, constructor, exception); + return messages_Chats.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { @@ -42303,15 +44155,15 @@ public class TLRPC { int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { - stream.writeInt32(id.get(a)); + stream.writeInt64(id.get(a)); } } } public static class TL_messages_getFullChat extends TLObject { - public static int constructor = 0x3b831c66; + public static int constructor = 0xaeb00b34; - public int chat_id; + public long chat_id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_messages_chatFull.TLdeserialize(stream, constructor, exception); @@ -42319,14 +44171,14 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); } } public static class TL_messages_editChatTitle extends TLObject { - public static int constructor = 0xdc452855; + public static int constructor = 0x73783ffd; - public int chat_id; + public long chat_id; public String title; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { @@ -42335,15 +44187,15 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); stream.writeString(title); } } public static class TL_messages_editChatPhoto extends TLObject { - public static int constructor = 0xca4c79d8; + public static int constructor = 0x35ddd674; - public int chat_id; + public long chat_id; public InputChatPhoto photo; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { @@ -42352,15 +44204,15 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); photo.serializeToStream(stream); } } public static class TL_messages_addChatUser extends TLObject { - public static int constructor = 0xf9a0aa09; + public static int constructor = 0xf24753e3; - public int chat_id; + public long chat_id; public InputUser user_id; public int fwd_limit; @@ -42370,18 +44222,18 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); user_id.serializeToStream(stream); stream.writeInt32(fwd_limit); } } public static class TL_messages_deleteChatUser extends TLObject { - public static int constructor = 0xc534459a; + public static int constructor = 0xa2185cab; public int flags; public boolean revoke_history; - public int chat_id; + public long chat_id; public InputUser user_id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { @@ -42392,7 +44244,7 @@ public class TLRPC { stream.writeInt32(constructor); flags = revoke_history ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); user_id.serializeToStream(stream); } } @@ -43020,7 +44872,7 @@ public class TLRPC { } public static class TL_contacts_getTopPeers extends TLObject { - public static int constructor = 0xd4982db5; + public static int constructor = 0x973478b6; public int flags; public boolean correspondents; @@ -43033,7 +44885,7 @@ public class TLRPC { public boolean channels; public int offset; public int limit; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return contacts_TopPeers.TLdeserialize(stream, constructor, exception); @@ -43052,7 +44904,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(offset); stream.writeInt32(limit); - stream.writeInt32(hash); + stream.writeInt64(hash); } } @@ -43316,29 +45168,29 @@ public class TLRPC { } } - public static class TL_account_getAuthorizationForm extends TLObject { - public static int constructor = 0xb86ba8e1; + public static class TL_account_getAuthorizationForm extends TLObject { + public static int constructor = 0xa929597a; - public int bot_id; - public String scope; - public String public_key; + public long bot_id; + public String scope; + public String public_key; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_account_authorizationForm.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return TL_account_authorizationForm.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(bot_id); - stream.writeString(scope); - stream.writeString(public_key); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(bot_id); + stream.writeString(scope); + stream.writeString(public_key); + } + } public static class TL_account_acceptAuthorization extends TLObject { - public static int constructor = 0xe7027c94; + public static int constructor = 0xf3ed4c73; - public int bot_id; + public long bot_id; public String scope; public String public_key; public ArrayList value_hashes = new ArrayList<>(); @@ -43350,7 +45202,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(bot_id); + stream.writeInt64(bot_id); stream.writeString(scope); stream.writeString(public_key); stream.writeInt32(0x1cb5c415); @@ -43787,10 +45639,10 @@ public class TLRPC { } public static class TL_account_getThemes extends TLObject { - public static int constructor = 0x285946f8; + public static int constructor = 0x7206e458; public String format; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return account_Themes.TLdeserialize(stream, constructor, exception); @@ -43799,25 +45651,10 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeString(format); - stream.writeInt32(hash); + stream.writeInt64(hash); } } - public static class TL_messages_getAllStickers extends TLObject { - public static int constructor = 0x1c9618b1; - - public int hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_AllStickers.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } - public static class TL_account_updateDeviceLocked extends TLObject { public static int constructor = 0x38df3532; @@ -44215,20 +46052,20 @@ public class TLRPC { } } - public static class TL_messages_getSavedGifs extends TLObject { - public static int constructor = 0x83bf3d52; + public static class TL_messages_getSavedGifs extends TLObject { + public static int constructor = 0x5cf09635; - public int hash; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_SavedGifs.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_SavedGifs.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_messages_saveGif extends TLObject { public static int constructor = 0x327a30cb; @@ -44501,20 +46338,20 @@ public class TLRPC { } } - public static class TL_messages_getFeaturedStickers extends TLObject { - public static int constructor = 0x2dacca4f; + public static class TL_messages_getFeaturedStickers extends TLObject { + public static int constructor = 0x64780b14; - public int hash; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_FeaturedStickers.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_FeaturedStickers.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_messages_readFeaturedStickers extends TLObject { public static int constructor = 0x5b118126; @@ -44536,24 +46373,24 @@ public class TLRPC { } } - public static class TL_messages_getRecentStickers extends TLObject { - public static int constructor = 0x5ea192c9; + public static class TL_messages_getRecentStickers extends TLObject { + public static int constructor = 0x9da9403b; - public int flags; - public boolean attached; - public int hash; + public int flags; + public boolean attached; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_RecentStickers.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_RecentStickers.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = attached ? (flags | 1) : (flags &~ 1); - stream.writeInt32(flags); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = attached ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + stream.writeInt64(hash); + } + } public static class TL_messages_saveRecentSticker extends TLObject { public static int constructor = 0x392718f8; @@ -44666,20 +46503,20 @@ public class TLRPC { } } - public static class TL_messages_getMaskStickers extends TLObject { - public static int constructor = 0x65b8c79f; + public static class TL_messages_getMaskStickers extends TLObject { + public static int constructor = 0x640f82b8; - public int hash; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_AllStickers.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_AllStickers.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_messages_getGameHighScores extends TLObject { public static int constructor = 0xe822649d; @@ -44741,44 +46578,44 @@ public class TLRPC { } } - public static class TL_messages_getCommonChats extends TLObject { - public static int constructor = 0xd0a48c4; + public static class TL_messages_getCommonChats extends TLObject { + public static int constructor = 0xe40ca104; - public InputUser user_id; - public int max_id; - public int limit; + public InputUser user_id; + public long max_id; + public int limit; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_Chats.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_Chats.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - user_id.serializeToStream(stream); - stream.writeInt32(max_id); - stream.writeInt32(limit); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + user_id.serializeToStream(stream); + stream.writeInt64(max_id); + stream.writeInt32(limit); + } + } - public static class TL_messages_getAllChats extends TLObject { - public static int constructor = 0xeba80ff0; + public static class TL_messages_getAllChats extends TLObject { + public static int constructor = 0x875f74be; - public ArrayList except_ids = new ArrayList<>(); + public ArrayList except_ids = new ArrayList<>(); - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_Chats.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_Chats.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = except_ids.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(except_ids.get(a)); - } - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt32(0x1cb5c415); + int count = except_ids.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + stream.writeInt64(except_ids.get(a)); + } + } + } public static class TL_messages_getWebPage extends TLObject { public static int constructor = 0x32ca8f91; @@ -44893,20 +46730,20 @@ public class TLRPC { } } - public static class TL_messages_getFavedStickers extends TLObject { - public static int constructor = 0x21ce0b0e; + public static class TL_messages_getFavedStickers extends TLObject { + public static int constructor = 0x4f1aaa9; - public int hash; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_FavedStickers.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_FavedStickers.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_messages_faveSticker extends TLObject { public static int constructor = 0xb9ffc55b; @@ -44965,24 +46802,24 @@ public class TLRPC { } } - public static class TL_messages_getRecentLocations extends TLObject { - public static int constructor = 0xbbc45b09; + public static class TL_messages_getRecentLocations extends TLObject { + public static int constructor = 0x702a40e0; - public InputPeer peer; - public int limit; - public int hash; + public InputPeer peer; + public int limit; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_Messages.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_Messages.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(limit); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + peer.serializeToStream(stream); + stream.writeInt32(limit); + stream.writeInt64(hash); + } + } public static class TL_messages_sendMultiMedia extends TLObject { public static int constructor = 0xcc0110cb; @@ -45358,10 +47195,10 @@ public class TLRPC { } public static class TL_messages_getScheduledHistory extends TLObject { - public static int constructor = 0xe2c2685b; + public static int constructor = 0xf516760b; public InputPeer peer; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return messages_Messages.TLdeserialize(stream, constructor, exception); @@ -45370,7 +47207,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); - stream.writeInt32(hash); + stream.writeInt64(hash); } } @@ -45657,11 +47494,11 @@ public class TLRPC { } public static class TL_messages_getOldFeaturedStickers extends TLObject { - public static int constructor = 0x5fe7025b; + public static int constructor = 0x7ed094a1; public int offset; public int limit; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return messages_FeaturedStickers.TLdeserialize(stream, constructor, exception); @@ -45671,12 +47508,12 @@ public class TLRPC { stream.writeInt32(constructor); stream.writeInt32(offset); stream.writeInt32(limit); - stream.writeInt32(hash); + stream.writeInt64(hash); } } public static class TL_messages_getReplies extends TLObject { - public static int constructor = 0x24b581ba; + public static int constructor = 0x22ddd30c; public InputPeer peer; public int msg_id; @@ -45686,7 +47523,7 @@ public class TLRPC { public int limit; public int max_id; public int min_id; - public int hash; + public long hash; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return messages_Messages.TLdeserialize(stream, constructor, exception); @@ -45702,7 +47539,7 @@ public class TLRPC { stream.writeInt32(limit); stream.writeInt32(max_id); stream.writeInt32(min_id); - stream.writeInt32(hash); + stream.writeInt64(hash); } } @@ -45924,9 +47761,9 @@ public class TLRPC { } public static class TL_messages_deleteChat extends TLObject { - public static int constructor = 0x83247d11; + public static int constructor = 0x5bd0ee50; - public int chat_id; + public long chat_id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return Bool.TLdeserialize(stream, constructor, exception); @@ -45934,7 +47771,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(chat_id); + stream.writeInt64(chat_id); } } @@ -46119,26 +47956,26 @@ public class TLRPC { } } - public static class TL_messages_searchStickerSets extends TLObject { - public static int constructor = 0xc2b7d08b; + public static class TL_messages_searchStickerSets extends TLObject { + public static int constructor = 0x35705b8a; - public int flags; - public boolean exclude_featured; - public String q; - public int hash; + public int flags; + public boolean exclude_featured; + public String q; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_FoundStickerSets.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_FoundStickerSets.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = exclude_featured ? (flags | 1) : (flags &~ 1); - stream.writeInt32(flags); - stream.writeString(q); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = exclude_featured ? (flags | 1) : (flags &~ 1); + stream.writeInt32(flags); + stream.writeString(q); + stream.writeInt64(hash); + } + } public static class TL_messages_markDialogUnread extends TLObject { public static int constructor = 0xc286d98f; @@ -46401,28 +48238,28 @@ public class TLRPC { } } - public static class TL_channels_getParticipants extends TLObject { - public static int constructor = 0x123e05e9; + public static class TL_channels_getParticipants extends TLObject { + public static int constructor = 0x77ced9d0; - public InputChannel channel; - public ChannelParticipantsFilter filter; - public int offset; - public int limit; - public int hash; + public InputChannel channel; + public ChannelParticipantsFilter filter; + public int offset; + public int limit; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return channels_ChannelParticipants.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return channels_ChannelParticipants.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - channel.serializeToStream(stream); - filter.serializeToStream(stream); - stream.writeInt32(offset); - stream.writeInt32(limit); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + channel.serializeToStream(stream); + filter.serializeToStream(stream); + stream.writeInt32(offset); + stream.writeInt32(limit); + stream.writeInt64(hash); + } + } public static class TL_channels_getParticipant extends TLObject { public static int constructor = 0xa0ab6cc6; @@ -47723,12 +49560,13 @@ public class TLRPC { } public static class TL_inputThemeSettings extends TLObject { - public static int constructor = 0xff38f912; + public static int constructor = 0x8fde504f; public int flags; public boolean message_colors_animated; public BaseTheme base_theme; public int accent_color; + public int outbox_accent_color; public ArrayList message_colors = new ArrayList<>(); public InputWallPaper wallpaper; public WallPaperSettings wallpaper_settings; @@ -47751,6 +49589,9 @@ public class TLRPC { message_colors_animated = (flags & 4) != 0; base_theme = BaseTheme.TLdeserialize(stream, stream.readInt32(exception), exception); accent_color = stream.readInt32(exception); + if ((flags & 8) != 0) { + outbox_accent_color = stream.readInt32(exception); + } if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { @@ -47778,6 +49619,9 @@ public class TLRPC { stream.writeInt32(flags); base_theme.serializeToStream(stream); stream.writeInt32(accent_color); + if ((flags & 8) != 0) { + stream.writeInt32(outbox_accent_color); + } if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = message_colors.size(); @@ -48240,7 +50084,7 @@ public class TLRPC { public String first_name; public String last_name; public String vcard; - public int user_id; + public long user_id; public WebPage webpage; public String venue_type; public boolean test; @@ -48330,8 +50174,11 @@ public class TLRPC { result = new TL_messageMediaDocument(); break; case 0xcbf24940: - result = new TL_messageMediaContact(); + result = new TL_messageMediaContact_layer131(); break; + case 0x70322949: + result = new TL_messageMediaContact(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in MessageMedia", constructor)); @@ -48662,8 +50509,8 @@ public class TLRPC { public int id; public long access_hash; public int date; - public int admin_id; - public int participant_id; + public long admin_id; + public long participant_id; public byte[] g_a; public byte[] nonce; public byte[] g_a_or_b; @@ -48671,7 +50518,7 @@ public class TLRPC { public boolean history_deleted; public byte[] a_or_b; //custom public byte[] auth_key; //custom - public int user_id; //custom + public long user_id; //custom public int ttl; //custom public int layer; //custom public int seq_in; //custom @@ -48696,10 +50543,10 @@ public class TLRPC { result = new TL_encryptedChatRequested_layer115(); break; case 0xfa56ce36: - result = new TL_encryptedChat(); + result = new TL_encryptedChat_layer131(); break; case 0x62718a82: - result = new TL_encryptedChatRequested(); + result = new TL_encryptedChatRequested_layer131(); break; case 0x6601d14f: result = new TL_encryptedChat_old(); @@ -48708,7 +50555,7 @@ public class TLRPC { result = new TL_encryptedChatEmpty(); break; case 0x3bf703dc: - result = new TL_encryptedChatWaiting(); + result = new TL_encryptedChatWaiting_layer131(); break; case 0x13d6dd27: result = new TL_encryptedChatDiscarded_layer122(); @@ -48716,6 +50563,15 @@ public class TLRPC { case 0x1e1c7c45: result = new TL_encryptedChatDiscarded(); break; + case 0x66b25953: + result = new TL_encryptedChatWaiting(); + break; + case 0x48f1d94c: + result = new TL_encryptedChatRequested(); + break; + case 0x61f0d4c7: + result = new TL_encryptedChat(); + break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in EncryptedChat", constructor)); @@ -48748,7 +50604,7 @@ public class TLRPC { public ReplyMarkup reply_markup; public int views; public int forwards; - public TL_messageReplies replies; + public MessageReplies replies; public int edit_date; public boolean silent; public boolean post; @@ -48757,7 +50613,7 @@ public class TLRPC { public boolean edit_hide; public boolean pinned; public MessageFwdHeader fwd_from; - public int via_bot_id; + public long via_bot_id; public TL_messageReplyHeader reply_to; public String post_author; public long grouped_id; @@ -48862,6 +50718,9 @@ public class TLRPC { result = new TL_message_layer123(); break; case 0xbce383d2: + result = new TL_message_layer131(); + break; + case 0x85d6cbe2: result = new TL_message(); break; case 0x9e19a1f6: @@ -48889,7 +50748,7 @@ public class TLRPC { return result; } - public void readAttachPath(AbstractSerializedData stream, int currentUserId) { + public void readAttachPath(AbstractSerializedData stream, long currentUserId) { boolean hasMedia = media != null && !(media instanceof TL_messageMediaEmpty) && !(media instanceof TL_messageMediaWebPage); boolean fixCaption = !TextUtils.isEmpty(message) && (media instanceof TL_messageMediaPhoto_old || @@ -49039,7 +50898,7 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); action.serializeToStream(stream); @@ -49124,14 +50983,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -49246,14 +51105,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -49362,7 +51221,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { @@ -49372,7 +51231,7 @@ public class TLRPC { stream.writeInt32(fwd_from.date); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -49475,7 +51334,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { @@ -49546,9 +51405,9 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); stream.writeString(message); @@ -49557,6 +51416,181 @@ public class TLRPC { } public static class TL_message extends Message { + public static int constructor = 0x85d6cbe2; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + flags = stream.readInt32(exception); + out = (flags & 2) != 0; + mentioned = (flags & 16) != 0; + media_unread = (flags & 32) != 0; + silent = (flags & 8192) != 0; + post = (flags & 16384) != 0; + from_scheduled = (flags & 262144) != 0; + legacy = (flags & 524288) != 0; + edit_hide = (flags & 2097152) != 0; + pinned = (flags & 16777216) != 0; + id = stream.readInt32(exception); + if ((flags & 256) != 0) { + from_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + } + peer_id = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); + if ((flags & 4) != 0) { + fwd_from = MessageFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 2048) != 0) { + via_bot_id = stream.readInt64(exception); + } + if ((flags & 8) != 0) { + reply_to = TL_messageReplyHeader.TLdeserialize(stream, stream.readInt32(exception), exception); + } + date = stream.readInt32(exception); + message = stream.readString(exception); + if ((flags & 512) != 0) { + media = MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); + if (media != null) { + ttl = media.ttl_seconds; + } + if (media != null && !TextUtils.isEmpty(media.captionLegacy)) { + message = media.captionLegacy; + } + } + if ((flags & 64) != 0) { + reply_markup = ReplyMarkup.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 128) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + MessageEntity object = MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + entities.add(object); + } + } + if ((flags & 1024) != 0) { + views = stream.readInt32(exception); + } + if ((flags & 1024) != 0) { + forwards = stream.readInt32(exception); + } + if ((flags & 8388608) != 0) { + replies = MessageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); + } + if ((flags & 32768) != 0) { + edit_date = stream.readInt32(exception); + } + if ((flags & 65536) != 0) { + post_author = stream.readString(exception); + } + if ((flags & 131072) != 0) { + grouped_id = stream.readInt64(exception); + } + if ((flags & 4194304) != 0) { + int magic = stream.readInt32(exception); + if (magic != 0x1cb5c415) { + if (exception) { + throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); + } + return; + } + int count = stream.readInt32(exception); + for (int a = 0; a < count; a++) { + TL_restrictionReason object = TL_restrictionReason.TLdeserialize(stream, stream.readInt32(exception), exception); + if (object == null) { + return; + } + restriction_reason.add(object); + } + } + if ((flags & 33554432) != 0) { + ttl_period = stream.readInt32(exception); + } + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + flags = out ? (flags | 2) : (flags &~ 2); + flags = mentioned ? (flags | 16) : (flags &~ 16); + flags = media_unread ? (flags | 32) : (flags &~ 32); + flags = silent ? (flags | 8192) : (flags &~ 8192); + flags = post ? (flags | 16384) : (flags &~ 16384); + flags = from_scheduled ? (flags | 262144) : (flags &~ 262144); + flags = legacy ? (flags | 524288) : (flags &~ 524288); + flags = edit_hide ? (flags | 2097152) : (flags &~ 2097152); + flags = pinned ? (flags | 16777216) : (flags &~ 16777216); + stream.writeInt32(flags); + stream.writeInt32(id); + if ((flags & 256) != 0) { + from_id.serializeToStream(stream); + } + peer_id.serializeToStream(stream); + if ((flags & 4) != 0) { + fwd_from.serializeToStream(stream); + } + if ((flags & 2048) != 0) { + stream.writeInt64(via_bot_id); + } + if ((flags & 8) != 0) { + reply_to.serializeToStream(stream); + } + stream.writeInt32(date); + stream.writeString(message); + if ((flags & 512) != 0) { + media.serializeToStream(stream); + } + if ((flags & 64) != 0) { + reply_markup.serializeToStream(stream); + } + if ((flags & 128) != 0) { + stream.writeInt32(0x1cb5c415); + int count = entities.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + entities.get(a).serializeToStream(stream); + } + } + if ((flags & 1024) != 0) { + stream.writeInt32(views); + } + if ((flags & 1024) != 0) { + stream.writeInt32(forwards); + } + if ((flags & 8388608) != 0) { + replies.serializeToStream(stream); + } + if ((flags & 32768) != 0) { + stream.writeInt32(edit_date); + } + if ((flags & 65536) != 0) { + stream.writeString(post_author); + } + if ((flags & 131072) != 0) { + stream.writeInt64(grouped_id); + } + if ((flags & 4194304) != 0) { + stream.writeInt32(0x1cb5c415); + int count = restriction_reason.size(); + stream.writeInt32(count); + for (int a = 0; a < count; a++) { + restriction_reason.get(a).serializeToStream(stream); + } + } + if ((flags & 33554432) != 0) { + stream.writeInt32(ttl_period); + } + writeAttachPath(stream); + } + } + + public static class TL_message_layer131 extends TL_message { public static int constructor = 0xbce383d2; @@ -49623,7 +51657,7 @@ public class TLRPC { forwards = stream.readInt32(exception); } if ((flags & 8388608) != 0) { - replies = TL_messageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); + replies = MessageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { edit_date = stream.readInt32(exception); @@ -49677,7 +51711,7 @@ public class TLRPC { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { reply_to.serializeToStream(stream); @@ -49798,7 +51832,7 @@ public class TLRPC { forwards = stream.readInt32(exception); } if ((flags & 8388608) != 0) { - replies = TL_messageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); + replies = MessageReplies.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { edit_date = stream.readInt32(exception); @@ -49849,7 +51883,7 @@ public class TLRPC { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { reply_to.serializeToStream(stream); @@ -50008,14 +52042,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -50168,14 +52202,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -50328,14 +52362,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -50477,14 +52511,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -50612,14 +52646,14 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 4) != 0) { fwd_from.serializeToStream(stream); } if ((flags & 2048) != 0) { - stream.writeInt32(via_bot_id); + stream.writeInt32((int) via_bot_id); } if ((flags & 8) != 0) { stream.writeInt32(reply_to.reply_to_msg_id); @@ -50721,10 +52755,10 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); if ((flags & 4) != 0) { - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); } if ((flags & 8) != 0) { @@ -50811,10 +52845,10 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); if ((flags & 4) != 0) { - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); } if ((flags & 8) != 0) { @@ -50874,7 +52908,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); stream.writeInt32(date); @@ -50926,10 +52960,10 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); if ((flags & 4) != 0) { - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); } if ((flags & 8) != 0) { @@ -50985,10 +53019,10 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); if ((flags & 4) != 0) { - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); } if ((flags & 8) != 0) { @@ -51031,7 +53065,7 @@ public class TLRPC { flags = media_unread ? (flags | 32) : (flags &~ 32); stream.writeInt32(flags); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); stream.writeString(message); @@ -51059,7 +53093,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeBool(out); stream.writeBool(unread); @@ -51096,9 +53130,9 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(id); - stream.writeInt32(fwd_from.from_id.user_id); + stream.writeInt32((int) fwd_from.from_id.user_id); stream.writeInt32(fwd_from.date); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeBool(out); stream.writeBool(unread); @@ -51131,7 +53165,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(id); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeBool(out); stream.writeBool(unread); @@ -51198,7 +53232,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(ttl); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); stream.writeString(message); @@ -51275,7 +53309,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(ttl); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); stream.writeString(message); @@ -51327,7 +53361,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(ttl); - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); peer_id.serializeToStream(stream); stream.writeInt32(date); stream.writeString(message); @@ -51473,7 +53507,7 @@ public class TLRPC { stream.writeInt32(flags); stream.writeInt32(id); if ((flags & 256) != 0) { - stream.writeInt32(from_id.user_id); + stream.writeInt32((int) from_id.user_id); } peer_id.serializeToStream(stream); if ((flags & 8) != 0) { @@ -51622,6 +53656,22 @@ public class TLRPC { //Chat start public static class TL_chatEmpty extends Chat { + public static int constructor = 0x29562865; + + + public void readParams(AbstractSerializedData stream, boolean exception) { + id = stream.readInt64(exception); + + title = "DELETED"; + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(id); + } + } + + public static class TL_chatEmpty_layer131 extends TL_chatEmpty { public static int constructor = 0x9ba2d800; @@ -51633,7 +53683,7 @@ public class TLRPC { public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); - stream.writeInt32(id); + stream.writeInt32((int) id); } } //Chat end @@ -51669,22 +53719,37 @@ public class TLRPC { } } - public static class TL_messages_getStickers extends TLObject { - public static int constructor = 0x43d4f2c; + public static class TL_messages_getStickers extends TLObject { + public static int constructor = 0xd5a5d3a1; - public String emoticon; - public int hash; + public String emoticon; + public long hash; - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_Stickers.TLdeserialize(stream, constructor, exception); - } + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_Stickers.TLdeserialize(stream, constructor, exception); + } - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(emoticon); - stream.writeInt32(hash); - } - } + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeString(emoticon); + stream.writeInt64(hash); + } + } + + public static class TL_messages_getAllStickers extends TLObject { + public static int constructor = 0xb8a0a1a8; + + public long hash; + + public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { + return messages_AllStickers.TLdeserialize(stream, constructor, exception); + } + + public void serializeToStream(AbstractSerializedData stream) { + stream.writeInt32(constructor); + stream.writeInt64(hash); + } + } public static class TL_upload_saveBigFilePart extends TLObject { public static int constructor = 0xde7b673d; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java index d22067847..6a2e75ac6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBar.java @@ -120,10 +120,18 @@ public class ActionBar extends FrameLayout { private boolean centerScale; private CharSequence subtitle; + private View.OnTouchListener interceptTouchEventListener; + private final Theme.ResourcesProvider resourcesProvider; + EllipsizeSpanAnimator ellipsizeSpanAnimator = new EllipsizeSpanAnimator(this); public ActionBar(Context context) { + this(context, null); + } + + public ActionBar(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setOnClickListener(v -> { if (isSearchFieldVisible()) { return; @@ -211,7 +219,7 @@ public class ActionBar extends FrameLayout { } } } - return super.onInterceptTouchEvent(ev); + return interceptTouchEventListener != null && interceptTouchEventListener.onTouch(this, ev) || super.onInterceptTouchEvent(ev); } protected boolean shouldClipChild(View child) { @@ -291,7 +299,7 @@ public class ActionBar extends FrameLayout { subtitleTextView = new SimpleTextView(getContext()); subtitleTextView.setGravity(Gravity.LEFT); subtitleTextView.setVisibility(GONE); - subtitleTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle)); + subtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle)); addView(subtitleTextView, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP)); } @@ -302,7 +310,7 @@ public class ActionBar extends FrameLayout { additionalSubtitleTextView = new SimpleTextView(getContext()); additionalSubtitleTextView.setGravity(Gravity.LEFT); additionalSubtitleTextView.setVisibility(GONE); - additionalSubtitleTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle)); + additionalSubtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle)); addView(additionalSubtitleTextView, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP)); } @@ -346,7 +354,7 @@ public class ActionBar extends FrameLayout { if (titleColorToSet != 0) { titleTextView[i].setTextColor(titleColorToSet); } else { - titleTextView[i].setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle)); + titleTextView[i].setTextColor(getThemedColor(Theme.key_actionBarDefaultTitle)); } titleTextView[i].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(titleTextView[i], 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP)); @@ -485,7 +493,7 @@ public class ActionBar extends FrameLayout { }; actionMode.isActionMode = true; actionMode.setClickable(true); - actionMode.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefault)); + actionMode.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefault)); addView(actionMode, indexOfChild(backButtonImageView)); actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionMode.getLayoutParams(); @@ -498,7 +506,7 @@ public class ActionBar extends FrameLayout { if (occupyStatusBar && needTop && actionModeTop == null) { actionModeTop = new View(getContext()); - actionModeTop.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultTop)); + actionModeTop.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultTop)); addView(actionModeTop); layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams(); layoutParams.height = AndroidUtilities.statusBarHeight; @@ -755,7 +763,7 @@ public class ActionBar extends FrameLayout { public void showActionModeTop() { if (occupyStatusBar && actionModeTop == null) { actionModeTop = new View(getContext()); - actionModeTop.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultTop)); + actionModeTop.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultTop)); addView(actionModeTop); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams(); layoutParams.height = AndroidUtilities.statusBarHeight; @@ -877,6 +885,10 @@ public class ActionBar extends FrameLayout { interceptTouches = value; } + public void setInterceptTouchEventListener(View.OnTouchListener listener) { + interceptTouchEventListener = listener; + } + public void setExtraHeight(int value) { extraHeight = value; if (actionMode != null) { @@ -1460,12 +1472,14 @@ public class ActionBar extends FrameLayout { public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) { if (startValues != null && startValues.view instanceof SimpleTextView) { AnimatorSet animatorSet = new AnimatorSet(); - Animator animator = super.createAnimator(sceneRoot, startValues, endValues); - float s = (float) startValues.values.get("text_size") / (float) endValues.values.get("text_size"); - startValues.view.setScaleX(s); - startValues.view.setScaleY(s); - if (animator != null) { - animatorSet.playTogether(animator); + if (startValues != null && endValues != null) { + Animator animator = super.createAnimator(sceneRoot, startValues, endValues); + float s = (float) startValues.values.get("text_size") / (float) endValues.values.get("text_size"); + startValues.view.setScaleX(s); + startValues.view.setScaleY(s); + if (animator != null) { + animatorSet.playTogether(animator); + } } animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_X, 1f)); animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_Y, 1f)); @@ -1495,4 +1509,12 @@ public class ActionBar extends FrameLayout { TransitionManager.beginDelayedTransition(this, transitionSet); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + if (color == null) { + color = parentFragment != null ? parentFragment.getThemedColor(key) : null; + } + return color != null ? color : Theme.getColor(key); + } } \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java index 4af6fec46..2d6a9fb8a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java @@ -24,9 +24,14 @@ import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; + import androidx.annotation.Keep; import android.os.SystemClock; + +import androidx.core.graphics.ColorUtils; +import androidx.core.math.MathUtils; + import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; @@ -54,14 +59,19 @@ import org.telegram.ui.Components.GroupCallPip; import org.telegram.ui.Components.LayoutHelper; import java.util.ArrayList; +import java.util.HashMap; public class ActionBarLayout extends FrameLayout { public interface ActionBarLayoutDelegate { boolean onPreIme(); + boolean needPresentFragment(BaseFragment fragment, boolean removeLast, boolean forceWithoutAnimation, ActionBarLayout layout); + boolean needAddFragmentToStack(BaseFragment fragment, ActionBarLayout layout); + boolean needCloseLastFragment(ActionBarLayout layout); + void onRebuildAllFragments(ActionBarLayout layout, boolean last); } @@ -209,11 +219,32 @@ public class ActionBarLayout extends FrameLayout { this.fragmentPanTranslationOffset = fragmentPanTranslationOffset; invalidate(); } + } - @Override - public void setTranslationX(float translationX) { - Log.d("kek", "set translationX" + translationX); - super.setTranslationX(translationX); + public static class ThemeAnimationSettings { + + public final Theme.ThemeInfo theme; + public final int accentId; + public final boolean nightTheme; + public final boolean instant; + public boolean onlyTopFragment; + public boolean applyTheme = true; + public Runnable afterStartDescriptionsAddedRunnable; + public Runnable beforeAnimationRunnable; + public Runnable afterAnimationRunnable; + public onAnimationProgress animationProgress; + public long duration = 200; + public Theme.ResourcesProvider resourcesProvider; + + public ThemeAnimationSettings(Theme.ThemeInfo theme, int accentId, boolean nightTheme, boolean instant) { + this.theme = theme; + this.accentId = accentId; + this.nightTheme = nightTheme; + this.instant = instant; + } + + public interface onAnimationProgress { + void setProgress(float p); } } @@ -256,6 +287,12 @@ public class ActionBarLayout extends FrameLayout { private boolean transitionAnimationPreviewMode; private ArrayList animateStartColors = new ArrayList<>(); private ArrayList animateEndColors = new ArrayList<>(); + + StartColorsProvider startColorsProvider = new StartColorsProvider(); + public Theme.MessageDrawable messageDrawableOutStart; + public Theme.MessageDrawable messageDrawableOutMediaStart; + public ThemeAnimationSettings.onAnimationProgress animationProgressListener; + private ArrayList> themeAnimatorDescriptions = new ArrayList<>(); private ArrayList presentingFragmentDescriptions; private ArrayList themeAnimatorDelegate = new ArrayList<>(); @@ -372,8 +409,18 @@ public class ActionBarLayout extends FrameLayout { invalidate(); if (fragmentsStack.size() >= 2 && containerView.getMeasuredWidth() > 0) { + float progress = value / containerView.getMeasuredWidth(); BaseFragment prevFragment = fragmentsStack.get(fragmentsStack.size() - 2); - prevFragment.onSlideProgress(false, value / containerView.getMeasuredWidth()); + prevFragment.onSlideProgress(false, progress); + BaseFragment currFragment = fragmentsStack.get(fragmentsStack.size() - 1); + if (currFragment.isBeginToShow()) { + int currNavigationBarColor = currFragment.getNavigationBarColor(); + int prevNavigationBarColor = prevFragment.getNavigationBarColor(); + if (currNavigationBarColor != prevNavigationBarColor) { + float ratio = MathUtils.clamp(2f * progress, 0f, 1f); + currFragment.setNavigationBarColor(ColorUtils.blendARGB(currNavigationBarColor, prevNavigationBarColor, ratio)); + } + } } } @@ -480,7 +527,7 @@ public class ActionBarLayout extends FrameLayout { layerShadowDrawable.setAlpha((int) (0xff * alpha)); layerShadowDrawable.draw(canvas); } else if (child == containerViewBack) { - float opacity = Math.min(0.8f, (width - translationX) / (float)width); + float opacity = Math.min(0.8f, (width - translationX) / (float) width); if (opacity < 0) { opacity = 0; } @@ -936,6 +983,12 @@ public class ActionBarLayout extends FrameLayout { if (oldFragment != null) { oldFragment.onTransitionAnimationProgress(false, animationProgress); } + Integer oldNavigationBarColor = oldFragment != null ? oldFragment.getNavigationBarColor() : null; + Integer newNavigationBarColor = newFragment != null ? newFragment.getNavigationBarColor() : null; + if (newFragment != null && !newFragment.inPreviewMode && oldNavigationBarColor != null) { + float ratio = MathUtils.clamp(2f * animationProgress - (open ? 1f : 0f), 0f, 1f); + newFragment.setNavigationBarColor(ColorUtils.blendARGB(oldNavigationBarColor, newNavigationBarColor, ratio)); + } float interpolated = decelerateInterpolator.getInterpolation(animationProgress); if (open) { containerView.setAlpha(interpolated); @@ -1635,7 +1688,7 @@ public class ActionBarLayout extends FrameLayout { b = Math.min(255, (int) (bS + (bE - bS) * value)); int color = Color.argb(a, r, g, b); ThemeDescription description = descriptions.get(i); - Theme.setAnimatedColor(description.getCurrentKey(), color); + description.setAnimatedColor(color); description.setColor(color, false, false); } } @@ -1643,6 +1696,7 @@ public class ActionBarLayout extends FrameLayout { ThemeDescription.ThemeDescriptionDelegate delegate = themeAnimatorDelegate.get(j); if (delegate != null) { delegate.didSetColor(); + delegate.onAnimationProgress(value); } } if (presentingFragmentDescriptions != null) { @@ -1652,6 +1706,9 @@ public class ActionBarLayout extends FrameLayout { description.setColor(Theme.getColor(key), false, false); } } + if (animationProgressListener != null) { + animationProgressListener.setProgress(value); + } } @Keep @@ -1688,11 +1745,15 @@ public class ActionBarLayout extends FrameLayout { } public void animateThemedValues(Theme.ThemeInfo theme, int accentId, boolean nightTheme, boolean instant) { + animateThemedValues(new ThemeAnimationSettings(theme, accentId, nightTheme, instant)); + } + + public void animateThemedValues(ThemeAnimationSettings settings) { if (transitionAnimationInProgress || startedTracking) { animateThemeAfterAnimation = true; - animateSetThemeAfterAnimation = theme; - animateSetThemeNightAfterAnimation = nightTheme; - animateSetThemeAccentIdAfterAnimation = accentId; + animateSetThemeAfterAnimation = settings.theme; + animateSetThemeNightAfterAnimation = settings.nightTheme; + animateSetThemeAccentIdAfterAnimation = settings.accentId; return; } if (themeAnimatorSet != null) { @@ -1700,7 +1761,8 @@ public class ActionBarLayout extends FrameLayout { themeAnimatorSet = null; } boolean startAnimation = false; - for (int i = 0; i < 2; i++) { + int fragmentCount = settings.onlyTopFragment ? 1 : 2; + for (int i = 0; i < fragmentCount; i++) { BaseFragment fragment; if (i == 0) { fragment = getLastFragment(); @@ -1712,6 +1774,15 @@ public class ActionBarLayout extends FrameLayout { } if (fragment != null) { startAnimation = true; + if (settings.resourcesProvider != null) { + if (messageDrawableOutStart == null) { + messageDrawableOutStart = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, true, false, startColorsProvider); + messageDrawableOutStart.isCrossfadeBackground = true; + messageDrawableOutMediaStart = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, true, false, startColorsProvider); + messageDrawableOutMediaStart.isCrossfadeBackground = true; + } + startColorsProvider.saveColors(settings.resourcesProvider); + } ArrayList descriptions = fragment.getThemeDescriptions(); addStartDescriptions(descriptions); if (fragment.visibleDialog instanceof BottomSheet) { @@ -1722,11 +1793,16 @@ public class ActionBarLayout extends FrameLayout { addStartDescriptions(dialog.getThemeDescriptions()); } if (i == 0) { - if (accentId != -1) { - theme.setCurrentAccentId(accentId); - Theme.saveThemeAccents(theme, true, false, true, false); + if (settings.applyTheme) { + if (settings.accentId != -1) { + settings.theme.setCurrentAccentId(settings.accentId); + Theme.saveThemeAccents(settings.theme, true, false, true, false); + } + Theme.applyTheme(settings.theme, settings.nightTheme); + } + if (settings.afterStartDescriptionsAddedRunnable != null) { + settings.afterStartDescriptionsAddedRunnable.run(); } - Theme.applyTheme(theme, nightTheme); } addEndDescriptions(descriptions); if (fragment.visibleDialog instanceof BottomSheet) { @@ -1743,16 +1819,26 @@ public class ActionBarLayout extends FrameLayout { fragment.clearViews(); fragment.setParentLayout(this); } - if (instant) { + if (settings.instant) { setThemeAnimationValue(1.0f); themeAnimatorDescriptions.clear(); animateStartColors.clear(); animateEndColors.clear(); themeAnimatorDelegate.clear(); presentingFragmentDescriptions = null; + if (settings.afterAnimationRunnable != null) { + settings.afterAnimationRunnable.run(); + } return; } Theme.setAnimatingColor(true); + if (settings.beforeAnimationRunnable != null) { + settings.beforeAnimationRunnable.run(); + } + animationProgressListener = settings.animationProgress; + if (animationProgressListener != null) { + animationProgressListener.setProgress(0); + } themeAnimatorSet = new AnimatorSet(); themeAnimatorSet.addListener(new AnimatorListenerAdapter() { @Override @@ -1765,6 +1851,9 @@ public class ActionBarLayout extends FrameLayout { Theme.setAnimatingColor(false); presentingFragmentDescriptions = null; themeAnimatorSet = null; + if (settings.afterAnimationRunnable != null) { + settings.afterAnimationRunnable.run(); + } } } @@ -1778,11 +1867,14 @@ public class ActionBarLayout extends FrameLayout { Theme.setAnimatingColor(false); presentingFragmentDescriptions = null; themeAnimatorSet = null; + if (settings.afterAnimationRunnable != null) { + settings.afterAnimationRunnable.run(); + } } } }); themeAnimatorSet.playTogether(ObjectAnimator.ofFloat(this, "themeAnimationValue", 0.0f, 1.0f)); - themeAnimatorSet.setDuration(200); + themeAnimatorSet.setDuration(settings.duration); themeAnimatorSet.start(); } } @@ -1965,4 +2057,35 @@ public class ActionBarLayout extends FrameLayout { } return null; } + + private class StartColorsProvider implements Theme.ResourcesProvider { + + HashMap colors = new HashMap<>(); + + String[] keysToSave = new String[]{ + Theme.key_chat_outBubble, + Theme.key_chat_outBubbleGradient1, + Theme.key_chat_outBubbleGradient2, + Theme.key_chat_outBubbleGradient3, + Theme.key_chat_outBubbleGradientAnimated, + Theme.key_chat_outBubbleShadow + }; + + @Override + public Integer getColor(String key) { + return colors.get(key); + } + + @Override + public Integer getCurrentColor(String key) { + return colors.get(key); + } + + public void saveColors(Theme.ResourcesProvider fragmentResourceProvider) { + colors.clear(); + for (String key : keysToSave) { + colors.put(key, fragmentResourceProvider.getCurrentColor(key)); + } + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenu.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenu.java index a422b0196..1357ef5bd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenu.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenu.java @@ -58,7 +58,11 @@ public class ActionBarMenu extends LinearLayout { } public ActionBarMenuItem addItem(int id, int icon) { - return addItem(id, icon, isActionMode ? parentActionBar.itemsActionModeBackgroundColor : parentActionBar.itemsBackgroundColor); + return addItem(id, icon, isActionMode ? parentActionBar.itemsActionModeBackgroundColor : parentActionBar.itemsBackgroundColor, null); + } + + public ActionBarMenuItem addItem(int id, int icon, Theme.ResourcesProvider resourcesProvider) { + return addItem(id, icon, isActionMode ? parentActionBar.itemsActionModeBackgroundColor : parentActionBar.itemsBackgroundColor, resourcesProvider); } public ActionBarMenuItem addItem(int id, CharSequence text) { @@ -66,7 +70,11 @@ public class ActionBarMenu extends LinearLayout { } public ActionBarMenuItem addItem(int id, int icon, int backgroundColor) { - return addItem(id, icon, null, backgroundColor, null, AndroidUtilities.dp(48), null); + return addItem(id, icon, backgroundColor, null); + } + + public ActionBarMenuItem addItem(int id, int icon, int backgroundColor, Theme.ResourcesProvider resourcesProvider) { + return addItem(id, icon, null, backgroundColor, null, AndroidUtilities.dp(48), null, resourcesProvider); } public ActionBarMenuItem addItemWithWidth(int id, int icon, int width) { @@ -78,7 +86,11 @@ public class ActionBarMenu extends LinearLayout { } public ActionBarMenuItem addItem(int id, int icon, CharSequence text, int backgroundColor, Drawable drawable, int width, CharSequence title) { - ActionBarMenuItem menuItem = new ActionBarMenuItem(getContext(), this, backgroundColor, isActionMode ? parentActionBar.itemsActionModeColor : parentActionBar.itemsColor, text != null); + return addItem(id, icon, text, backgroundColor, drawable, width, title, null); + } + + public ActionBarMenuItem addItem(int id, int icon, CharSequence text, int backgroundColor, Drawable drawable, int width, CharSequence title, Theme.ResourcesProvider resourcesProvider) { + ActionBarMenuItem menuItem = new ActionBarMenuItem(getContext(), this, backgroundColor, isActionMode ? parentActionBar.itemsActionModeColor : parentActionBar.itemsColor, text != null, resourcesProvider); menuItem.setTag(id); if (text != null) { menuItem.textView.setText(text); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuItem.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuItem.java index 847ba04e3..c153557e1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuItem.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuItem.java @@ -165,13 +165,23 @@ public class ActionBarMenuItem extends FrameLayout { private int notificationIndex = -1; private float transitionOffset; + private final Theme.ResourcesProvider resourcesProvider; public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor) { this(context, menu, backgroundColor, iconColor, false); } + public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor, Theme.ResourcesProvider resourcesProvider) { + this(context, menu, backgroundColor, iconColor, false, resourcesProvider); + } + public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor, boolean text) { + this(context, menu, backgroundColor, iconColor, text, null); + } + + public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor, boolean text, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; if (backgroundColor != 0) { setBackgroundDrawable(Theme.createSelectorDrawable(backgroundColor, text ? 5 : 1)); } @@ -325,7 +335,7 @@ public class ActionBarMenuItem extends FrameLayout { } rect = new Rect(); location = new int[2]; - popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext()); + popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext(), resourcesProvider); popupLayout.setOnTouchListener((v, event) -> { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { if (popupWindow != null && popupWindow.isShowing()) { @@ -388,7 +398,7 @@ public class ActionBarMenuItem extends FrameLayout { public TextView addSubItem(int id, CharSequence text) { createPopupLayout(); TextView textView = new TextView(getContext()); - textView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + textView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); textView.setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (!LocaleController.isRTL) { textView.setGravity(Gravity.CENTER_VERTICAL); @@ -435,6 +445,10 @@ public class ActionBarMenuItem extends FrameLayout { return addSubItem(id, icon, null, text, true, false); } + public ActionBarMenuSubItem addSubItem(int id, int icon, CharSequence text, Theme.ResourcesProvider resourcesProvider) { + return addSubItem(id, icon, null, text, true, false, resourcesProvider); + } + public ActionBarMenuSubItem addSubItem(int id, int icon, CharSequence text, boolean needCheck) { return addSubItem(id, icon, null, text, true, needCheck); } @@ -458,9 +472,13 @@ public class ActionBarMenuItem extends FrameLayout { } public ActionBarMenuSubItem addSubItem(int id, int icon, Drawable iconDrawable, CharSequence text, boolean dismiss, boolean needCheck) { + return addSubItem(id, icon, iconDrawable, text, dismiss, needCheck, null); + } + + public ActionBarMenuSubItem addSubItem(int id, int icon, Drawable iconDrawable, CharSequence text, boolean dismiss, boolean needCheck, Theme.ResourcesProvider resourcesProvider) { createPopupLayout(); - ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), needCheck, false, false); + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), needCheck, false, false, resourcesProvider); cell.setTextAndIcon(text, icon, iconDrawable); cell.setMinimumWidth(AndroidUtilities.dp(196)); cell.setTag(id); @@ -857,7 +875,7 @@ public class ActionBarMenuItem extends FrameLayout { } for (int i = 0; i < localFilters.size(); i++) { - SearchFilterView searchFilterView = new SearchFilterView(getContext()); + SearchFilterView searchFilterView = new SearchFilterView(getContext(), resourcesProvider); searchFilterView.setData(localFilters.get(i)); searchFilterView.setOnClickListener(view -> { int index = currentSearchFilters.indexOf(searchFilterView.getFilter()); @@ -1140,7 +1158,7 @@ public class ActionBarMenuItem extends FrameLayout { searchFieldCaption = new TextView(getContext()); searchFieldCaption.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - searchFieldCaption.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); + searchFieldCaption.setTextColor(getThemedColor(Theme.key_actionBarDefaultSearch)); searchFieldCaption.setSingleLine(true); searchFieldCaption.setEllipsize(TextUtils.TruncateAt.END); searchFieldCaption.setVisibility(GONE); @@ -1191,10 +1209,10 @@ public class ActionBarMenuItem extends FrameLayout { }; searchField.setScrollContainer(false); searchField.setCursorWidth(1.5f); - searchField.setCursorColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); + searchField.setCursorColor(getThemedColor(Theme.key_actionBarDefaultSearch)); searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); - searchField.setHintTextColor(Theme.getColor(Theme.key_actionBarDefaultSearchPlaceholder)); - searchField.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); + searchField.setHintTextColor(getThemedColor(Theme.key_actionBarDefaultSearchPlaceholder)); + searchField.setTextColor(getThemedColor(Theme.key_actionBarDefaultSearch)); searchField.setSingleLine(true); searchField.setBackgroundResource(0); searchField.setPadding(0, 0, 0, 0); @@ -1606,6 +1624,13 @@ public class ActionBarMenuItem extends FrameLayout { } } } + if (popupLayout != null) { + for (int i = 0; i < popupLayout.getItemsCount(); ++i) { + if (popupLayout.getItemAt(i) instanceof ActionBarMenuSubItem) { + ((ActionBarMenuSubItem) popupLayout.getItemAt(i)).setSelectorColor(getThemedColor(Theme.key_dialogButtonSelector)); + } + } + } } public void collapseSearchFilters() { @@ -1618,6 +1643,11 @@ public class ActionBarMenuItem extends FrameLayout { setTranslationX(0); } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + private static class SearchFilterView extends FrameLayout { Drawable thumbDrawable; @@ -1640,8 +1670,11 @@ public class ActionBarMenuItem extends FrameLayout { } }; - public SearchFilterView(Context context) { + private final Theme.ResourcesProvider resourcesProvider; + + public SearchFilterView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; avatarImageView = new BackupImageView(context); addView(avatarImageView, LayoutHelper.createFrame(32, 32)); @@ -1658,10 +1691,10 @@ public class ActionBarMenuItem extends FrameLayout { } private void updateColors() { - int defaultBackgroundColor = Theme.getColor(Theme.key_groupcreate_spanBackground); - int selectedBackgroundColor = Theme.getColor(Theme.key_avatar_backgroundBlue); - int textDefaultColor = Theme.getColor(Theme.key_windowBackgroundWhiteBlackText); - int textSelectedColor = Theme.getColor(Theme.key_avatar_actionBarIconBlue); + int defaultBackgroundColor = getThemedColor(Theme.key_groupcreate_spanBackground); + int selectedBackgroundColor = getThemedColor(Theme.key_avatar_backgroundBlue); + int textDefaultColor = getThemedColor(Theme.key_windowBackgroundWhiteBlackText); + int textSelectedColor = getThemedColor(Theme.key_avatar_actionBarIconBlue); shapeDrawable.getPaint().setColor(ColorUtils.blendARGB(defaultBackgroundColor, selectedBackgroundColor, selectedProgress)); titleView.setTextColor(ColorUtils.blendARGB(textDefaultColor, textSelectedColor, selectedProgress)); closeIconView.setColorFilter(textSelectedColor); @@ -1671,8 +1704,8 @@ public class ActionBarMenuItem extends FrameLayout { closeIconView.setScaleY(0.82f * selectedProgress); if (thumbDrawable != null) { - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); } avatarImageView.setAlpha(1f - selectedProgress); @@ -1686,16 +1719,16 @@ public class ActionBarMenuItem extends FrameLayout { this.data = data; titleView.setText(data.title); thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); if (data.filterType == FiltersView.FILTER_TYPE_CHAT) { if (data.chat instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) data.chat; if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) { CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundSaved), false); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundSaved), false); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); avatarImageView.setImageDrawable(combinedDrawable); } else { avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16)); @@ -1709,8 +1742,8 @@ public class ActionBarMenuItem extends FrameLayout { } else if (data.filterType == FiltersView.FILTER_TYPE_ARCHIVE) { CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); avatarImageView.setImageDrawable(combinedDrawable); } else { avatarImageView.setImageDrawable(thumbDrawable); @@ -1757,5 +1790,10 @@ public class ActionBarMenuItem extends FrameLayout { public FiltersView.MediaFilterData getFilter() { return data; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuSubItem.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuSubItem.java index 1eef0fe36..2d9686357 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuSubItem.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarMenuSubItem.java @@ -15,6 +15,8 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; +import org.telegram.ui.Components.CheckBox; +import org.telegram.ui.Components.CheckBox2; import org.telegram.ui.Components.LayoutHelper; public class ActionBarMenuSubItem extends FrameLayout { @@ -22,28 +24,42 @@ public class ActionBarMenuSubItem extends FrameLayout { private TextView textView; private TextView subtextView; private ImageView imageView; - private ImageView checkView; + private CheckBox2 checkView; private ImageView rightIcon; - private int textColor = Theme.getColor(Theme.key_actionBarDefaultSubmenuItem); - private int iconColor = Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon); - private int selectorColor = Theme.getColor(Theme.key_dialogButtonSelector); + private int textColor; + private int iconColor; + private int selectorColor; boolean top; boolean bottom; private int itemHeight = 48; + private final Theme.ResourcesProvider resourcesProvider; public ActionBarMenuSubItem(Context context, boolean top, boolean bottom) { this(context, false, top, bottom); } public ActionBarMenuSubItem(Context context, boolean needCheck, boolean top, boolean bottom) { + this(context, needCheck, top, bottom, null); + } + + public ActionBarMenuSubItem(Context context, boolean top, boolean bottom, Theme.ResourcesProvider resourcesProvider) { + this(context, false, top, bottom, resourcesProvider); + } + + public ActionBarMenuSubItem(Context context, boolean needCheck, boolean top, boolean bottom, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; this.top = top; this.bottom = bottom; + textColor = getThemedColor(Theme.key_actionBarDefaultSubmenuItem); + iconColor = getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon); + selectorColor = getThemedColor(Theme.key_dialogButtonSelector); + updateBackground(); setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); @@ -62,10 +78,10 @@ public class ActionBarMenuSubItem extends FrameLayout { addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL)); if (needCheck) { - checkView = new ImageView(context); - checkView.setImageResource(R.drawable.msg_text_check); - checkView.setScaleType(ImageView.ScaleType.CENTER); - checkView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); + checkView = new CheckBox2(context, 26, resourcesProvider); + checkView.setDrawUnchecked(false); + checkView.setColor(null, null, Theme.key_radioBackgroundChecked); + checkView.setDrawBackgroundAsArc(-1); addView(checkView, LayoutHelper.createFrame(26, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT))); } } @@ -78,15 +94,16 @@ public class ActionBarMenuSubItem extends FrameLayout { public void setItemHeight(int itemHeight) { this.itemHeight = itemHeight; } + public void setChecked(boolean checked) { if (checkView == null) { return; } - checkView.setVisibility(checked ? VISIBLE : INVISIBLE); + checkView.setChecked(checked, true); } - public void setCheckColor(int color) { - checkView.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); + public void setCheckColor(String colorKey) { + checkView.setColor(null, null, colorKey); } public void setRightIcon(int icon) { @@ -207,9 +224,14 @@ public class ActionBarMenuSubItem extends FrameLayout { updateBackground(); } - private void updateBackground() { + void updateBackground() { int topBackgroundRadius = top ? 6 : 0; int bottomBackgroundRadius = bottom ? 6 : 0; setBackground(Theme.createRadSelectorDrawable(selectorColor, topBackgroundRadius, bottomBackgroundRadius)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarPopupWindow.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarPopupWindow.java index 571feb664..d7ec53615 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarPopupWindow.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarPopupWindow.java @@ -12,6 +12,7 @@ import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; +import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; @@ -57,6 +58,7 @@ public class ActionBarPopupWindow extends PopupWindow { private boolean isClosingAnimated; private int currentAccount = UserConfig.selectedAccount; private boolean pauseNotifications; + private long outEmptyTime = -1; static { Field f = null; @@ -103,19 +105,25 @@ public class ActionBarPopupWindow extends PopupWindow { protected Drawable backgroundDrawable; private boolean fitItems; + private final Theme.ResourcesProvider resourcesProvider; public ActionBarPopupWindowLayout(Context context) { - this(context, R.drawable.popup_fixed_alert2); + this(context, null); } - public ActionBarPopupWindowLayout(Context context, int resId) { + public ActionBarPopupWindowLayout(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, R.drawable.popup_fixed_alert2, resourcesProvider); + } + + public ActionBarPopupWindowLayout(Context context, int resId, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; backgroundDrawable = getResources().getDrawable(resId).mutate(); if (backgroundDrawable != null) { backgroundDrawable.getPadding(bgPaddings); } - setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); setWillNotDraw(false); @@ -422,6 +430,11 @@ public class ActionBarPopupWindow extends PopupWindow { } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } public ActionBarPopupWindow() { @@ -616,20 +629,34 @@ public class ActionBarPopupWindow extends PopupWindow { isClosingAnimated = false; if (animationEnabled && animated) { isClosingAnimated = true; - ActionBarPopupWindowLayout content = (ActionBarPopupWindowLayout) getContentView(); - if (content.itemAnimators != null && !content.itemAnimators.isEmpty()) { - for (int a = 0, N = content.itemAnimators.size(); a < N; a++) { - AnimatorSet animatorSet = content.itemAnimators.get(a); - animatorSet.removeAllListeners(); - animatorSet.cancel(); + ViewGroup viewGroup = (ViewGroup) getContentView(); + ActionBarPopupWindowLayout content = null; + for (int i = 0; i < viewGroup.getChildCount(); i++) { + if (viewGroup.getChildAt(i) instanceof ActionBarPopupWindowLayout) { + content = (ActionBarPopupWindowLayout) viewGroup.getChildAt(i); + } + } + if (content != null) { + if (content.itemAnimators != null && !content.itemAnimators.isEmpty()) { + for (int a = 0, N = content.itemAnimators.size(); a < N; a++) { + AnimatorSet animatorSet = content.itemAnimators.get(a); + animatorSet.removeAllListeners(); + animatorSet.cancel(); + } + content.itemAnimators.clear(); } - content.itemAnimators.clear(); } windowAnimatorSet = new AnimatorSet(); - windowAnimatorSet.playTogether( - ObjectAnimator.ofFloat(content, View.TRANSLATION_Y, AndroidUtilities.dp(content.shownFromBotton ? 5 : -5)), - ObjectAnimator.ofFloat(content, View.ALPHA, 0.0f)); - windowAnimatorSet.setDuration(dismissAnimationDuration); + if (outEmptyTime > 0) { + windowAnimatorSet.playTogether(ValueAnimator.ofFloat(0, 1f)); + windowAnimatorSet.setDuration(outEmptyTime); + } else { + windowAnimatorSet.playTogether( + ObjectAnimator.ofFloat(viewGroup, View.TRANSLATION_Y, AndroidUtilities.dp((content != null && content.shownFromBotton) ? 5 : -5)), + ObjectAnimator.ofFloat(viewGroup, View.ALPHA, 0.0f)); + windowAnimatorSet.setDuration(dismissAnimationDuration); + } + windowAnimatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { @@ -660,4 +687,8 @@ public class ActionBarPopupWindow extends PopupWindow { unregisterListener(); } } + + public void setEmptyOutAnimation(long time) { + outEmptyTime = time; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AlertDialog.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AlertDialog.java index d103f45cc..e5982c48f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AlertDialog.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AlertDialog.java @@ -137,21 +137,24 @@ public class AlertDialog extends Dialog implements Drawable.Callback { private ArrayList itemViews = new ArrayList<>(); private float aspectRatio; private boolean dimEnabled = true; + private final Theme.ResourcesProvider resourcesProvider; public static class AlertDialogCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private TextView textView; private ImageView imageView; - public AlertDialogCell(Context context) { + public AlertDialogCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; - setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), 2)); + setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 2)); setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0); imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 40, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT))); textView = new TextView(context); @@ -159,7 +162,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { textView.setSingleLine(true); textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setEllipsize(TextUtils.TruncateAt.END); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL)); } @@ -188,15 +191,25 @@ public class AlertDialog extends Dialog implements Drawable.Callback { textView.setPadding(0, 0, 0, 0); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } public AlertDialog(Context context, int progressStyle) { + this(context, progressStyle, null); + } + + public AlertDialog(Context context, int progressStyle, Theme.ResourcesProvider resourcesProvider) { super(context, R.style.TransparentDialog); + this.resourcesProvider = resourcesProvider; backgroundPaddings = new Rect(); if (progressStyle != 3) { shadowDrawable = context.getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemeColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadowDrawable.getPadding(backgroundPaddings); } @@ -468,7 +481,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { titleTextView = new TextView(getContext()); titleTextView.setText(title); - titleTextView.setTextColor(getThemeColor(Theme.key_dialogTextBlack)); + titleTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); @@ -478,7 +491,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { if (secondTitle != null && title != null) { secondTitleTextView = new TextView(getContext()); secondTitleTextView.setText(secondTitle); - secondTitleTextView.setTextColor(getThemeColor(Theme.key_dialogTextGray3)); + secondTitleTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray3)); secondTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); secondTitleTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP); titleContainer.addView(secondTitleTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, 0, 21, 0, 0)); @@ -487,7 +500,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { if (subtitle != null) { subtitleTextView = new TextView(getContext()); subtitleTextView.setText(subtitle); - subtitleTextView.setTextColor(getThemeColor(Theme.key_dialogIcon)); + subtitleTextView.setTextColor(getThemedColor(Theme.key_dialogIcon)); subtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); containerView.addView(subtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 24, 0, 24, items != null ? 14 : 10)); @@ -517,7 +530,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { } }; contentScrollView.setVerticalScrollBarEnabled(false); - AndroidUtilities.setScrollViewEdgeEffectColor(contentScrollView, getThemeColor(Theme.key_dialogScrollGlow)); + AndroidUtilities.setScrollViewEdgeEffectColor(contentScrollView, getThemedColor(Theme.key_dialogScrollGlow)); containerView.addView(contentScrollView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0)); scrollContainer = new LinearLayout(getContext()); @@ -526,10 +539,10 @@ public class AlertDialog extends Dialog implements Drawable.Callback { } messageTextView = new TextView(getContext()); - messageTextView.setTextColor(getThemeColor(Theme.key_dialogTextBlack)); + messageTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); messageTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); - messageTextView.setLinkTextColor(getThemeColor(Theme.key_dialogTextLink)); + messageTextView.setLinkTextColor(getThemedColor(Theme.key_dialogTextLink)); if (!messageTextViewClickable) { messageTextView.setClickable(false); messageTextView.setEnabled(false); @@ -539,8 +552,8 @@ public class AlertDialog extends Dialog implements Drawable.Callback { progressViewContainer = new FrameLayout(getContext()); containerView.addView(progressViewContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 44, Gravity.LEFT | Gravity.TOP, 23, title == null ? 24 : 0, 23, 24)); - RadialProgressView progressView = new RadialProgressView(getContext()); - progressView.setProgressColor(getThemeColor(Theme.key_dialogProgressCircle)); + RadialProgressView progressView = new RadialProgressView(getContext(), resourcesProvider); + progressView.setProgressColor(getThemedColor(Theme.key_dialogProgressCircle)); progressViewContainer.addView(progressView, LayoutHelper.createFrame(44, 44, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP)); messageTextView.setLines(1); @@ -551,14 +564,14 @@ public class AlertDialog extends Dialog implements Drawable.Callback { lineProgressView = new LineProgressView(getContext()); lineProgressView.setProgress(currentProgress / 100.0f, false); - lineProgressView.setProgressColor(getThemeColor(Theme.key_dialogLineProgress)); - lineProgressView.setBackColor(getThemeColor(Theme.key_dialogLineProgressBackground)); + lineProgressView.setProgressColor(getThemedColor(Theme.key_dialogLineProgress)); + lineProgressView.setBackColor(getThemedColor(Theme.key_dialogLineProgressBackground)); containerView.addView(lineProgressView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 4, Gravity.LEFT | Gravity.CENTER_VERTICAL, 24, 0, 24, 0)); lineProgressViewPercent = new TextView(getContext()); lineProgressViewPercent.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); lineProgressViewPercent.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); - lineProgressViewPercent.setTextColor(getThemeColor(Theme.key_dialogTextGray2)); + lineProgressViewPercent.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); lineProgressViewPercent.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); containerView.addView(lineProgressViewPercent, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 23, 4, 23, 24)); updateLineProgressTextView(); @@ -567,11 +580,11 @@ public class AlertDialog extends Dialog implements Drawable.Callback { setCancelable(false); progressViewContainer = new FrameLayout(getContext()); - progressViewContainer.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(Theme.key_dialog_inlineProgressBackground))); + progressViewContainer.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(Theme.key_dialog_inlineProgressBackground))); containerView.addView(progressViewContainer, LayoutHelper.createLinear(86, 86, Gravity.CENTER)); - RadialProgressView progressView = new RadialProgressView(getContext()); - progressView.setProgressColor(getThemeColor(Theme.key_dialog_inlineProgress)); + RadialProgressView progressView = new RadialProgressView(getContext(), resourcesProvider); + progressView.setProgressColor(getThemedColor(Theme.key_dialog_inlineProgress)); progressViewContainer.addView(progressView, LayoutHelper.createLinear(86, 86)); } else { scrollContainer.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 24, 0, 24, customView != null || items != null ? customViewOffset : 0)); @@ -590,7 +603,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback { if (items[a] == null) { continue; } - AlertDialogCell cell = new AlertDialogCell(getContext()); + AlertDialogCell cell = new AlertDialogCell(getContext(), resourcesProvider); cell.setTextAndIcon(items[a], itemIcons != null ? itemIcons[a] : 0); cell.setTag(a); itemViews.add(cell); @@ -734,13 +747,13 @@ public class AlertDialog extends Dialog implements Drawable.Callback { textView.setMinWidth(AndroidUtilities.dp(64)); textView.setTag(Dialog.BUTTON_POSITIVE); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(getThemeColor(dialogButtonColorKey)); + textView.setTextColor(getThemedColor(dialogButtonColorKey)); textView.setGravity(Gravity.CENTER); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); // textView.setLines(1); // textView.setSingleLine(true); //TODO textView.setText(positiveButtonText.toString().toUpperCase()); - textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemeColor(dialogButtonColorKey))); + textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemedColor(dialogButtonColorKey))); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0); if (verticalButtons) { buttonsLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); @@ -774,13 +787,13 @@ public class AlertDialog extends Dialog implements Drawable.Callback { textView.setMinWidth(AndroidUtilities.dp(64)); textView.setTag(Dialog.BUTTON_NEGATIVE); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(getThemeColor(dialogButtonColorKey)); + textView.setTextColor(getThemedColor(dialogButtonColorKey)); textView.setGravity(Gravity.CENTER); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setSingleLine(true); textView.setText(negativeButtonText.toString().toUpperCase()); - textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemeColor(dialogButtonColorKey))); + textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemedColor(dialogButtonColorKey))); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0); if (verticalButtons) { buttonsLayout.addView(textView, 0, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); @@ -814,13 +827,13 @@ public class AlertDialog extends Dialog implements Drawable.Callback { textView.setMinWidth(AndroidUtilities.dp(64)); textView.setTag(Dialog.BUTTON_NEUTRAL); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(getThemeColor(dialogButtonColorKey)); + textView.setTextColor(getThemedColor(dialogButtonColorKey)); textView.setGravity(Gravity.CENTER); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setSingleLine(true); textView.setText(neutralButtonText.toString().toUpperCase()); - textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemeColor(dialogButtonColorKey))); + textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(getThemedColor(dialogButtonColorKey))); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0); if (verticalButtons) { buttonsLayout.addView(textView, 1, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); @@ -1168,8 +1181,9 @@ public class AlertDialog extends Dialog implements Drawable.Callback { positiveButtonListener = listener; } - protected int getThemeColor(String key) { - return Theme.getColor(key); + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); } public void showDelayed(long delay) { @@ -1190,11 +1204,15 @@ public class AlertDialog extends Dialog implements Drawable.Callback { } public Builder(Context context) { - alertDialog = new AlertDialog(context, 0); + this(context, null); } - public Builder(Context context, int progressViewStyle) { - alertDialog = new AlertDialog(context, progressViewStyle); + public Builder(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, 0, resourcesProvider); + } + + public Builder(Context context, int progressViewStyle, Theme.ResourcesProvider resourcesProvider) { + alertDialog = new AlertDialog(context, progressViewStyle, resourcesProvider); } public Context getContext() { @@ -1332,8 +1350,9 @@ public class AlertDialog extends Dialog implements Drawable.Callback { alertDialog.aspectRatio = aspectRatio; } - public void setDimEnabled(boolean dimEnabled) { + public Builder setDimEnabled(boolean dimEnabled) { alertDialog.dimEnabled = dimEnabled; + return this; } public void notDrawBackgroundOnTopView(boolean b) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java index f1df5ef05..8302b031c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java @@ -17,17 +17,19 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; -import android.os.SystemClock; +import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; +import android.view.Window; import android.view.accessibility.AccessibilityManager; import android.widget.FrameLayout; import org.telegram.messenger.AccountInstance; +import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ContactsController; import org.telegram.messenger.DownloadController; @@ -65,6 +67,8 @@ public abstract class BaseFragment { protected boolean hasOwnBackground = false; protected boolean isPaused = true; protected Dialog parentDialog; + protected boolean inTransitionAnimation = false; + protected boolean fragmentBeginToShow; public BaseFragment() { classGuid = ConnectionsManager.generateClassGuid(); @@ -215,11 +219,11 @@ public abstract class BaseFragment { protected ActionBar createActionBar(Context context) { ActionBar actionBar = new ActionBar(context); - actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault)); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSelector), false); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), true); - actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultIcon), false); - actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), true); + actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarDefault)); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSelector), false); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), true); + actionBar.setItemsColor(getThemedColor(Theme.key_actionBarDefaultIcon), false); + actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), true); if (inPreviewMode || inBubbleMode) { actionBar.setOccupyStatusBar(false); } @@ -435,11 +439,14 @@ public abstract class BaseFragment { } protected void onTransitionAnimationStart(boolean isOpen, boolean backward) { - + inTransitionAnimation = true; + if (isOpen) { + fragmentBeginToShow = true; + } } protected void onTransitionAnimationEnd(boolean isOpen, boolean backward) { - + inTransitionAnimation = false; } protected void onBecomeFullyVisible() { @@ -671,7 +678,40 @@ public abstract class BaseFragment { return actionBarLayout; } + public int getThemedColor(String key) { + return Theme.getColor(key); + } + + public Drawable getThemedDrawable(String key) { + return Theme.getThemeDrawable(key); + } + + public int getNavigationBarColor() { + return Theme.getColor(Theme.key_windowBackgroundGray); + } + + public void setNavigationBarColor(int color) { + Activity activity = getParentActivity(); + if (activity != null) { + Window window = activity.getWindow(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && window != null && window.getNavigationBarColor() != color) { + window.setNavigationBarColor(color); + final float brightness = AndroidUtilities.computePerceivedBrightness(color); + AndroidUtilities.setLightNavigationBar(window, brightness >= 0.721f); + } + } + } + + public boolean isBeginToShow() { + return fragmentBeginToShow; + } + private void setParentDialog(Dialog dialog) { parentDialog = dialog; } + + public Theme.ResourcesProvider getResourceProvider() { + return null; + } + } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheet.java index c466f0181..47b27b635 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheet.java @@ -157,6 +157,7 @@ public class BottomSheet extends Dialog { protected int navBarColor; private OnDismissListener onHideListener; + protected Theme.ResourcesProvider resourcesProvider; public void setDisableScroll(boolean b) { disableScroll = b; @@ -573,7 +574,7 @@ public class BottomSheet extends Dialog { super.dispatchDraw(canvas); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (navBarColorKey != null) { - backgroundPaint.setColor(Theme.getColor(navBarColorKey)); + backgroundPaint.setColor(getThemedColor(navBarColorKey)); } else { backgroundPaint.setColor(navBarColor); } @@ -603,7 +604,7 @@ public class BottomSheet extends Dialog { } if (containerView.getTranslationY() < 0) { - backgroundPaint.setColor(behindKeyboardColorKey != null ? Theme.getColor(behindKeyboardColorKey) : behindKeyboardColor); + backgroundPaint.setColor(behindKeyboardColorKey != null ? getThemedColor(behindKeyboardColorKey) : behindKeyboardColor); canvas.drawRect(containerView.getLeft() + backgroundPaddingLeft, containerView.getY() + containerView.getMeasuredHeight(), containerView.getRight() - backgroundPaddingLeft, getMeasuredHeight(), backgroundPaint); } } @@ -612,7 +613,7 @@ public class BottomSheet extends Dialog { protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (lastInsets != null && keyboardHeight != 0) { - backgroundPaint.setColor(behindKeyboardColorKey != null ? Theme.getColor(behindKeyboardColorKey) : behindKeyboardColor); + backgroundPaint.setColor(behindKeyboardColorKey != null ? getThemedColor(behindKeyboardColorKey) : behindKeyboardColor); canvas.drawRect(containerView.getLeft() + backgroundPaddingLeft, getMeasuredHeight() - keyboardHeight - (drawNavigationBar ? bottomInset : 0), containerView.getRight() - backgroundPaddingLeft, getMeasuredHeight() - (drawNavigationBar ? bottomInset : 0), backgroundPaint); } onContainerDraw(canvas); @@ -658,12 +659,18 @@ public class BottomSheet extends Dialog { public static class BottomSheetCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private TextView textView; private ImageView imageView; int currentType; public BottomSheetCell(Context context, int type) { + this(context, type, null); + } + + public BottomSheetCell(Context context, int type, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; currentType = type; setBackgroundDrawable(Theme.getSelectorDrawable(false)); @@ -671,7 +678,7 @@ public class BottomSheet extends Dialog { imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogIcon), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(56, 48, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT))); textView = new TextView(context); @@ -680,21 +687,21 @@ public class BottomSheet extends Dialog { textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setEllipsize(TextUtils.TruncateAt.END); if (type == 0) { - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL)); } else if (type == 1) { textView.setGravity(Gravity.CENTER); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } else if (type == 2) { textView.setGravity(Gravity.CENTER); - textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + textView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - textView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + textView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 16, 16, 16, 16)); } } @@ -757,6 +764,11 @@ public class BottomSheet extends Dialog { public ImageView getImageView() { return imageView; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } public void setAllowNestedScroll(boolean value) { @@ -767,7 +779,12 @@ public class BottomSheet extends Dialog { } public BottomSheet(Context context, boolean needFocus) { + this(context, needFocus, null); + } + + public BottomSheet(Context context, boolean needFocus, Theme.ResourcesProvider resourcesProvider) { super(context, R.style.TransparentDialog); + this.resourcesProvider = resourcesProvider; if (Build.VERSION.SDK_INT >= 30) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); @@ -779,7 +796,7 @@ public class BottomSheet extends Dialog { Rect padding = new Rect(); shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); shadowDrawable.getPadding(padding); backgroundPaddingLeft = padding.left; backgroundPaddingTop = padding.top; @@ -871,12 +888,12 @@ public class BottomSheet extends Dialog { titleView.setSingleLine(true); titleView.setText(title); if (bigTitle) { - titleView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + titleView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8)); } else { - titleView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + titleView.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8)); } @@ -900,7 +917,7 @@ public class BottomSheet extends Dialog { if (items[a] == null) { continue; } - BottomSheetCell cell = new BottomSheetCell(getContext(), 0); + BottomSheetCell cell = new BottomSheetCell(getContext(), 0, resourcesProvider); cell.setTextAndIcon(items[a], itemIcons != null ? itemIcons[a] : 0, null, bigTitle); containerView.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP, 0, topOffset, 0, 0)); topOffset += 48; @@ -1358,11 +1375,15 @@ public class BottomSheet extends Dialog { private BottomSheet bottomSheet; public Builder(Context context) { - bottomSheet = new BottomSheet(context, false); + this(context, false); } public Builder(Context context, boolean needFocus) { - bottomSheet = new BottomSheet(context, needFocus); + this(context, needFocus, null); + } + + public Builder(Context context, boolean needFocus, Theme.ResourcesProvider resourcesProvider) { + bottomSheet = new BottomSheet(context, needFocus, resourcesProvider); } public Builder setItems(CharSequence[] items, final OnClickListener onClickListener) { @@ -1510,4 +1531,9 @@ public class BottomSheet extends Dialog { public int getCurrentAccount() { return currentAccount; } + + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ChatTheme.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ChatTheme.java new file mode 100644 index 000000000..994dabb08 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ChatTheme.java @@ -0,0 +1,298 @@ +package org.telegram.ui.ActionBar; + +import android.app.Activity; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.BitmapDrawable; +import android.util.Pair; + +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.ApplicationLoader; +import org.telegram.messenger.ChatThemeController; +import org.telegram.messenger.FileLoader; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.ImageLoader; +import org.telegram.messenger.ImageLocation; +import org.telegram.messenger.ImageReceiver; +import org.telegram.messenger.SharedConfig; +import org.telegram.messenger.Utilities; +import org.telegram.tgnet.ResultCallback; +import org.telegram.tgnet.TLRPC; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class ChatTheme { + + public final boolean isDefault; + private final TLRPC.TL_chatTheme chatThemeObject; + private HashMap lightCurrentColors; + private HashMap darkCurrentColors; + private String darkWallpaperLink; + private String lightWallpaperLink; + + public ChatTheme(TLRPC.TL_chatTheme chatThemeObject, boolean isDefault) { + this.chatThemeObject = chatThemeObject; + this.isDefault = isDefault; + } + + public void initColors() { + getCurrentColors(0, false); + getCurrentColors(0, true); + } + + public String getEmoticon() { + return chatThemeObject.emoticon; + } + + public TLRPC.TL_theme getTlTheme(boolean isDark) { + return isDark ? ((TLRPC.TL_theme) chatThemeObject.dark_theme) : ((TLRPC.TL_theme) chatThemeObject.theme); + } + + public TLRPC.WallPaper getWallpaper(boolean isDark) { + return getTlTheme(isDark).settings.wallpaper; + } + + public String getWallpaperLink(boolean isDark) { + return isDark ? darkWallpaperLink : lightWallpaperLink; + } + + public HashMap getCurrentColors(int currentAccount, boolean isDark) { + HashMap currentColors = isDark ? darkCurrentColors : lightCurrentColors; + if (currentColors != null) { + return currentColors; + } + + TLRPC.TL_theme tlTheme = getTlTheme(isDark); + Theme.ThemeInfo baseTheme = Theme.getTheme(Theme.getBaseThemeKey(tlTheme.settings)); + Theme.ThemeInfo themeInfo = new Theme.ThemeInfo(baseTheme); + Theme.ThemeAccent accent = themeInfo.createNewAccent(tlTheme, currentAccount, true); + themeInfo.setCurrentAccentId(accent.id); + + HashMap currentColorsNoAccent = new HashMap<>(); + String[] wallpaperLink = new String[1]; + if (themeInfo.pathToFile != null) { + currentColorsNoAccent.putAll(Theme.getThemeFileValues(new File(themeInfo.pathToFile), null, wallpaperLink)); + } else if (themeInfo.assetName != null) { + currentColorsNoAccent.putAll(Theme.getThemeFileValues(null, themeInfo.assetName, wallpaperLink)); + } + if (isDark) { + darkWallpaperLink = wallpaperLink[0]; + } else { + lightWallpaperLink = wallpaperLink[0]; + } + currentColors = new HashMap<>(currentColorsNoAccent); + accent.fillAccentColors(currentColorsNoAccent, currentColors); + if (!isDark) { + currentColors.put(Theme.key_chat_messageTextOut, Theme.MSG_OUT_COLOR_BLACK); + } + HashMap fallbackKeys = Theme.getFallbackKeys(); + for (Map.Entry fallbackEntry : fallbackKeys.entrySet()) { + String colorKey = fallbackEntry.getKey(); + if (!currentColors.containsKey(colorKey)) { + Integer color = currentColors.get(fallbackEntry.getValue()); + currentColors.put(colorKey, color); + } + } + HashMap defaultColors = Theme.getDefaultColors(); + for (Map.Entry entry : defaultColors.entrySet()) { + if (!currentColors.containsKey(entry.getKey())) { + currentColors.put(entry.getKey(), entry.getValue()); + } + } + if (isDark) { + darkCurrentColors = currentColors; + } else { + lightCurrentColors = currentColors; + } + return currentColors; + } + + public void loadWallpaper(boolean isDark, ResultCallback> callback) { + final TLRPC.WallPaper wallPaper = getWallpaper(isDark); + if (wallPaper == null && callback != null) { + callback.onComplete(null); + return; + } + + long themeId = getTlTheme(isDark).id; + Bitmap cachedBitmap = ChatThemeController.getWallpaperBitmap(themeId); + if (cachedBitmap != null && callback != null) { + callback.onComplete(new Pair<>(themeId, cachedBitmap)); + return; + } + + ImageLocation imageLocation = ImageLocation.getForDocument(wallPaper.document); + ImageReceiver imageReceiver = new ImageReceiver(); + String imageFilter; + if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) { + int w = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); + int h = Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); + imageFilter = (int) (w / AndroidUtilities.density) + "_" + (int) (h / AndroidUtilities.density) + "_f"; + } else { + imageFilter = (int) (1080 / AndroidUtilities.density) + "_" + (int) (1920 / AndroidUtilities.density) + "_f"; + } + imageReceiver.setImage(imageLocation, imageFilter, null, ".jpg", wallPaper, 1); + imageReceiver.setDelegate((receiver, set, thumb, memCache) -> { + ImageReceiver.BitmapHolder holder = receiver.getBitmapSafe(); + if (!set || holder == null) { + return; + } + Bitmap bitmap = holder.bitmap; + if (bitmap == null && (holder.drawable instanceof BitmapDrawable)) { + bitmap = ((BitmapDrawable) holder.drawable).getBitmap(); + } + if (callback != null) { + callback.onComplete(new Pair<>(themeId, bitmap)); + } + }); + ImageLoader.getInstance().loadImageForImageReceiver(imageReceiver); + } + + public void loadWallpaperThumb(boolean isDark, ResultCallback> callback) { + final TLRPC.WallPaper wallpaper = getWallpaper(isDark); + if (wallpaper == null && callback != null) { + callback.onComplete(null); + return; + } + + long themeId = getTlTheme(isDark).id; + Bitmap bitmap = ChatThemeController.getWallpaperThumbBitmap(themeId); + File file = getWallpaperThumbFile(themeId); + if (bitmap == null && file.exists() && file.length() > 0) { + try { + bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); + } catch (Exception e) { + FileLog.e(e); + } + } + if (bitmap != null) { + if (callback != null) { + callback.onComplete(new Pair<>(themeId, bitmap)); + } + return; + } + + final TLRPC.PhotoSize thumbSize = FileLoader.getClosestPhotoSizeWithSize(wallpaper.document.thumbs, 120); + ImageLocation imageLocation = ImageLocation.getForDocument(thumbSize, wallpaper.document); + ImageReceiver imageReceiver = new ImageReceiver(); + imageReceiver.setImage(imageLocation, "120_80", null, null, null, 1); + imageReceiver.setDelegate((receiver, set, thumb, memCache) -> { + ImageReceiver.BitmapHolder holder = receiver.getBitmapSafe(); + if (!set || holder == null) { + return; + } + Bitmap resultBitmap = holder.bitmap; + if (resultBitmap == null && (holder.drawable instanceof BitmapDrawable)) { + resultBitmap = ((BitmapDrawable) holder.drawable).getBitmap(); + } + if (resultBitmap != null) { + if (callback != null) { + callback.onComplete(new Pair<>(themeId, resultBitmap)); + } + final Bitmap saveBitmap = resultBitmap; + Utilities.globalQueue.postRunnable(() -> { + try (FileOutputStream outputStream = new FileOutputStream(file)) { + saveBitmap.compress(Bitmap.CompressFormat.PNG, 87, outputStream); + } catch (Exception e) { + FileLog.e(e); + } + }); + } else { + if (callback != null) { + callback.onComplete(null); + } + } + }); + ImageLoader.getInstance().loadImageForImageReceiver(imageReceiver); + } + + public void preloadWallpaper() { + loadWallpaperThumb(false, null); + loadWallpaperThumb(true, null); + loadWallpaper(false, null); + loadWallpaper(true, null); + } + + private File getWallpaperThumbFile(long themeId) { + return new File(ApplicationLoader.getFilesDirFixed(), "wallpaper_thumb_" + themeId + ".png"); + } + + public static Theme.ThemeInfo getDefaultThemeInfo(boolean isDark) { + Theme.ThemeInfo themeInfo = isDark ? Theme.getCurrentNightTheme() : Theme.getCurrentTheme(); + if (isDark != themeInfo.isDark()) { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE); + String lastThemeName = isDark + ? preferences.getString("lastNightTheme", "Dark Blue") + : preferences.getString("lastDayTheme", "Blue"); + themeInfo = Theme.getTheme(lastThemeName); + if (themeInfo == null) { + themeInfo = Theme.getTheme(isDark ? "Dark Blue" : "Blue"); + } + } + return new Theme.ThemeInfo(themeInfo); + } + + public static ChatTheme getDefault() { + Theme.ThemeInfo darkThemeInfo = getDefaultThemeInfo(true); + fillTlTheme(darkThemeInfo); + Theme.ThemeInfo lightThemeInfo = getDefaultThemeInfo(false); + fillTlTheme(lightThemeInfo); + + TLRPC.TL_chatTheme tlChatTheme = new TLRPC.TL_chatTheme(); + tlChatTheme.emoticon = "❌"; + tlChatTheme.dark_theme = darkThemeInfo.info; + tlChatTheme.theme = lightThemeInfo.info; + + ChatTheme chatTheme = new ChatTheme(tlChatTheme, true); + chatTheme.darkCurrentColors = getCurrentColors(darkThemeInfo); + chatTheme.lightCurrentColors = getCurrentColors(lightThemeInfo); + return chatTheme; + } + + private static void fillTlTheme(Theme.ThemeInfo themeInfo) { + if (themeInfo.info == null) { + themeInfo.info = new TLRPC.TL_theme(); + } + if (themeInfo.info.settings == null) { + themeInfo.info.settings = new TLRPC.TL_themeSettings(); + } + ArrayList messageColors = new ArrayList<>(); + Theme.ThemeAccent accent = themeInfo.getAccent(false); + if (accent != null) { + if (accent.myMessagesAccentColor != 0) { + messageColors.add(accent.myMessagesAccentColor); + } + if (accent.myMessagesGradientAccentColor1 != 0) { + messageColors.add(accent.myMessagesGradientAccentColor1); + } + if (accent.myMessagesGradientAccentColor2 != 0) { + messageColors.add(accent.myMessagesGradientAccentColor2); + } + if (accent.myMessagesGradientAccentColor3 != 0) { + messageColors.add(accent.myMessagesGradientAccentColor3); + } + } + themeInfo.info.settings.message_colors = messageColors; + } + + private static HashMap getCurrentColors(Theme.ThemeInfo themeInfo) { + HashMap currentColorsNoAccent = new HashMap<>(); + if (themeInfo.pathToFile != null) { + currentColorsNoAccent.putAll(Theme.getThemeFileValues(new File(themeInfo.pathToFile), null, null)); + } else if (themeInfo.assetName != null) { + currentColorsNoAccent.putAll(Theme.getThemeFileValues(null, themeInfo.assetName, null)); + } + HashMap currentColors = new HashMap<>(currentColorsNoAccent); + Theme.ThemeAccent themeAccent = themeInfo.getAccent(false); + if (themeAccent != null) { + themeAccent.fillAccentColors(currentColorsNoAccent, currentColors); + } + return currentColors; + } + +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DarkAlertDialog.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DarkAlertDialog.java index f5117d2ec..f58ccb850 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DarkAlertDialog.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/DarkAlertDialog.java @@ -3,12 +3,13 @@ package org.telegram.ui.ActionBar; import android.content.Context; public class DarkAlertDialog extends AlertDialog { + public DarkAlertDialog(Context context, int progressStyle) { super(context, progressStyle); } @Override - protected int getThemeColor(String key) { + protected int getThemedColor(String key) { switch (key) { case Theme.key_dialogBackground: return 0xFF262626; @@ -17,7 +18,7 @@ public class DarkAlertDialog extends AlertDialog { case Theme.key_dialogScrollGlow: return 0xFFFFFFFF; } - return super.getThemeColor(key); + return super.getThemedColor(key); } public static class Builder extends AlertDialog.Builder { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/FloatingToolbar.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/FloatingToolbar.java index 3a622ed71..172c0015a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/FloatingToolbar.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/FloatingToolbar.java @@ -106,10 +106,13 @@ public final class FloatingToolbar { }; private final Comparator mMenuItemComparator = (menuItem1, menuItem2) -> menuItem1.getOrder() - menuItem2.getOrder(); + + private final Theme.ResourcesProvider resourcesProvider; - public FloatingToolbar(Context context, View windowView, int style) { + public FloatingToolbar(Context context, View windowView, int style, Theme.ResourcesProvider resourcesProvider) { mWindowView = windowView; currentStyle = style; + this.resourcesProvider = resourcesProvider; mPopup = new FloatingToolbarPopup(context, windowView); } @@ -971,7 +974,7 @@ public final class FloatingToolbar { return new LinearLayout(mContext) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - if (isOverflowAnimating()) { + if (isOverflowAnimating() && mMainPanelSize != null) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(mMainPanelSize.getWidth(), MeasureSpec.EXACTLY); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); @@ -992,14 +995,14 @@ public final class FloatingToolbar { overflowButton.setImageDrawable(mOverflow); int color; if (currentStyle == STYLE_DIALOG) { - color = Theme.getColor(Theme.key_dialogTextBlack); - overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1)); + color = getThemedColor(Theme.key_dialogTextBlack); + overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1)); } else if (currentStyle == STYLE_BLACK) { color = 0xfffafafa; overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x40ffffff, 1)); } else { - color = Theme.getColor(Theme.key_windowBackgroundWhiteBlackText); - overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1)); + color = getThemedColor(Theme.key_windowBackgroundWhiteBlackText); + overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1)); } mOverflow.setTint(color); mArrow.setTint(color); @@ -1204,13 +1207,13 @@ public final class FloatingToolbar { textView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); textView.setFocusableInTouchMode(false); if (currentStyle == STYLE_DIALOG) { - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false)); } else if (currentStyle == STYLE_BLACK) { textView.setTextColor(0xfffafafa); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(0x40ffffff, false)); } else if (currentStyle == STYLE_THEME) { - textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false)); } textView.setPaddingRelative(AndroidUtilities.dp(11), 0, 0, 0); @@ -1253,11 +1256,11 @@ public final class FloatingToolbar { int r = AndroidUtilities.dp(6); shape.setCornerRadii(new float[] { r, r, r, r, r, r, r, r }); if (currentStyle == STYLE_DIALOG) { - shape.setColor(Theme.getColor(Theme.key_dialogBackground)); + shape.setColor(getThemedColor(Theme.key_dialogBackground)); } else if (currentStyle == STYLE_BLACK) { shape.setColor(0xf9222222); } else if (currentStyle == STYLE_THEME) { - shape.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + shape.setColor(getThemedColor(Theme.key_windowBackgroundWhite)); } contentContainer.setBackgroundDrawable(shape); contentContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); @@ -1265,6 +1268,11 @@ public final class FloatingToolbar { return contentContainer; } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + private static PopupWindow createPopupWindow(ViewGroup content) { ViewGroup popupContentHolder = new LinearLayout(content.getContext()); PopupWindow popupWindow = new PopupWindow(popupContentHolder); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/Theme.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/Theme.java index bd4c1cc34..64ac990e9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/Theme.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/Theme.java @@ -105,6 +105,7 @@ import org.telegram.ui.RoundVideoProgressShadow; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.lang.reflect.Field; @@ -118,6 +119,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; +import java.util.Map; import java.util.concurrent.CountDownLatch; import androidx.annotation.NonNull; @@ -125,12 +127,26 @@ import androidx.annotation.Nullable; import androidx.annotation.UiThread; import androidx.core.graphics.ColorUtils; +import com.google.android.exoplayer2.util.Log; + public class Theme { public static final String DEFAULT_BACKGROUND_SLUG = "d"; public static final String THEME_BACKGROUND_SLUG = "t"; public static final String COLOR_BACKGROUND_SLUG = "c"; + public static final int MSG_OUT_COLOR_BLACK = 0xff212121; + public static final int MSG_OUT_COLOR_WHITE = 0xffffffff; + + public static class BackgroundDrawableSettings { + + public Drawable wallpaper; + public Drawable themedWallpaper; + public Boolean isWallpaperMotion; + public Boolean isPatternWallpaper; + public Boolean isCustomTheme; + } + public static class MessageDrawable extends Drawable { private Shader gradientShader; @@ -151,13 +167,15 @@ public class Theme { private Rect backupRect = new Rect(); + private final ResourcesProvider resourcesProvider; private final boolean isOut; private int topY; private boolean isTopNear; private boolean isBottomNear; + public boolean themePreview; - public static MotionBackgroundDrawable[] motionBackground = new MotionBackgroundDrawable[2]; + public static MotionBackgroundDrawable[] motionBackground = new MotionBackgroundDrawable[3]; private int[] currentShadowDrawableRadius = new int[]{-1, -1, -1, -1}; private Drawable[] shadowDrawable = new Drawable[4]; @@ -180,8 +198,20 @@ public class Theme { private int alpha; private boolean drawFullBubble; + public MessageDrawable crossfadeFromDrawable; + public float crossfadeProgress; + public boolean isCrossfadeBackground; + public boolean lastDrawWithShadow; + private Bitmap crosfadeFromBitmap; + private Shader crosfadeFromBitmapShader; + public MessageDrawable(int type, boolean out, boolean selected) { + this(type, out, selected, null); + } + + public MessageDrawable(int type, boolean out, boolean selected, ResourcesProvider resourcesProvider) { super(); + this.resourcesProvider = resourcesProvider; isOut = out; currentType = type; isSelected = selected; @@ -196,12 +226,25 @@ public class Theme { public void applyMatrixScale() { if (gradientShader instanceof BitmapShader) { - int num = currentType == TYPE_PREVIEW ? 1 : 0; - Bitmap bitmap = motionBackground[num].getBitmap(); - float scaleW = (bitmap.getWidth() / (float) motionBackground[num].getBounds().width()); - float scaleH = (bitmap.getHeight() / (float) motionBackground[num].getBounds().height()); - float scale = 1.0f / Math.min(scaleW, scaleH); - matrix.postScale(scale, scale); + if (isCrossfadeBackground && crosfadeFromBitmap != null) { + int num = currentType == TYPE_PREVIEW ? 1 : 0; + float scaleW = (crosfadeFromBitmap.getWidth() / (float) motionBackground[num].getBounds().width()); + float scaleH = (crosfadeFromBitmap.getHeight() / (float) motionBackground[num].getBounds().height()); + float scale = 1.0f / Math.min(scaleW, scaleH); + matrix.postScale(scale, scale); + } else { + int num; + if (themePreview) { + num = 2; + } else { + num = currentType == TYPE_PREVIEW ? 1 : 0; + } + Bitmap bitmap = motionBackground[num].getBitmap(); + float scaleW = (bitmap.getWidth() / (float) motionBackground[num].getBounds().width()); + float scaleH = (bitmap.getHeight() / (float) motionBackground[num].getBounds().height()); + float scale = 1.0f / Math.min(scaleW, scaleH); + matrix.postScale(scale, scale); + } } } @@ -214,11 +257,18 @@ public class Theme { } protected int getColor(String key) { - return Theme.getColor(key); + if (currentType == TYPE_PREVIEW) { + return Theme.getColor(key); + } + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); } protected Integer getCurrentColor(String key) { - return Theme.currentColors.get(key); + if (currentType == TYPE_PREVIEW) { + return Theme.getColor(key); + } + return resourcesProvider != null ? resourcesProvider.getCurrentColor(key) : Theme.currentColors.get(key); } public void setTop(int top, int backgroundWidth, int backgroundHeight, boolean topNear, boolean bottomNear) { @@ -226,6 +276,9 @@ public class Theme { } public void setTop(int top, int backgroundWidth, int backgroundHeight, int heightOffset, boolean topNear, boolean bottomNear) { + if (crossfadeFromDrawable != null) { + crossfadeFromDrawable.setTop(top, backgroundWidth, backgroundHeight, heightOffset, topNear, bottomNear); + } int color; Integer gradientColor1; Integer gradientColor2; @@ -257,8 +310,42 @@ public class Theme { if (gradientColor3 == null) { gradientColor3 = 0; } - int num = currentType == TYPE_PREVIEW ? 1 : 0; - if (gradientColor1 != 0 && (gradientShader == null || backgroundHeight != currentBackgroundHeight || currentColor != color || currentGradientColor1 != gradientColor1 || currentGradientColor2 != gradientColor2 || currentGradientColor3 != gradientColor3 || currentAnimateGradient != animatedGradient)) { + int num = 0; + if (themePreview) { + num = 2; + } else { + num = currentType == TYPE_PREVIEW ? 1 : 0; + } + if (gradientColor2 != 0 && animatedGradient && motionBackground[num] != null) { + int[] colors = motionBackground[num].getColors(); + currentColor = colors[0]; + currentGradientColor1 = colors[1]; + currentGradientColor2 = colors[2]; + currentGradientColor3 = colors[3]; + } + if (isCrossfadeBackground && gradientColor2 != 0 && animatedGradient) { + if (backgroundHeight != currentBackgroundHeight || crosfadeFromBitmapShader == null || currentColor != color || currentGradientColor1 != gradientColor1 || currentGradientColor2 != gradientColor2 || currentGradientColor3 != gradientColor3 || currentAnimateGradient != animatedGradient) { + crosfadeFromBitmap = Bitmap.createBitmap(60, 80, Bitmap.Config.ARGB_8888); + crosfadeFromBitmapShader = new BitmapShader(crosfadeFromBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + if (motionBackground[num] == null) { + motionBackground[num] = new MotionBackgroundDrawable(); + if (currentType != TYPE_PREVIEW) { + motionBackground[num].setPostInvalidateParent(true); + } + motionBackground[num].setRoundRadius(AndroidUtilities.dp(1)); + } + motionBackground[num].setColors(color, gradientColor1, gradientColor2, gradientColor3, crosfadeFromBitmap); + crosfadeFromBitmapShader.setLocalMatrix(matrix); + } + gradientShader = crosfadeFromBitmapShader; + paint.setShader(gradientShader); + paint.setColor(0xffffffff); + currentColor = color; + currentAnimateGradient = animatedGradient; + currentGradientColor1 = gradientColor1; + currentGradientColor2 = gradientColor2; + currentGradientColor3 = gradientColor3; + } else if (gradientColor1 != 0 && (gradientShader == null || backgroundHeight != currentBackgroundHeight || currentColor != color || currentGradientColor1 != gradientColor1 || currentGradientColor2 != gradientColor2 || currentGradientColor3 != gradientColor3 || currentAnimateGradient != animatedGradient)) { if (gradientColor2 != 0 && animatedGradient) { if (motionBackground[num] == null) { motionBackground[num] = new MotionBackgroundDrawable(); @@ -272,12 +359,15 @@ public class Theme { } else { if (gradientColor2 != 0) { if (gradientColor3 != 0) { - gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, new int[]{gradientColor3, gradientColor2, gradientColor1, color}, null, Shader.TileMode.CLAMP); + int[] colors = new int[]{gradientColor3, gradientColor2, gradientColor1, color}; + gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, colors, null, Shader.TileMode.CLAMP); } else { - gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, new int[]{gradientColor2, gradientColor1, color}, null, Shader.TileMode.CLAMP); + int[] colors = new int[]{gradientColor2, gradientColor1, color}; + gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, colors, null, Shader.TileMode.CLAMP); } } else { - gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, new int[]{gradientColor1, color}, null, Shader.TileMode.CLAMP); + int[] colors = new int[]{gradientColor1, color}; + gradientShader = new LinearGradient(0, 0, 0, backgroundHeight, colors, null, Shader.TileMode.CLAMP); } } paint.setShader(gradientShader); @@ -339,9 +429,9 @@ public class Theme { int idx2 = isSelected ? 1 : 0; boolean forceSetColor = false; - boolean drawWithShadow = gradientShader == null && !isSelected; + boolean drawWithShadow = gradientShader == null && !isSelected && !isCrossfadeBackground; int shadowColor = getColor(isOut ? key_chat_outBubbleShadow : key_chat_inBubbleShadow); - if (currentBackgroundDrawableRadius[idx2][idx] != newRad || (drawWithShadow && shadowDrawableColor[idx] != shadowColor)) { + if (lastDrawWithShadow != drawWithShadow || currentBackgroundDrawableRadius[idx2][idx] != newRad || (drawWithShadow && shadowDrawableColor[idx] != shadowColor)) { currentBackgroundDrawableRadius[idx2][idx] = newRad; try { Bitmap bitmap = Bitmap.createBitmap(dp(50), dp(40), Bitmap.Config.ARGB_8888); @@ -387,6 +477,7 @@ public class Theme { } } + lastDrawWithShadow = drawWithShadow; int color; if (isSelected) { color = getColor(isOut ? key_chat_outBubbleSelected : key_chat_inBubbleSelected); @@ -424,11 +515,17 @@ public class Theme { } public MotionBackgroundDrawable getMotionBackgroundDrawable() { + if (themePreview) { + return motionBackground[2]; + } return motionBackground[currentType == TYPE_PREVIEW ? 1 : 0]; } public Drawable getShadowDrawable() { - if (gradientShader == null && !isSelected) { + if (isCrossfadeBackground) { + return null; + } + if (gradientShader == null && !isSelected && crossfadeFromDrawable == null) { return null; } int newRad = AndroidUtilities.dp(SharedConfig.bubbleRadius); @@ -522,7 +619,14 @@ public class Theme { @Override public void draw(Canvas canvas) { - draw(canvas, null); + if (crossfadeFromDrawable != null) { + crossfadeFromDrawable.draw(canvas); + setAlpha((int) (255 * crossfadeProgress)); + draw(canvas, null); + setAlpha(255); + } else { + draw(canvas, null); + } } public void draw(Canvas canvas, Paint paintToUse) { @@ -718,6 +822,14 @@ public class Theme { public int getOpacity() { return PixelFormat.TRANSPARENT; } + + @Override + public void setBounds(int left, int top, int right, int bottom) { + super.setBounds(left, top, right, bottom); + if (crossfadeFromDrawable != null) { + crossfadeFromDrawable.setBounds(left, top, right, bottom); + } + } } public static class PatternsLoader implements NotificationCenter.NotificationCenterDelegate { @@ -956,21 +1068,26 @@ public class Theme { } } - Bitmap dst = Bitmap.createBitmap(patternBitmap.getWidth(), patternBitmap.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(dst); if (background != null) { - background.setBounds(0, 0, patternBitmap.getWidth(), patternBitmap.getHeight()); - background.draw(canvas); + Bitmap dst = Bitmap.createBitmap(patternBitmap.getWidth(), patternBitmap.getHeight(), Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(dst); + if (background != null) { + background.setBounds(0, 0, patternBitmap.getWidth(), patternBitmap.getHeight()); + background.draw(canvas); + } + + Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); + paint.setColorFilter(new PorterDuffColorFilter(patternColor, PorterDuff.Mode.SRC_IN)); + paint.setAlpha((int) (255 * Math.abs(accent.patternIntensity))); + canvas.drawBitmap(patternBitmap, 0, 0, paint); + + FileOutputStream stream = new FileOutputStream(toFile); + dst.compress(Bitmap.CompressFormat.JPEG, 87, stream); + } else { + FileOutputStream stream = new FileOutputStream(toFile); + patternBitmap.compress(Bitmap.CompressFormat.PNG, 87, stream); + stream.close(); } - - Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); - paint.setColorFilter(new PorterDuffColorFilter(patternColor, PorterDuff.Mode.SRC_IN)); - paint.setAlpha((int) (255 * Math.abs(accent.patternIntensity))); - canvas.drawBitmap(patternBitmap, 0, 0, paint); - - FileOutputStream stream = new FileOutputStream(toFile); - dst.compress(background == null ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 87, stream); - stream.close(); } catch (Throwable e) { FileLog.e(e); } @@ -1022,6 +1139,7 @@ public class Theme { public ThemeInfo parentTheme; public int accentColor; + public int accentColor2; public int myMessagesAccentColor; public int myMessagesGradientAccentColor1; public int myMessagesGradientAccentColor2; @@ -1048,6 +1166,38 @@ public class Theme { public OverrideWallpaperInfo overrideWallpaper; + ThemeAccent() { + + } + + public ThemeAccent(ThemeAccent other) { + this.id = other.id; + this.parentTheme = other.parentTheme; + this.accentColor = other.accentColor; + this.myMessagesAccentColor = other.myMessagesAccentColor; + this.myMessagesGradientAccentColor1 = other.myMessagesGradientAccentColor1; + this.myMessagesGradientAccentColor2 = other.myMessagesGradientAccentColor2; + this.myMessagesGradientAccentColor3 = other.myMessagesGradientAccentColor3; + this.myMessagesAnimated = other.myMessagesAnimated; + this.backgroundOverrideColor = other.backgroundOverrideColor; + this.backgroundGradientOverrideColor1 = other.backgroundGradientOverrideColor1; + this.backgroundGradientOverrideColor2 = other.backgroundGradientOverrideColor2; + this.backgroundGradientOverrideColor3 = other.backgroundGradientOverrideColor3; + this.backgroundRotation = other.backgroundRotation; + this.patternSlug = other.patternSlug; + this.patternIntensity = other.patternIntensity; + this.patternMotion = other.patternMotion; + this.info = other.info; + this.pattern = other.pattern; + this.account = other.account; + this.pathToFile = other.pathToFile; + this.uploadingThumb = other.uploadingThumb; + this.uploadingFile = other.uploadingFile; + this.uploadedThumb = other.uploadedThumb; + this.uploadedFile = other.uploadedFile; + this.overrideWallpaper = other.overrideWallpaper; + } + public boolean fillAccentColors(HashMap currentColorsNoAccent, HashMap currentColors) { boolean isMyMessagesGradientColorsNear = false; @@ -1058,7 +1208,7 @@ public class Theme { Color.colorToHSV(accentColor, hsvTemp2); boolean isDarkTheme = parentTheme.isDark(); - if (accentColor != parentTheme.accentBaseColor) { + if (accentColor != parentTheme.accentBaseColor || accentColor2 != 0) { HashSet keys = new HashSet<>(currentColorsNoAccent.keySet()); keys.addAll(defaultColors.keySet()); keys.removeAll(themeAccentExclusionKeys); @@ -1091,12 +1241,34 @@ public class Theme { int newColor = changeColorAccent(hsvTemp1, hsvTemp2, color, isDarkTheme); int distance1 = AndroidUtilities.getColorDistance(firstColor, newColor); int distance2 = AndroidUtilities.getColorDistance(firstColor, myMessagesGradientAccentColor1); - isMyMessagesGradientColorsNear = distance1 <= 35000 && distance2 <= 35000; + + boolean useBlackText; + if (myMessagesGradientAccentColor2 != 0) { + int averageColor = AndroidUtilities.getAverageColor(myMessagesAccentColor, myMessagesGradientAccentColor1); + averageColor = AndroidUtilities.getAverageColor(averageColor, myMessagesGradientAccentColor2); + if (myMessagesGradientAccentColor3 != 0) { + averageColor = AndroidUtilities.getAverageColor(averageColor, myMessagesGradientAccentColor3); + } + useBlackText = AndroidUtilities.computePerceivedBrightness(averageColor) > 0.705f; + } else { + useBlackText = useBlackText(myMessagesAccentColor, myMessagesGradientAccentColor1); + } + if (useBlackText) { + isMyMessagesGradientColorsNear = distance1 <= 35000 && distance2 <= 35000; + } else { + isMyMessagesGradientColorsNear = false; + } myMessagesAccent = getAccentColor(hsvTemp1, color, firstColor); } - if (myMessagesAccent != 0 && (parentTheme.accentBaseColor != 0 && myMessagesAccent != parentTheme.accentBaseColor || accentColor != 0 && accentColor != myMessagesAccent)) { - Color.colorToHSV(myMessagesAccent, hsvTemp2); + boolean changeMyMessagesColors = (myMessagesAccent != 0 && (parentTheme.accentBaseColor != 0 && myMessagesAccent != parentTheme.accentBaseColor || accentColor != 0 && accentColor != myMessagesAccent)); + if (changeMyMessagesColors || accentColor2 != 0) { + if (accentColor2 != 0) { + Color.colorToHSV(accentColor2, hsvTemp2); + } else { + Color.colorToHSV(myMessagesAccent, hsvTemp2); + } + for (String key : myMessagesColorKeys) { Integer color = currentColorsNoAccent.get(key); if (color == null) { @@ -1116,6 +1288,29 @@ public class Theme { currentColors.put(key, newColor); } } + + if (changeMyMessagesColors) { + Color.colorToHSV(myMessagesAccent, hsvTemp2); + for (String key : myMessagesBubblesColorKeys) { + Integer color = currentColorsNoAccent.get(key); + if (color == null) { + String fallbackKey = fallbackKeys.get(key); + if (fallbackKey != null && currentColorsNoAccent.get(fallbackKey) != null) { + continue; + } + } + if (color == null) { + color = defaultColors.get(key); + } + if (color == null) { + continue; + } + int newColor = changeColorAccent(hsvTemp1, hsvTemp2, color, isDarkTheme); + if (newColor != color) { + currentColors.put(key, newColor); + } + } + } } if (!isMyMessagesGradientColorsNear) { if (myMessagesGradientAccentColor1 != 0) { @@ -1134,91 +1329,96 @@ public class Theme { useBlackText = useBlackText(myMessagesAccentColor, myMessagesGradientAccentColor1); } if (useBlackText) { - textColor = 0xff212121; + textColor = MSG_OUT_COLOR_BLACK; subTextColor = 0xff555555; seekbarColor = 0x4d000000; } else { - textColor = 0xffffffff; + textColor = MSG_OUT_COLOR_WHITE; subTextColor = 0xffeeeeee; seekbarColor = 0x4dffffff; } - currentColors.put(key_chat_outAudioProgress, seekbarColor); - currentColors.put(key_chat_outAudioSelectedProgress, seekbarColor); - currentColors.put(key_chat_outAudioSeekbar, seekbarColor); - currentColors.put(key_chat_outAudioCacheSeekbar, seekbarColor); - currentColors.put(key_chat_outAudioSeekbarSelected, seekbarColor); - currentColors.put(key_chat_outAudioSeekbarFill, textColor); + if (accentColor2 == 0) { + currentColors.put(key_chat_outAudioProgress, seekbarColor); + currentColors.put(key_chat_outAudioSelectedProgress, seekbarColor); + currentColors.put(key_chat_outAudioSeekbar, seekbarColor); + currentColors.put(key_chat_outAudioCacheSeekbar, seekbarColor); + currentColors.put(key_chat_outAudioSeekbarSelected, seekbarColor); + currentColors.put(key_chat_outAudioSeekbarFill, textColor); - currentColors.put(key_chat_outVoiceSeekbar, seekbarColor); - currentColors.put(key_chat_outVoiceSeekbarSelected, seekbarColor); - currentColors.put(key_chat_outVoiceSeekbarFill, textColor); + currentColors.put(key_chat_outVoiceSeekbar, seekbarColor); + currentColors.put(key_chat_outVoiceSeekbarSelected, seekbarColor); + currentColors.put(key_chat_outVoiceSeekbarFill, textColor); - currentColors.put(key_chat_messageTextOut, textColor); - currentColors.put(key_chat_messageLinkOut, textColor); - currentColors.put(key_chat_outForwardedNameText, textColor); - currentColors.put(key_chat_outViaBotNameText, textColor); - currentColors.put(key_chat_outReplyLine, textColor); - currentColors.put(key_chat_outReplyNameText, textColor); + currentColors.put(key_chat_messageLinkOut, textColor); + currentColors.put(key_chat_outForwardedNameText, textColor); + currentColors.put(key_chat_outViaBotNameText, textColor); + currentColors.put(key_chat_outReplyLine, textColor); + currentColors.put(key_chat_outReplyNameText, textColor); - currentColors.put(key_chat_outPreviewLine, textColor); - currentColors.put(key_chat_outSiteNameText, textColor); - currentColors.put(key_chat_outInstant, textColor); - currentColors.put(key_chat_outInstantSelected, textColor); - currentColors.put(key_chat_outPreviewInstantText, textColor); - currentColors.put(key_chat_outPreviewInstantSelectedText, textColor); + currentColors.put(key_chat_outPreviewLine, textColor); + currentColors.put(key_chat_outSiteNameText, textColor); + currentColors.put(key_chat_outInstant, textColor); + currentColors.put(key_chat_outInstantSelected, textColor); + currentColors.put(key_chat_outPreviewInstantText, textColor); + currentColors.put(key_chat_outPreviewInstantSelectedText, textColor); - currentColors.put(key_chat_outViews, textColor); - currentColors.put(key_chat_outViewsSelected, textColor); + currentColors.put(key_chat_outViews, textColor); + currentColors.put(key_chat_outViewsSelected, textColor); - currentColors.put(key_chat_outAudioTitleText, textColor); - currentColors.put(key_chat_outFileNameText, textColor); - currentColors.put(key_chat_outContactNameText, textColor); + currentColors.put(key_chat_outAudioTitleText, textColor); + currentColors.put(key_chat_outFileNameText, textColor); + currentColors.put(key_chat_outContactNameText, textColor); - currentColors.put(key_chat_outAudioPerformerText, textColor); - currentColors.put(key_chat_outAudioPerformerSelectedText, textColor); + currentColors.put(key_chat_outAudioPerformerText, textColor); + currentColors.put(key_chat_outAudioPerformerSelectedText, textColor); - currentColors.put(key_chat_outSentCheck, textColor); - currentColors.put(key_chat_outSentCheckSelected, textColor); + currentColors.put(key_chat_outSentCheck, textColor); + currentColors.put(key_chat_outSentCheckSelected, textColor); - currentColors.put(key_chat_outSentCheckRead, textColor); - currentColors.put(key_chat_outSentCheckReadSelected, textColor); + currentColors.put(key_chat_outSentCheckRead, textColor); + currentColors.put(key_chat_outSentCheckReadSelected, textColor); - currentColors.put(key_chat_outSentClock, textColor); - currentColors.put(key_chat_outSentClockSelected, textColor); + currentColors.put(key_chat_outSentClock, textColor); + currentColors.put(key_chat_outSentClockSelected, textColor); - currentColors.put(key_chat_outMenu, textColor); - currentColors.put(key_chat_outMenuSelected, textColor); + currentColors.put(key_chat_outMenu, textColor); + currentColors.put(key_chat_outMenuSelected, textColor); - currentColors.put(key_chat_outTimeText, textColor); - currentColors.put(key_chat_outTimeSelectedText, textColor); + currentColors.put(key_chat_outTimeText, textColor); + currentColors.put(key_chat_outTimeSelectedText, textColor); - currentColors.put(key_chat_outAudioDurationText, subTextColor); - currentColors.put(key_chat_outAudioDurationSelectedText, subTextColor); + currentColors.put(key_chat_outAudioDurationText, subTextColor); + currentColors.put(key_chat_outAudioDurationSelectedText, subTextColor); - currentColors.put(key_chat_outContactPhoneText, subTextColor); - currentColors.put(key_chat_outContactPhoneSelectedText, subTextColor); + currentColors.put(key_chat_outContactPhoneText, subTextColor); + currentColors.put(key_chat_outContactPhoneSelectedText, subTextColor); - currentColors.put(key_chat_outFileInfoText, subTextColor); - currentColors.put(key_chat_outFileInfoSelectedText, subTextColor); + currentColors.put(key_chat_outFileInfoText, subTextColor); + currentColors.put(key_chat_outFileInfoSelectedText, subTextColor); - currentColors.put(key_chat_outVenueInfoText, subTextColor); - currentColors.put(key_chat_outVenueInfoSelectedText, subTextColor); + currentColors.put(key_chat_outVenueInfoText, subTextColor); + currentColors.put(key_chat_outVenueInfoSelectedText, subTextColor); + + + currentColors.put(key_chat_outLoader, textColor); + currentColors.put(key_chat_outLoaderSelected, textColor); + currentColors.put(key_chat_outFileProgress, myMessagesAccentColor); + currentColors.put(key_chat_outFileProgressSelected, myMessagesAccentColor); + currentColors.put(key_chat_outMediaIcon, myMessagesAccentColor); + currentColors.put(key_chat_outMediaIconSelected, myMessagesAccentColor); + } currentColors.put(key_chat_outReplyMessageText, textColor); currentColors.put(key_chat_outReplyMediaMessageText, textColor); currentColors.put(key_chat_outReplyMediaMessageSelectedText, textColor); - - currentColors.put(key_chat_outLoader, textColor); - currentColors.put(key_chat_outLoaderSelected, textColor); - currentColors.put(key_chat_outFileProgress, myMessagesAccentColor); - currentColors.put(key_chat_outFileProgressSelected, myMessagesAccentColor); - currentColors.put(key_chat_outMediaIcon, myMessagesAccentColor); - currentColors.put(key_chat_outMediaIconSelected, myMessagesAccentColor); + currentColors.put(key_chat_messageTextOut, textColor); } } if (isMyMessagesGradientColorsNear) { - int outColor = currentColors.get(key_chat_outLoader); + int outColor = currentColors.containsKey(key_chat_outLoader) + ? currentColors.get(key_chat_outLoader) + : Color.TRANSPARENT; if (AndroidUtilities.getColorDistance(0xffffffff, outColor) < 5000) { isMyMessagesGradientColorsNear = false; } @@ -1266,9 +1466,10 @@ public class Theme { public File getPathToWallpaper() { if (id < 100) { - return !TextUtils.isEmpty(patternSlug) ? new File(ApplicationLoader.getFilesDirFixed(), String.format(Locale.US, "%s_%d_%s_v3.jpg", parentTheme.getKey(), id, patternSlug)) : null; + return !TextUtils.isEmpty(patternSlug) ? new File(ApplicationLoader.getFilesDirFixed(), String.format(Locale.US, "%s_%d_%s_v5.jpg", parentTheme.getKey(), id, patternSlug)) : null; } else { - return !TextUtils.isEmpty(patternSlug) ? new File(ApplicationLoader.getFilesDirFixed(), String.format(Locale.US, "%s_%d_%s.jpg", parentTheme.getKey(), id, patternSlug)) : null; + // return !TextUtils.isEmpty(patternSlug) ? new File(ApplicationLoader.getFilesDirFixed(), String.format(Locale.US, "%s_%d_%s_v4.jpg", parentTheme.getKey(), id, patternSlug)) : null; + return !TextUtils.isEmpty(patternSlug) ? new File(ApplicationLoader.getFilesDirFixed(), String.format(Locale.US, "%s_%d_%s_v8_dubug.jpg", parentTheme.getKey(), id, patternSlug)) : null; } } @@ -1532,6 +1733,8 @@ public class Theme { public SparseArray themeAccentsMap; public ArrayList themeAccents; public LongSparseArray accentsByThemeId; + public LongSparseArray chatAccentsByThemeId = new LongSparseArray<>(); + public int lastChatThemeId = 0; public int lastAccentId = 100; private String loadingThemeWallpaperName; @@ -1543,6 +1746,52 @@ public class Theme { } + public ThemeInfo(ThemeInfo other) { + this.name = other.name; + this.pathToFile = other.pathToFile; + this.pathToWallpaper = other.pathToWallpaper; + this.assetName = other.assetName; + this.slug = other.slug; + this.badWallpaper = other.badWallpaper; + this.isBlured = other.isBlured; + this.isMotion = other.isMotion; + this.patternBgColor = other.patternBgColor; + this.patternBgGradientColor1 = other.patternBgGradientColor1; + this.patternBgGradientColor2 = other.patternBgGradientColor2; + this.patternBgGradientColor3 = other.patternBgGradientColor3; + this.patternBgGradientRotation = other.patternBgGradientRotation; + this.patternIntensity = other.patternIntensity; + this.account = other.account; + this.info = other.info; + this.loaded = other.loaded; + this.uploadingThumb = other.uploadingThumb; + this.uploadingFile = other.uploadingFile; + this.uploadedThumb = other.uploadedThumb; + this.uploadedFile = other.uploadedFile; + this.previewBackgroundColor = other.previewBackgroundColor; + this.previewBackgroundGradientColor1 = other.previewBackgroundGradientColor1; + this.previewBackgroundGradientColor2 = other.previewBackgroundGradientColor2; + this.previewBackgroundGradientColor3 = other.previewBackgroundGradientColor3; + this.previewWallpaperOffset = other.previewWallpaperOffset; + this.previewInColor = other.previewInColor; + this.previewOutColor = other.previewOutColor; + this.firstAccentIsDefault = other.firstAccentIsDefault; + this.previewParsed = other.previewParsed; + this.themeLoaded = other.themeLoaded; + this.sortIndex = other.sortIndex; + this.defaultAccentCount = other.defaultAccentCount; + this.accentBaseColor = other.accentBaseColor; + this.currentAccentId = other.currentAccentId; + this.prevAccentId = other.prevAccentId; + this.themeAccentsMap = other.themeAccentsMap; + this.themeAccents = other.themeAccents; + this.accentsByThemeId = other.accentsByThemeId; + this.lastAccentId = other.lastAccentId; + this.loadingThemeWallpaperName = other.loadingThemeWallpaperName; + this.newPathToWallpaper = other.newPathToWallpaper; + this.overrideWallpaper = other.overrideWallpaper; + } + JSONObject getSaveJson() { try { JSONObject jsonObject = new JSONObject(); @@ -1696,7 +1945,8 @@ public class Theme { return previewBackgroundColor; } - private boolean isDefaultMyMessages() { + + private boolean isDefaultMyMessagesBubbles() { if (!firstAccentIsDefault) { return false; } @@ -1715,6 +1965,26 @@ public class Theme { defaultAccent.myMessagesAnimated == accent.myMessagesAnimated; } + private boolean isDefaultMyMessages() { + if (!firstAccentIsDefault) { + return false; + } + if (currentAccentId == DEFALT_THEME_ACCENT_ID) { + return true; + } + ThemeAccent defaultAccent = themeAccentsMap.get(DEFALT_THEME_ACCENT_ID); + ThemeAccent accent = themeAccentsMap.get(currentAccentId); + if (defaultAccent == null || accent == null) { + return false; + } + return defaultAccent.accentColor2 == accent.accentColor2 && + defaultAccent.myMessagesAccentColor == accent.myMessagesAccentColor && + defaultAccent.myMessagesGradientAccentColor1 == accent.myMessagesGradientAccentColor1 && + defaultAccent.myMessagesGradientAccentColor2 == accent.myMessagesGradientAccentColor2 && + defaultAccent.myMessagesGradientAccentColor3 == accent.myMessagesGradientAccentColor3 && + defaultAccent.myMessagesAnimated == accent.myMessagesAnimated; + } + private boolean isDefaultMainAccent() { if (!firstAccentIsDefault) { return false; @@ -1879,7 +2149,7 @@ public class Theme { } } - public static boolean accentEquals(ThemeAccent accent, TLRPC.TL_themeSettings settings) { + public static boolean accentEquals(ThemeAccent accent, TLRPC.ThemeSettings settings) { int bottomColor = settings.message_colors.size() > 0 ? settings.message_colors.get(0) | 0xff000000 : 0; int myMessagesGradientAccentColor1 = settings.message_colors.size() > 1 ? settings.message_colors.get(1) | 0xff000000 : 0; if (bottomColor == myMessagesGradientAccentColor1) { @@ -1918,6 +2188,7 @@ public class Theme { } } return settings.accent_color == accent.accentColor && + settings.outbox_accent_color == accent.accentColor2 && bottomColor == accent.myMessagesAccentColor && myMessagesGradientAccentColor1 == accent.myMessagesGradientAccentColor1 && myMessagesGradientAccentColor2 == accent.myMessagesGradientAccentColor2 && @@ -1932,8 +2203,9 @@ public class Theme { Math.abs(patternIntensity - accent.patternIntensity) < 0.001; } - public static void fillAccentValues(ThemeAccent themeAccent, TLRPC.TL_themeSettings settings) { + public static void fillAccentValues(ThemeAccent themeAccent, TLRPC.ThemeSettings settings) { themeAccent.accentColor = settings.accent_color; + themeAccent.accentColor2 = settings.outbox_accent_color; themeAccent.myMessagesAccentColor = settings.message_colors.size() > 0 ? settings.message_colors.get(0) | 0xff000000 : 0; themeAccent.myMessagesGradientAccentColor1 = settings.message_colors.size() > 1 ? settings.message_colors.get(1) | 0xff000000 : 0; if (themeAccent.myMessagesAccentColor == themeAccent.myMessagesGradientAccentColor1) { @@ -1943,7 +2215,11 @@ public class Theme { themeAccent.myMessagesGradientAccentColor3 = settings.message_colors.size() > 3 ? settings.message_colors.get(3) | 0xff000000 : 0; themeAccent.myMessagesAnimated = settings.message_colors_animated; if (settings.wallpaper != null && settings.wallpaper.settings != null) { - themeAccent.backgroundOverrideColor = getWallpaperColor(settings.wallpaper.settings.background_color); + if (settings.wallpaper.settings.background_color == 0) { + themeAccent.backgroundOverrideColor = 0x100000000L; + } else { + themeAccent.backgroundOverrideColor = getWallpaperColor(settings.wallpaper.settings.background_color); + } if ((settings.wallpaper.settings.flags & 16) != 0 && settings.wallpaper.settings.second_background_color == 0) { themeAccent.backgroundGradientOverrideColor1 = 0x100000000L; } else { @@ -1968,7 +2244,7 @@ public class Theme { } } - public ThemeAccent createNewAccent(TLRPC.TL_themeSettings settings) { + public ThemeAccent createNewAccent(TLRPC.ThemeSettings settings) { ThemeAccent themeAccent = new ThemeAccent(); fillAccentValues(themeAccent, settings); themeAccent.parentTheme = this; @@ -1976,22 +2252,40 @@ public class Theme { } public ThemeAccent createNewAccent(TLRPC.TL_theme info, int account) { + return createNewAccent(info, account, false); + } + + public ThemeAccent createNewAccent(TLRPC.TL_theme info, int account, boolean ignoreThemeInfoId) { if (info == null) { return null; } - ThemeAccent themeAccent = accentsByThemeId.get(info.id); - if (themeAccent != null) { + if (ignoreThemeInfoId) { + ThemeAccent themeAccent = chatAccentsByThemeId.get(info.id); + if (themeAccent != null) { + return themeAccent; + } + int id = ++lastChatThemeId; + themeAccent = createNewAccent(info.settings); + themeAccent.id = id; + themeAccent.info = info; + themeAccent.account = account; + chatAccentsByThemeId.put(id, themeAccent); + return themeAccent; + } else { + ThemeAccent themeAccent = accentsByThemeId.get(info.id); + if (themeAccent != null) { + return themeAccent; + } + int id = ++lastAccentId; + themeAccent = createNewAccent(info.settings); + themeAccent.id = id; + themeAccent.info = info; + themeAccent.account = account; + themeAccentsMap.put(id, themeAccent); + themeAccents.add(0, themeAccent); + accentsByThemeId.put(info.id, themeAccent); return themeAccent; } - int id = ++lastAccentId; - themeAccent = createNewAccent(info.settings); - themeAccent.id = id; - themeAccent.info = info; - themeAccent.account = account; - themeAccentsMap.put(id, themeAccent); - themeAccents.add(0, themeAccent); - accentsByThemeId.put(info.id, themeAccent); - return themeAccent; } public ThemeAccent getAccent(boolean createNew) { @@ -2003,6 +2297,7 @@ public class Theme { int id = ++lastAccentId; ThemeAccent themeAccent = new ThemeAccent(); themeAccent.accentColor = accent.accentColor; + themeAccent.accentColor2 = accent.accentColor2; themeAccent.myMessagesAccentColor = accent.myMessagesAccentColor; themeAccent.myMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor1; themeAccent.myMessagesGradientAccentColor2 = accent.myMessagesGradientAccentColor2; @@ -2131,6 +2426,38 @@ public class Theme { } } + public interface ResourcesProvider { + + Integer getColor(String key); + + default int getColorOrDefault(String key) { + Integer color = getColor(key); + return color != null ? color : Theme.getColor(key); + } + + default Integer getCurrentColor(String key) { + return getColor(key); + } + + default void setAnimatedColor(String key, int color) {} + + default Drawable getDrawable(String drawableKey) { + return null; + } + + default Paint getPaint(String paintKey) { + return null; + } + + default boolean hasGradientService() { + return false; + } + + default void applyServiceShaderMatrix(int w, int h, float translationX, float translationY) { + Theme.applyServiceShaderMatrix(w, h, translationX, translationY); + } + } + private static final Object sync = new Object(); private static Runnable wallpaperLoadTask; @@ -2192,7 +2519,7 @@ public class Theme { private static int lastLoadingCurrentThemeTime; private static boolean[] loadingRemoteThemes = new boolean[UserConfig.MAX_ACCOUNT_COUNT]; private static int[] lastLoadingThemesTime = new int[UserConfig.MAX_ACCOUNT_COUNT]; - private static int[] remoteThemesHash = new int[UserConfig.MAX_ACCOUNT_COUNT]; + private static long[] remoteThemesHash = new long[UserConfig.MAX_ACCOUNT_COUNT]; public static ArrayList themes; private static ArrayList otherThemes; @@ -2386,16 +2713,11 @@ public class Theme { public static Drawable chat_msgOutCheckReadSelectedDrawable; public static Drawable chat_msgOutHalfCheckDrawable; public static Drawable chat_msgOutHalfCheckSelectedDrawable; - public static Drawable chat_msgOutClockDrawable; - public static Drawable chat_msgOutSelectedClockDrawable; - public static Drawable chat_msgInClockDrawable; - public static Drawable chat_msgInSelectedClockDrawable; + public static MsgClockDrawable chat_msgClockDrawable; public static Drawable chat_msgMediaCheckDrawable; public static Drawable chat_msgMediaHalfCheckDrawable; - public static Drawable chat_msgMediaClockDrawable; public static Drawable chat_msgStickerCheckDrawable; public static Drawable chat_msgStickerHalfCheckDrawable; - public static Drawable chat_msgStickerClockDrawable; public static Drawable chat_msgStickerViewsDrawable; public static Drawable chat_msgStickerRepliesDrawable; public static Drawable chat_msgInViewsDrawable; @@ -3110,6 +3432,8 @@ public class Theme { public static final String key_voipgroup_mutedByAdminGradient3 = "voipgroup_mutedByAdminGradient3"; public static final String key_voipgroup_mutedByAdminMuteButton = "voipgroup_mutedByAdminMuteButton"; public static final String key_voipgroup_mutedByAdminMuteButtonDisabled = "voipgroup_mutedByAdminMuteButtonDisabled"; + public static final String key_voipgroup_windowBackgroundWhiteInputField = "voipgroup_windowBackgroundWhiteInputField"; + public static final String key_voipgroup_windowBackgroundWhiteInputFieldActivated = "voipgroup_windowBackgroundWhiteInputFieldActivated"; public static final String key_passport_authorizeBackground = "passport_authorizeBackground"; public static final String key_passport_authorizeBackgroundSelected = "passport_authorizeBackgroundSelected"; @@ -3267,7 +3591,65 @@ public class Theme { public final static String key_statisticChartLine_indigo = "statisticChartLine_indigo"; public final static String key_statisticChartLineEmpty = "statisticChartLineEmpty"; + public static final String key_drawable_botInline = "drawableBotInline"; + public static final String key_drawable_botLink = "drawableBotLink"; + public static final String key_drawable_commentSticker = "drawableCommentSticker"; + public static final String key_drawable_goIcon = "drawableGoIcon"; + public static final String key_drawable_msgError = "drawableMsgError"; + public static final String key_drawable_msgIn = "drawableMsgIn"; + public static final String key_drawable_msgInClock = "drawableMsgInClock"; + public static final String key_drawable_msgInClockSelected = "drawableMsgInClockSelected"; + public static final String key_drawable_msgInSelected = "drawableMsgInSelected"; + public static final String key_drawable_msgInMedia = "drawableMsgInMedia"; + public static final String key_drawable_msgInMediaSelected = "drawableMsgInMediaSelected"; + public static final String key_drawable_msgOut = "drawableMsgOut"; + public static final String key_drawable_msgOutSelected = "drawableMsgOutSelected"; + public static final String key_drawable_msgOutCallAudio = "drawableMsgOutCallAudio"; + public static final String key_drawable_msgOutCallAudioSelected = "drawableMsgOutCallAudioSelected"; + public static final String key_drawable_msgOutCallVideo = "drawableMsgOutCallVideo"; + public static final String key_drawable_msgOutCallVideoSelected = "drawableMsgOutCallVideo"; + public static final String key_drawable_msgOutCheck = "drawableMsgOutCheck"; + public static final String key_drawable_msgOutCheckSelected = "drawableMsgOutCheckSelected"; + public static final String key_drawable_msgOutCheckRead = "drawableMsgOutCheckRead"; + public static final String key_drawable_msgOutCheckReadSelected = "drawableMsgOutCheckReadSelected"; + public static final String key_drawable_msgOutHalfCheck = "drawableMsgOutHalfCheck"; + public static final String key_drawable_msgOutHalfCheckSelected = "drawableMsgOutHalfCheckSelected"; + public static final String key_drawable_msgOutInstant = "drawableMsgOutInstant"; + public static final String key_drawable_msgOutMedia = "drawableMsgOutMedia"; + public static final String key_drawable_msgOutMediaSelected = "drawableMsgOutMediaSelected"; + public static final String key_drawable_msgOutMenu = "drawableMsgOutMenu"; + public static final String key_drawable_msgOutMenuSelected = "drawableMsgOutMenuSelected"; + public static final String key_drawable_msgOutPinned = "drawableMsgOutPinned"; + public static final String key_drawable_msgOutPinnedSelected = "drawableMsgOutPinnedSelected"; + public static final String key_drawable_msgOutReplies = "drawableMsgOutReplies"; + public static final String key_drawable_msgOutRepliesSelected = "drawableMsgOutReplies"; + public static final String key_drawable_msgOutViews = "drawableMsgOutViews"; + public static final String key_drawable_msgOutViewsSelected = "drawableMsgOutViewsSelected"; + public static final String key_drawable_msgStickerCheck = "drawableMsgStickerCheck"; + public static final String key_drawable_msgStickerClock = "drawableMsgStickerClock"; + public static final String key_drawable_msgStickerHalfCheck = "drawableMsgStickerHalfCheck"; + public static final String key_drawable_msgStickerPinned = "drawableMsgStickerPinned"; + public static final String key_drawable_msgStickerReplies = "drawableMsgStickerReplies"; + public static final String key_drawable_msgStickerViews = "drawableMsgStickerViews"; + public static final String key_drawable_replyIcon = "drawableReplyIcon"; + public static final String key_drawable_shareIcon = "drawableShareIcon"; + public static final String key_drawable_muteIconDrawable = "drawableMuteIcon"; + public static final String key_drawable_lockIconDrawable = "drawableLockIcon"; + private static final HashMap defaultChatDrawables = new HashMap<>(); + private static final HashMap defaultChatDrawableColorKeys = new HashMap<>(); + + public static final String key_paint_chatActionBackground = "paintChatActionBackground"; + public static final String key_paint_chatActionBackgroundSelected = "paintChatActionBackgroundSelected"; + public static final String key_paint_chatActionText = "paintChatActionText"; + public static final String key_paint_chatBotButton = "paintChatBotButton"; + public static final String key_paint_chatComposeBackground = "paintChatComposeBackground"; + public static final String key_paint_chatTimeBackground = "paintChatTimeBackground"; + private static final HashMap defaultChatPaints = new HashMap<>(); + private static final HashMap defaultChatPaintColors = new HashMap<>(); + private static HashSet myMessagesColorKeys = new HashSet<>(); + private static HashSet myMessagesBubblesColorKeys = new HashSet<>(); + private static HashSet myMessagesGradientColorsNearKeys = new HashSet<>(); private static HashMap defaultColors = new HashMap<>(); private static HashMap fallbackKeys = new HashMap<>(); private static HashSet themeAccentExclusionKeys = new HashSet<>(); @@ -4056,7 +4438,8 @@ public class Theme { defaultColors.put(key_voipgroup_overlayAlertMutedByAdmin2, 0xff2F5078); defaultColors.put(key_voipgroup_mutedByAdminMuteButton, 0x7F78A3FF); defaultColors.put(key_voipgroup_mutedByAdminMuteButtonDisabled, 0x3378A3FF); - + defaultColors.put(key_voipgroup_windowBackgroundWhiteInputField, 0xffdbdbdb); + defaultColors.put(key_voipgroup_windowBackgroundWhiteInputFieldActivated, 0xff37a9f0); fallbackKeys.put(key_chat_inAdminText, key_chat_inTimeText); @@ -4272,12 +4655,15 @@ public class Theme { themeAccentExclusionKeys.add(key_voipgroup_mutedByAdminGradient3); themeAccentExclusionKeys.add(key_voipgroup_mutedByAdminMuteButton); themeAccentExclusionKeys.add(key_voipgroup_mutedByAdminMuteButtonDisabled); + themeAccentExclusionKeys.add(key_voipgroup_windowBackgroundWhiteInputField); + themeAccentExclusionKeys.add(key_voipgroup_windowBackgroundWhiteInputFieldActivated); + + myMessagesBubblesColorKeys.add(key_chat_outBubble); + myMessagesBubblesColorKeys.add(key_chat_outBubbleSelected); + myMessagesBubblesColorKeys.add(key_chat_outBubbleShadow); + myMessagesBubblesColorKeys.add(key_chat_outBubbleGradient1); myMessagesColorKeys.add(key_chat_outGreenCall); - myMessagesColorKeys.add(key_chat_outBubble); - myMessagesColorKeys.add(key_chat_outBubbleSelected); - myMessagesColorKeys.add(key_chat_outBubbleShadow); - myMessagesColorKeys.add(key_chat_outBubbleGradient1); myMessagesColorKeys.add(key_chat_outSentCheck); myMessagesColorKeys.add(key_chat_outSentCheckSelected); myMessagesColorKeys.add(key_chat_outSentCheckRead); @@ -4475,7 +4861,7 @@ public class Theme { String themesString = themeConfig.getString("themes2", null); for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { - remoteThemesHash[a] = themeConfig.getInt("remoteThemesHash" + (a != 0 ? a : ""), 0); + remoteThemesHash[a] = themeConfig.getLong("2remoteThemesHash" + (a != 0 ? a : ""), 0); lastLoadingThemesTime[a] = themeConfig.getInt("lastLoadingThemesTime" + (a != 0 ? a : ""), 0); } if (!TextUtils.isEmpty(themesString)) { @@ -4566,56 +4952,63 @@ public class Theme { int version = data.readInt32(true); int count = data.readInt32(true); for (int a = 0; a < count; a++) { - ThemeAccent accent = new ThemeAccent(); - accent.id = data.readInt32(true); - accent.accentColor = data.readInt32(true); - accent.parentTheme = info; - accent.myMessagesAccentColor = data.readInt32(true); - accent.myMessagesGradientAccentColor1 = data.readInt32(true); - if (version >= 7) { - accent.myMessagesGradientAccentColor2 = data.readInt32(true); - accent.myMessagesGradientAccentColor3 = data.readInt32(true); - } - if (version >= 8) { - accent.myMessagesAnimated = data.readBool(true); - } - if (version >= 3) { - accent.backgroundOverrideColor = data.readInt64(true); - } else { - accent.backgroundOverrideColor = data.readInt32(true); - } - if (version >= 2) { - accent.backgroundGradientOverrideColor1 = data.readInt64(true); - } else { - accent.backgroundGradientOverrideColor1 = data.readInt32(true); - } - if (version >= 6) { - accent.backgroundGradientOverrideColor2 = data.readInt64(true); - accent.backgroundGradientOverrideColor3 = data.readInt64(true); - } - if (version >= 1) { - accent.backgroundRotation = data.readInt32(true); - } - if (version >= 4) { - data.readInt64(true); //unused - accent.patternIntensity = (float) data.readDouble(true); - accent.patternMotion = data.readBool(true); + try { + ThemeAccent accent = new ThemeAccent(); + accent.id = data.readInt32(true); + accent.accentColor = data.readInt32(true); + if (version >= 9) { + accent.accentColor2 = data.readInt32(true); + } + accent.parentTheme = info; + accent.myMessagesAccentColor = data.readInt32(true); + accent.myMessagesGradientAccentColor1 = data.readInt32(true); + if (version >= 7) { + accent.myMessagesGradientAccentColor2 = data.readInt32(true); + accent.myMessagesGradientAccentColor3 = data.readInt32(true); + } + if (version >= 8) { + accent.myMessagesAnimated = data.readBool(true); + } + if (version >= 3) { + accent.backgroundOverrideColor = data.readInt64(true); + } else { + accent.backgroundOverrideColor = data.readInt32(true); + } + if (version >= 2) { + accent.backgroundGradientOverrideColor1 = data.readInt64(true); + } else { + accent.backgroundGradientOverrideColor1 = data.readInt32(true); + } + if (version >= 6) { + accent.backgroundGradientOverrideColor2 = data.readInt64(true); + accent.backgroundGradientOverrideColor3 = data.readInt64(true); + } + if (version >= 1) { + accent.backgroundRotation = data.readInt32(true); + } + if (version >= 4) { + data.readInt64(true); //unused + accent.patternIntensity = (float) data.readDouble(true); + accent.patternMotion = data.readBool(true); + if (version >= 5) { + accent.patternSlug = data.readString(true); + } + } if (version >= 5) { - accent.patternSlug = data.readString(true); + if (data.readBool(true)) { + accent.account = data.readInt32(true); + accent.info = (TLRPC.TL_theme) TLRPC.Theme.TLdeserialize(data, data.readInt32(true), true); + } } - } - if (version >= 5) { - if (data.readBool(true)) { - accent.account = data.readInt32(true); - accent.info = (TLRPC.TL_theme) TLRPC.Theme.TLdeserialize(data, data.readInt32(true), true); + info.themeAccentsMap.put(accent.id, accent); + if (accent.info != null) { + info.accentsByThemeId.put(accent.info.id, accent); } + newAccents.add(accent); + info.lastAccentId = Math.max(info.lastAccentId, accent.id); + } catch (Throwable e) { + } - info.themeAccentsMap.put(accent.id, accent); - if (accent.info != null) { - info.accentsByThemeId.put(accent.info.id, accent); - } - newAccents.add(accent); - info.lastAccentId = Math.max(info.lastAccentId, accent.id); } } catch (Throwable e) { FileLog.e(e); @@ -4648,8 +5041,9 @@ public class Theme { info.currentAccentId = 100; info.lastAccentId = 101; - SerializedData data = new SerializedData(4 * (15 + 2)); - data.writeInt32(8); + SerializedData data = new SerializedData(4 * (16 + 2)); + //verison + data.writeInt32(9); data.writeInt32(1); data.writeInt32(accent.id); @@ -4855,11 +5249,15 @@ public class Theme { } public static Drawable createEditTextDrawable(Context context, boolean alert) { + return createEditTextDrawable(context, getColor(alert ? key_dialogInputField : key_windowBackgroundWhiteInputField), getColor(alert ? key_dialogInputFieldActivated : key_windowBackgroundWhiteInputFieldActivated)); + } + + public static Drawable createEditTextDrawable(Context context, int color, int colorActivated) { Resources resources = context.getResources(); Drawable defaultDrawable = resources.getDrawable(R.drawable.search_dark).mutate(); - defaultDrawable.setColorFilter(new PorterDuffColorFilter(getColor(alert ? key_dialogInputField : key_windowBackgroundWhiteInputField), PorterDuff.Mode.MULTIPLY)); + defaultDrawable.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); Drawable pressedDrawable = resources.getDrawable(R.drawable.search_dark_activated).mutate(); - pressedDrawable.setColorFilter(new PorterDuffColorFilter(getColor(alert ? key_dialogInputFieldActivated : key_windowBackgroundWhiteInputFieldActivated), PorterDuff.Mode.MULTIPLY)); + pressedDrawable.setColorFilter(new PorterDuffColorFilter(colorActivated, PorterDuff.Mode.MULTIPLY)); StateListDrawable stateListDrawable = new StateListDrawable() { @Override public boolean selectDrawable(int index) { @@ -5087,6 +5485,10 @@ public class Theme { } public static Drawable createServiceDrawable(int rad, View view, View containerView) { + return createServiceDrawable(rad, view, containerView, chat_actionBackgroundPaint); + } + + public static Drawable createServiceDrawable(int rad, View view, View containerView, Paint backgroundPaint) { return new Drawable() { private RectF rect = new RectF(); @@ -5096,9 +5498,9 @@ public class Theme { Rect bounds = getBounds(); rect.set(bounds.left, bounds.top, bounds.right, bounds.bottom); applyServiceShaderMatrixForView(view, containerView); - canvas.drawRoundRect(rect, rad, rad, chat_actionBackgroundPaint); + canvas.drawRoundRect(rect, rad, rad, backgroundPaint); if (hasGradientService()) { - canvas.drawRoundRect(rect, rad, rad, Theme.chat_actionBackgroundGradientDarkenPaint); + canvas.drawRoundRect(rect, rad, rad, chat_actionBackgroundGradientDarkenPaint); } } @@ -5624,7 +6026,11 @@ public class Theme { } public static void applyTheme(ThemeInfo themeInfo, boolean nightTheme) { - applyTheme(themeInfo, true, true, nightTheme); + applyTheme(themeInfo, true, nightTheme); + } + + public static void applyTheme(ThemeInfo themeInfo, boolean save, boolean nightTheme) { + applyTheme(themeInfo, save, true, nightTheme); } private static void applyTheme(ThemeInfo themeInfo, boolean save, boolean removeWallpaperOverride, final boolean nightTheme) { @@ -5787,7 +6193,8 @@ public class Theme { applyDialogsTheme(); applyProfileTheme(); applyChatTheme(false, bg); - AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewTheme, false)); + boolean checkNavigationBarColor = !hasPreviousTheme; + AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewTheme, false, checkNavigationBarColor)); } public static int changeColorAccent(ThemeInfo themeInfo, int accent, int color) { @@ -5940,8 +6347,8 @@ public class Theme { if (!indexOnly) { int N = theme.themeAccents.size(); int count = Math.max(0, N - theme.defaultAccentCount); - SerializedData data = new SerializedData(4 * (count * 15 + 2)); - data.writeInt32(8); + SerializedData data = new SerializedData(4 * (count * 16 + 2)); + data.writeInt32(9); data.writeInt32(count); for (int a = 0; a < N; a++) { ThemeAccent accent = theme.themeAccents.get(a); @@ -5950,6 +6357,7 @@ public class Theme { } data.writeInt32(accent.id); data.writeInt32(accent.accentColor); + data.writeInt32(accent.accentColor2); data.writeInt32(accent.myMessagesAccentColor); data.writeInt32(accent.myMessagesGradientAccentColor1); data.writeInt32(accent.myMessagesGradientAccentColor2); @@ -6023,7 +6431,7 @@ public class Theme { editor.putString("themes2", array.toString()); } for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { - editor.putInt("remoteThemesHash" + (a != 0 ? a : ""), remoteThemesHash[a]); + editor.putLong("2remoteThemesHash" + (a != 0 ? a : ""), remoteThemesHash[a]); editor.putInt("lastLoadingThemesTime" + (a != 0 ? a : ""), lastLoadingThemesTime[a]); } @@ -6717,7 +7125,7 @@ public class Theme { })); } - public static String getBaseThemeKey(TLRPC.TL_themeSettings settings) { + public static String getBaseThemeKey(TLRPC.ThemeSettings settings) { if (settings.base_theme instanceof TLRPC.TL_baseThemeClassic) { return "Blue"; } else if (settings.base_theme instanceof TLRPC.TL_baseThemeDay) { @@ -7619,6 +8027,13 @@ public class Theme { chat_actionBackgroundSelectedPaint = new Paint(Paint.ANTI_ALIAS_FLAG); chat_actionBackgroundPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG); chat_actionBackgroundSelectedPaint2 = new Paint(Paint.ANTI_ALIAS_FLAG); + + addChatPaint(key_paint_chatActionBackground, chat_actionBackgroundPaint, key_chat_serviceBackground); + addChatPaint(key_paint_chatActionBackgroundSelected, chat_actionBackgroundSelectedPaint, key_chat_serviceBackgroundSelected); + addChatPaint(key_paint_chatActionText, chat_actionTextPaint, key_chat_serviceText); + addChatPaint(key_paint_chatBotButton, chat_botButtonPaint, key_chat_botButtonText); + addChatPaint(key_paint_chatComposeBackground, chat_composeBackgroundPaint, key_chat_messagePanelBackground); + addChatPaint(key_paint_chatTimeBackground, chat_timeBackgroundPaint, key_chat_mediaTimeBackground); } } @@ -7659,12 +8074,7 @@ public class Theme { chat_msgOutHalfCheckSelectedDrawable = resources.getDrawable(R.drawable.msg_halfcheck).mutate(); chat_msgMediaHalfCheckDrawable = resources.getDrawable(R.drawable.msg_halfcheck_s).mutate(); chat_msgStickerHalfCheckDrawable = resources.getDrawable(R.drawable.msg_halfcheck_s).mutate(); - chat_msgOutClockDrawable = new MsgClockDrawable(); - chat_msgOutSelectedClockDrawable = new MsgClockDrawable(); - chat_msgInClockDrawable = new MsgClockDrawable(); - chat_msgInSelectedClockDrawable = new MsgClockDrawable(); - chat_msgMediaClockDrawable = new MsgClockDrawable(); - chat_msgStickerClockDrawable = new MsgClockDrawable(); + chat_msgClockDrawable = new MsgClockDrawable(); chat_msgInViewsDrawable = resources.getDrawable(R.drawable.msg_views).mutate(); chat_msgInViewsSelectedDrawable = resources.getDrawable(R.drawable.msg_views).mutate(); chat_msgOutViewsDrawable = resources.getDrawable(R.drawable.msg_views).mutate(); @@ -7865,6 +8275,51 @@ public class Theme { } + defaultChatDrawables.clear(); + defaultChatDrawableColorKeys.clear(); + + addChatDrawable(key_drawable_botInline, chat_botInlineDrawable, key_chat_serviceIcon); + addChatDrawable(key_drawable_botLink, chat_botLinkDrawalbe, key_chat_serviceIcon); + addChatDrawable(key_drawable_goIcon, chat_goIconDrawable, key_chat_serviceIcon); + addChatDrawable(key_drawable_commentSticker, chat_commentStickerDrawable, key_chat_serviceIcon); + addChatDrawable(key_drawable_msgError, chat_msgErrorDrawable, key_chat_sentErrorIcon); + addChatDrawable(key_drawable_msgIn, chat_msgInDrawable, null); + addChatDrawable(key_drawable_msgInSelected, chat_msgInSelectedDrawable, null); + addChatDrawable(key_drawable_msgInMedia, chat_msgInMediaDrawable, null); + addChatDrawable(key_drawable_msgInMediaSelected, chat_msgInMediaSelectedDrawable, null); + addChatDrawable(key_drawable_msgOut, chat_msgOutDrawable, null); + addChatDrawable(key_drawable_msgOutSelected, chat_msgOutSelectedDrawable, null); + addChatDrawable(key_drawable_msgOutMedia, chat_msgOutMediaDrawable, null); + addChatDrawable(key_drawable_msgOutMediaSelected, chat_msgOutMediaSelectedDrawable, null); + addChatDrawable(key_drawable_msgOutCallAudio, chat_msgOutCallDrawable[0], key_chat_outInstant); + addChatDrawable(key_drawable_msgOutCallAudioSelected, chat_msgOutCallSelectedDrawable[0], key_chat_outInstantSelected); + addChatDrawable(key_drawable_msgOutCallVideo, chat_msgOutCallDrawable[1], key_chat_outInstant); + addChatDrawable(key_drawable_msgOutCallVideoSelected, chat_msgOutCallSelectedDrawable[1], key_chat_outInstantSelected); + addChatDrawable(key_drawable_msgOutCheck, chat_msgOutCheckDrawable, key_chat_outSentCheck); + addChatDrawable(key_drawable_msgOutCheckSelected, chat_msgOutCheckSelectedDrawable, key_chat_outSentCheckSelected); + addChatDrawable(key_drawable_msgOutCheckRead, chat_msgOutCheckReadDrawable, key_chat_outSentCheckRead); + addChatDrawable(key_drawable_msgOutCheckReadSelected, chat_msgOutCheckReadSelectedDrawable, key_chat_outSentCheckReadSelected); + addChatDrawable(key_drawable_msgOutHalfCheck, chat_msgOutHalfCheckDrawable, key_chat_outSentCheckRead); + addChatDrawable(key_drawable_msgOutHalfCheckSelected, chat_msgOutHalfCheckSelectedDrawable, key_chat_outSentCheckReadSelected); + addChatDrawable(key_drawable_msgOutInstant, chat_msgOutInstantDrawable, key_chat_outInstant); + addChatDrawable(key_drawable_msgOutMenu, chat_msgOutMenuDrawable, key_chat_outMenu); + addChatDrawable(key_drawable_msgOutMenuSelected, chat_msgOutMenuSelectedDrawable, key_chat_outMenuSelected); + addChatDrawable(key_drawable_msgOutPinned, chat_msgOutPinnedDrawable, key_chat_outViews); + addChatDrawable(key_drawable_msgOutPinnedSelected, chat_msgOutPinnedSelectedDrawable, key_chat_outViewsSelected); + addChatDrawable(key_drawable_msgOutReplies, chat_msgOutRepliesDrawable, key_chat_outViews); + addChatDrawable(key_drawable_msgOutRepliesSelected, chat_msgOutRepliesSelectedDrawable, key_chat_outViewsSelected); + addChatDrawable(key_drawable_msgOutViews, chat_msgOutViewsDrawable, key_chat_outViews); + addChatDrawable(key_drawable_msgOutViewsSelected, chat_msgOutViewsSelectedDrawable, key_chat_outViewsSelected); + addChatDrawable(key_drawable_msgStickerCheck, chat_msgStickerCheckDrawable, key_chat_serviceText); + addChatDrawable(key_drawable_msgStickerHalfCheck, chat_msgStickerHalfCheckDrawable, key_chat_serviceText); + addChatDrawable(key_drawable_msgStickerPinned, chat_msgStickerPinnedDrawable, key_chat_serviceText); + addChatDrawable(key_drawable_msgStickerReplies, chat_msgStickerRepliesDrawable, key_chat_serviceText); + addChatDrawable(key_drawable_msgStickerViews, chat_msgStickerViewsDrawable, key_chat_serviceText); + addChatDrawable(key_drawable_replyIcon, chat_replyIconDrawable, key_chat_serviceIcon); + addChatDrawable(key_drawable_shareIcon, chat_shareIconDrawable, key_chat_serviceIcon); + addChatDrawable(key_drawable_muteIconDrawable, chat_muteIconDrawable, key_chat_muteIcon); + addChatDrawable(key_drawable_lockIconDrawable, chat_lockIconDrawable, key_chat_lockIcon); + applyChatTheme(fontsOnly, false); } @@ -7968,16 +8423,10 @@ public class Theme { setDrawableColorByKey(chat_msgOutCheckReadSelectedDrawable, key_chat_outSentCheckReadSelected); setDrawableColorByKey(chat_msgOutHalfCheckDrawable, key_chat_outSentCheckRead); setDrawableColorByKey(chat_msgOutHalfCheckSelectedDrawable, key_chat_outSentCheckReadSelected); - setDrawableColorByKey(chat_msgOutClockDrawable, key_chat_outSentClock); - setDrawableColorByKey(chat_msgOutSelectedClockDrawable, key_chat_outSentClockSelected); - setDrawableColorByKey(chat_msgInClockDrawable, key_chat_inSentClock); - setDrawableColorByKey(chat_msgInSelectedClockDrawable, key_chat_inSentClockSelected); setDrawableColorByKey(chat_msgMediaCheckDrawable, key_chat_mediaSentCheck); setDrawableColorByKey(chat_msgMediaHalfCheckDrawable, key_chat_mediaSentCheck); - setDrawableColorByKey(chat_msgMediaClockDrawable, key_chat_mediaSentClock); setDrawableColorByKey(chat_msgStickerCheckDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerHalfCheckDrawable, key_chat_serviceText); - setDrawableColorByKey(chat_msgStickerClockDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerViewsDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerRepliesDrawable, key_chat_serviceText); setDrawableColorByKey(chat_shareIconDrawable, key_chat_serviceIcon); @@ -8145,22 +8594,26 @@ public class Theme { } public static void applyServiceShaderMatrix(int w, int h, float translationX, float translationY) { - if (serviceBitmapShader == null) { + applyServiceShaderMatrix(serviceBitmap, serviceBitmapShader, serviceBitmapMatrix, w, h, translationX, translationY); + } + + public static void applyServiceShaderMatrix(Bitmap bitmap, BitmapShader shader, Matrix matrix, int w, int h, float translationX, float translationY) { + if (shader == null) { return; } - float bitmapWidth = serviceBitmap.getWidth(); - float bitmapHeight = serviceBitmap.getHeight(); + float bitmapWidth = bitmap.getWidth(); + float bitmapHeight = bitmap.getHeight(); float maxScale = Math.max(w / bitmapWidth, h / bitmapHeight); float width = bitmapWidth * maxScale; float height = bitmapHeight * maxScale; float x = (w - width) / 2; float y = (h - height) / 2; - serviceBitmapMatrix.reset(); - serviceBitmapMatrix.setTranslate(x - translationX, y - translationY); - serviceBitmapMatrix.preScale(maxScale, maxScale); - serviceBitmapShader.setLocalMatrix(serviceBitmapMatrix); + matrix.reset(); + matrix.setTranslate(x - translationX, y - translationY); + matrix.preScale(maxScale, maxScale); + shader.setLocalMatrix(matrix); } public static void applyChatServiceMessageColor(int[] custom, Drawable wallpaperOverride) { @@ -8211,11 +8664,9 @@ public class Theme { setDrawableColor(chat_msgStickerPinnedDrawable, 0xffffffff); setDrawableColor(chat_msgStickerCheckDrawable, 0xffffffff); setDrawableColor(chat_msgStickerHalfCheckDrawable, 0xffffffff); - setDrawableColor(chat_msgStickerClockDrawable, 0xffffffff); setDrawableColor(chat_msgStickerViewsDrawable, 0xffffffff); setDrawableColor(chat_msgStickerRepliesDrawable, 0xffffffff); chat_actionTextPaint.setColor(0xffffffff); - chat_actionTextPaint.setColor(0xffffffff); chat_actionTextPaint.linkColor = 0xffffffff; chat_botButtonPaint.setColor(0xffffffff); setDrawableColor(chat_commentStickerDrawable, 0xffffffff); @@ -8231,11 +8682,9 @@ public class Theme { setDrawableColorByKey(chat_msgStickerPinnedDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerCheckDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerHalfCheckDrawable, key_chat_serviceText); - setDrawableColorByKey(chat_msgStickerClockDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerViewsDrawable, key_chat_serviceText); setDrawableColorByKey(chat_msgStickerRepliesDrawable, key_chat_serviceText); chat_actionTextPaint.setColor(getColor(key_chat_serviceText)); - chat_actionTextPaint.setColor(getColor(key_chat_serviceText)); chat_actionTextPaint.linkColor = getColor(key_chat_serviceLink); setDrawableColorByKey(chat_commentStickerDrawable, key_chat_serviceIcon); setDrawableColorByKey(chat_shareIconDrawable, key_chat_serviceIcon); @@ -8256,7 +8705,7 @@ public class Theme { chat_actionBackgroundPaint.setShader(serviceBitmapShader); chat_actionBackgroundSelectedPaint.setShader(serviceBitmapShader); ColorMatrix colorMatrix = new ColorMatrix(); - colorMatrix.setSaturation(1.8f); + colorMatrix.setSaturation(((MotionBackgroundDrawable) drawable).getIntensity() >= 0 ? 1.8f : 0.5f); chat_actionBackgroundPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); chat_actionBackgroundPaint.setAlpha(127); @@ -8397,6 +8846,15 @@ public class Theme { return getColor(key, null, true); } + public static int getColor(String key, ResourcesProvider provider) { + if (provider != null) { + Integer colorInteger = provider.getColor(key); + if (colorInteger != null) { + return colorInteger; + } + } + return getColor(key); + } public static int getColor(String key) { return getColor(key, null, false); } @@ -8418,7 +8876,9 @@ public class Theme { } if (currentTheme == defaultTheme) { boolean useDefault; - if (myMessagesColorKeys.contains(key)) { + if (myMessagesBubblesColorKeys.contains(key)) { + useDefault = currentTheme.isDefaultMyMessagesBubbles(); + } else if (myMessagesColorKeys.contains(key)) { useDefault = currentTheme.isDefaultMyMessages(); } else if (key_chat_wallpaper.equals(key) || key_chat_wallpaper_gradient_to1.equals(key) || key_chat_wallpaper_gradient_to2.equals(key) || key_chat_wallpaper_gradient_to3.equals(key)) { useDefault = false; @@ -8674,9 +9134,13 @@ public class Theme { File wallpaperFile; boolean wallpaperMotion; ThemeAccent accent = currentTheme.getAccent(false); + TLRPC.Document wallpaperDocument = null; if (accent != null) { wallpaperFile = accent.getPathToWallpaper(); wallpaperMotion = accent.patternMotion; + if (accent.info != null && accent.info.settings != null && accent.info.settings.wallpaper != null) { + wallpaperDocument = accent.info.settings.wallpaper.document; + } } else { wallpaperFile = null; wallpaperMotion = false; @@ -8684,167 +9148,36 @@ public class Theme { int intensity; OverrideWallpaperInfo overrideWallpaper = currentTheme.overrideWallpaper; if (overrideWallpaper != null) { - intensity = overrideWallpaper != null ? (int) (overrideWallpaper.intensity * 100) : 100; + intensity = (int) (overrideWallpaper.intensity * 100); } else { intensity = (int) (accent != null ? (accent.patternIntensity * 100) : currentTheme.patternIntensity); } + TLRPC.Document finalWallpaperDocument = wallpaperDocument; Utilities.searchQueue.postRunnable(wallpaperLoadTask = () -> { - boolean overrideTheme = (!hasPreviousTheme || isApplyingAccent) && overrideWallpaper != null; - if (overrideWallpaper != null) { - isWallpaperMotion = overrideWallpaper != null && overrideWallpaper.isMotion; - isPatternWallpaper = overrideWallpaper != null && overrideWallpaper.color != 0 && !overrideWallpaper.isDefault() && !overrideWallpaper.isColor(); - } else { - isWallpaperMotion = currentTheme.isMotion; - isPatternWallpaper = currentTheme.patternBgColor != 0; - } + BackgroundDrawableSettings settings = createBackgroundDrawable( + currentTheme, + overrideWallpaper, + currentColors, + wallpaperFile, + themedWallpaperLink, + themedWallpaperFileOffset, + intensity, + previousPhase, + defaultTheme, + hasPreviousTheme, + isApplyingAccent, + wallpaperMotion, + finalWallpaperDocument + ); + isWallpaperMotion = settings.isWallpaperMotion != null ? settings.isWallpaperMotion : isWallpaperMotion; + isPatternWallpaper = settings.isPatternWallpaper != null ? settings.isPatternWallpaper : isPatternWallpaper; + isCustomTheme = settings.isCustomTheme != null ? settings.isCustomTheme : isCustomTheme; patternIntensity = intensity; - if (!overrideTheme) { - Integer backgroundColor = defaultTheme ? null : currentColors.get(key_chat_wallpaper); - Integer gradientToColor3 = currentColors.get(key_chat_wallpaper_gradient_to3); - if (gradientToColor3 == null) { - gradientToColor3 = 0; - } - Integer gradientToColor2 = currentColors.get(key_chat_wallpaper_gradient_to2); - Integer gradientToColor1 = currentColors.get(key_chat_wallpaper_gradient_to1); - if (wallpaperFile != null && wallpaperFile.exists()) { - try { - if (backgroundColor != null && gradientToColor1 != null && gradientToColor2 != null) { - MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, false); - motionBackgroundDrawable.setPatternBitmap(patternIntensity, BitmapFactory.decodeFile(wallpaperFile.getAbsolutePath())); - wallpaper = motionBackgroundDrawable; - } else { - wallpaper = Drawable.createFromPath(wallpaperFile.getAbsolutePath()); - } - isWallpaperMotion = wallpaperMotion; - isCustomTheme = true; - isPatternWallpaper = true; - } catch (Throwable e) { - FileLog.e(e); - } - } else if (backgroundColor != null) { - Integer rotation = currentColors.get(key_chat_wallpaper_gradient_rotation); - if (rotation == null) { - rotation = 45; - } - if (gradientToColor1 != null && gradientToColor2 != null) { - MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, false); - motionBackgroundDrawable.setPhase(previousPhase); - wallpaper = motionBackgroundDrawable; - } else if (gradientToColor1 == null || gradientToColor1.equals(backgroundColor)) { - wallpaper = new ColorDrawable(backgroundColor); - } else { - final int[] colors = {backgroundColor, gradientToColor1}; - final BackgroundGradientDrawable.Orientation orientation = BackgroundGradientDrawable.getGradientOrientation(rotation); - final BackgroundGradientDrawable backgroundGradientDrawable = new BackgroundGradientDrawable(orientation, colors); - final BackgroundGradientDrawable.Listener listener = new BackgroundGradientDrawable.ListenerAdapter() { - @Override - public void onSizeReady(int width, int height) { - final boolean isOrientationPortrait = AndroidUtilities.displaySize.x <= AndroidUtilities.displaySize.y; - final boolean isGradientPortrait = width <= height; - if (isOrientationPortrait == isGradientPortrait) { - NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewWallpapper); - } - } - }; - backgroundGradientDisposable = backgroundGradientDrawable.startDithering(BackgroundGradientDrawable.Sizes.ofDeviceScreen(), listener, 100); - wallpaper = backgroundGradientDrawable; - } - isCustomTheme = true; - } else if (themedWallpaperLink != null) { - try { - File pathToWallpaper = new File(ApplicationLoader.getFilesDirFixed(), Utilities.MD5(themedWallpaperLink) + ".wp"); - Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(pathToWallpaper), 0); - if (bitmap != null) { - themedWallpaper = wallpaper = new BitmapDrawable(bitmap); - isCustomTheme = true; - } - } catch (Exception e) { - FileLog.e(e); - } - } else if (themedWallpaperFileOffset > 0 && (currentTheme.pathToFile != null || currentTheme.assetName != null)) { - try { - File file; - if (currentTheme.assetName != null) { - file = getAssetFile(currentTheme.assetName); - } else { - file = new File(currentTheme.pathToFile); - } - Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(file), themedWallpaperFileOffset); - if (bitmap != null) { - themedWallpaper = wallpaper = new BitmapDrawable(bitmap); - isCustomTheme = true; - } - } catch (Throwable e) { - FileLog.e(e); - } - } - } - if (wallpaper == null) { - int selectedColor = overrideWallpaper != null ? overrideWallpaper.color : 0; - try { - if (overrideWallpaper == null || overrideWallpaper.isDefault()) { - wallpaper = createDefaultWallpaper(); - isCustomTheme = false; - } else if (!overrideWallpaper.isColor() || overrideWallpaper.gradientColor1 != 0) { - if (selectedColor != 0 && (!isPatternWallpaper || overrideWallpaper.gradientColor2 != 0)) { - if (overrideWallpaper.gradientColor1 != 0 && overrideWallpaper.gradientColor2 != 0) { - MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(overrideWallpaper.color, overrideWallpaper.gradientColor1, overrideWallpaper.gradientColor2, overrideWallpaper.gradientColor3, false); - motionBackgroundDrawable.setPhase(previousPhase); - if (isPatternWallpaper) { - File toFile = new File(ApplicationLoader.getFilesDirFixed(), overrideWallpaper.fileName); - if (toFile.exists()) { - motionBackgroundDrawable.setPatternBitmap((int) (overrideWallpaper.intensity * 100), loadScreenSizedBitmap(new FileInputStream(toFile), 0)); - isCustomTheme = true; - } - } - wallpaper = motionBackgroundDrawable; - } else if (overrideWallpaper.gradientColor1 != 0) { - final int[] colors = {selectedColor, overrideWallpaper.gradientColor1}; - final BackgroundGradientDrawable.Orientation orientation = BackgroundGradientDrawable.getGradientOrientation(overrideWallpaper.rotation); - final BackgroundGradientDrawable backgroundGradientDrawable = new BackgroundGradientDrawable(orientation, colors); - final BackgroundGradientDrawable.Listener listener = new BackgroundGradientDrawable.ListenerAdapter() { - @Override - public void onSizeReady(int width, int height) { - final boolean isOrientationPortrait = AndroidUtilities.displaySize.x <= AndroidUtilities.displaySize.y; - final boolean isGradientPortrait = width <= height; - if (isOrientationPortrait == isGradientPortrait) { - NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewWallpapper); - } - } - }; - backgroundGradientDisposable = backgroundGradientDrawable.startDithering(BackgroundGradientDrawable.Sizes.ofDeviceScreen(), listener, 100); - wallpaper = backgroundGradientDrawable; - } else { - wallpaper = new ColorDrawable(selectedColor); - } - } else { - File toFile = new File(ApplicationLoader.getFilesDirFixed(), overrideWallpaper.fileName); - if (toFile.exists()) { - Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(toFile), 0); - if (bitmap != null) { - wallpaper = new BitmapDrawable(bitmap); - isCustomTheme = true; - } - } - if (wallpaper == null) { - wallpaper = createDefaultWallpaper(); - isCustomTheme = false; - } - } - } - } catch (Throwable throwable) { - //ignore - } - if (wallpaper == null) { - if (selectedColor == 0) { - selectedColor = -2693905; - } - wallpaper = new ColorDrawable(selectedColor); - } - } - calcBackgroundColor(wallpaper, 1); - Drawable drawable = wallpaper; + wallpaper = settings.wallpaper != null ? settings.wallpaper : wallpaper; + Drawable drawable = settings.wallpaper; + calcBackgroundColor(drawable, 1); + AndroidUtilities.runOnUIThread(() -> { wallpaperLoadTask = null; createCommonChatResources(); @@ -8854,6 +9187,218 @@ public class Theme { }); } + public static BackgroundDrawableSettings createBackgroundDrawable( + ThemeInfo currentTheme, + HashMap currentColors, + String wallpaperLink, + int prevoiusPhase + ) { + boolean defaultTheme = currentTheme.firstAccentIsDefault && currentTheme.currentAccentId == DEFALT_THEME_ACCENT_ID; + ThemeAccent accent = currentTheme.getAccent(false); + File wallpaperFile = accent != null ? accent.getPathToWallpaper() : null; + boolean wallpaperMotion = accent != null && accent.patternMotion; + OverrideWallpaperInfo overrideWallpaper = currentTheme.overrideWallpaper; + int intensity = overrideWallpaper != null + ? (int) (overrideWallpaper.intensity * 100) + : (int) (accent != null ? (accent.patternIntensity * 100) : currentTheme.patternIntensity); + Integer offset = currentColorsNoAccent.get("wallpaperFileOffset"); + int wallpaperFileOffset = offset != null ? offset : -1; + return createBackgroundDrawable(currentTheme, overrideWallpaper, currentColors, wallpaperFile, wallpaperLink, wallpaperFileOffset, intensity, prevoiusPhase, defaultTheme, false, false, wallpaperMotion, null); + } + + public static BackgroundDrawableSettings createBackgroundDrawable( + ThemeInfo currentTheme, + OverrideWallpaperInfo overrideWallpaper, + HashMap currentColors, + File wallpaperFile, + String themedWallpaperLink, + int themedWallpaperFileOffset, + int intensity, + int previousPhase, + boolean defaultTheme, + boolean hasPreviousTheme, + boolean isApplyingAccent, + boolean wallpaperMotion, + TLRPC.Document wallpaperDocument + ) { + BackgroundDrawableSettings settings = new BackgroundDrawableSettings(); + settings.wallpaper = wallpaper; + boolean overrideTheme = (!hasPreviousTheme || isApplyingAccent) && overrideWallpaper != null; + if (overrideWallpaper != null) { + settings.isWallpaperMotion = overrideWallpaper.isMotion; + settings.isPatternWallpaper = overrideWallpaper.color != 0 && !overrideWallpaper.isDefault() && !overrideWallpaper.isColor(); + } else { + settings.isWallpaperMotion = currentTheme.isMotion; + settings.isPatternWallpaper = currentTheme.patternBgColor != 0; + } + if (!overrideTheme) { + Integer backgroundColor = defaultTheme ? null : currentColors.get(key_chat_wallpaper); + Integer gradientToColor3 = currentColors.get(key_chat_wallpaper_gradient_to3); + if (gradientToColor3 == null) { + gradientToColor3 = 0; + } + Integer gradientToColor2 = currentColors.get(key_chat_wallpaper_gradient_to2); + gradientToColor2 = currentColors.get(key_chat_wallpaper_gradient_to2); + Integer gradientToColor1 = currentColors.get(key_chat_wallpaper_gradient_to1); + if (wallpaperFile != null && wallpaperFile.exists()) { + try { + if (backgroundColor != null && gradientToColor1 != null && gradientToColor2 != null) { + MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, false); + motionBackgroundDrawable.setPatternBitmap(intensity, BitmapFactory.decodeFile(wallpaperFile.getAbsolutePath())); + motionBackgroundDrawable.setPatternColorFilter(motionBackgroundDrawable.getPatternColor()); + settings.wallpaper = motionBackgroundDrawable; + } else { + settings.wallpaper = Drawable.createFromPath(wallpaperFile.getAbsolutePath()); + } + settings.isWallpaperMotion = wallpaperMotion; + settings.isPatternWallpaper = true; + settings.isCustomTheme = true; + } catch (Throwable e) { + FileLog.e(e); + } + } else if (backgroundColor != null) { + Integer rotation = currentColors.get(key_chat_wallpaper_gradient_rotation); + if (rotation == null) { + rotation = 45; + } + if (gradientToColor1 != null && gradientToColor2 != null) { + MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, false); + Bitmap pattensBitmap = null; + + if (wallpaperFile != null && wallpaperDocument != null) { + File f = FileLoader.getPathToAttach(wallpaperDocument, true); + pattensBitmap = SvgHelper.getBitmap(f, AndroidUtilities.dp(360), AndroidUtilities.dp(640), false); + if (pattensBitmap != null) { + FileOutputStream stream = null; + try { + stream = new FileOutputStream(wallpaperFile); + pattensBitmap.compress(Bitmap.CompressFormat.PNG, 87, stream); + stream.close(); + } catch (Exception e) { + FileLog.e(e); + e.printStackTrace(); + } + } + } + motionBackgroundDrawable.setPatternBitmap(intensity, pattensBitmap); + motionBackgroundDrawable.setPhase(previousPhase); + settings.wallpaper = motionBackgroundDrawable; + } else if (gradientToColor1 == null || gradientToColor1.equals(backgroundColor)) { + settings.wallpaper = new ColorDrawable(backgroundColor); + } else { + final int[] colors = {backgroundColor, gradientToColor1}; + final BackgroundGradientDrawable.Orientation orientation = BackgroundGradientDrawable.getGradientOrientation(rotation); + final BackgroundGradientDrawable backgroundGradientDrawable = new BackgroundGradientDrawable(orientation, colors); + final BackgroundGradientDrawable.Listener listener = new BackgroundGradientDrawable.ListenerAdapter() { + @Override + public void onSizeReady(int width, int height) { + final boolean isOrientationPortrait = AndroidUtilities.displaySize.x <= AndroidUtilities.displaySize.y; + final boolean isGradientPortrait = width <= height; + if (isOrientationPortrait == isGradientPortrait) { + NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewWallpapper); + } + } + }; + backgroundGradientDisposable = backgroundGradientDrawable.startDithering(BackgroundGradientDrawable.Sizes.ofDeviceScreen(), listener, 100); + settings.wallpaper = backgroundGradientDrawable; + } + settings.isCustomTheme = true; + } else if (themedWallpaperLink != null) { + try { + File pathToWallpaper = new File(ApplicationLoader.getFilesDirFixed(), Utilities.MD5(themedWallpaperLink) + ".wp"); + Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(pathToWallpaper), 0); + if (bitmap != null) { + settings.wallpaper = new BitmapDrawable(bitmap); + settings.themedWallpaper = settings.wallpaper; + settings.isCustomTheme = true; + } + } catch (Exception e) { + FileLog.e(e); + } + } else if (themedWallpaperFileOffset > 0 && (currentTheme.pathToFile != null || currentTheme.assetName != null)) { + try { + File file; + if (currentTheme.assetName != null) { + file = getAssetFile(currentTheme.assetName); + } else { + file = new File(currentTheme.pathToFile); + } + Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(file), themedWallpaperFileOffset); + if (bitmap != null) { + settings.wallpaper = settings.themedWallpaper = wallpaper = new BitmapDrawable(bitmap); + settings.isCustomTheme = true; + } + } catch (Throwable e) { + FileLog.e(e); + } + } + } + if (settings.wallpaper == null) { + int selectedColor = overrideWallpaper != null ? overrideWallpaper.color : 0; + try { + if (overrideWallpaper == null || overrideWallpaper.isDefault()) { + settings.wallpaper = createDefaultWallpaper(); + settings.isCustomTheme = false; + } else if (!overrideWallpaper.isColor() || overrideWallpaper.gradientColor1 != 0) { + if (selectedColor != 0 && (!isPatternWallpaper || overrideWallpaper.gradientColor2 != 0)) { + if (overrideWallpaper.gradientColor1 != 0 && overrideWallpaper.gradientColor2 != 0) { + MotionBackgroundDrawable motionBackgroundDrawable = new MotionBackgroundDrawable(overrideWallpaper.color, overrideWallpaper.gradientColor1, overrideWallpaper.gradientColor2, overrideWallpaper.gradientColor3, false); + motionBackgroundDrawable.setPhase(previousPhase); + if (settings.isPatternWallpaper) { + File toFile = new File(ApplicationLoader.getFilesDirFixed(), overrideWallpaper.fileName); + if (toFile.exists()) { + motionBackgroundDrawable.setPatternBitmap((int) (overrideWallpaper.intensity * 100), loadScreenSizedBitmap(new FileInputStream(toFile), 0)); + settings.isCustomTheme = true; + } + } + settings.wallpaper = motionBackgroundDrawable; + } else if (overrideWallpaper.gradientColor1 != 0) { + final int[] colors = {selectedColor, overrideWallpaper.gradientColor1}; + final BackgroundGradientDrawable.Orientation orientation = BackgroundGradientDrawable.getGradientOrientation(overrideWallpaper.rotation); + final BackgroundGradientDrawable backgroundGradientDrawable = new BackgroundGradientDrawable(orientation, colors); + final BackgroundGradientDrawable.Listener listener = new BackgroundGradientDrawable.ListenerAdapter() { + @Override + public void onSizeReady(int width, int height) { + final boolean isOrientationPortrait = AndroidUtilities.displaySize.x <= AndroidUtilities.displaySize.y; + final boolean isGradientPortrait = width <= height; + if (isOrientationPortrait == isGradientPortrait) { + NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didSetNewWallpapper); + } + } + }; + backgroundGradientDisposable = backgroundGradientDrawable.startDithering(BackgroundGradientDrawable.Sizes.ofDeviceScreen(), listener, 100); + settings.wallpaper = backgroundGradientDrawable; + } else { + settings.wallpaper = new ColorDrawable(selectedColor); + } + } else { + File toFile = new File(ApplicationLoader.getFilesDirFixed(), overrideWallpaper.fileName); + if (toFile.exists()) { + Bitmap bitmap = loadScreenSizedBitmap(new FileInputStream(toFile), 0); + if (bitmap != null) { + settings.wallpaper = new BitmapDrawable(bitmap); + settings.isCustomTheme = true; + } + } + if (settings.wallpaper == null) { + settings.wallpaper = createDefaultWallpaper(); + settings.isCustomTheme = false; + } + } + } + } catch (Throwable throwable) { + //ignore + } + if (settings.wallpaper == null) { + if (selectedColor == 0) { + selectedColor = -2693905; + } + settings.wallpaper = new ColorDrawable(selectedColor); + } + } + return settings; + } + public static Drawable createDefaultWallpaper() { return createDefaultWallpaper(0, 0); } @@ -8864,13 +9409,8 @@ public class Theme { w = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); h = Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y); } - int patternColor; - if (Build.VERSION.SDK_INT >= 29) { - patternColor = 0x57000000; - } else { - patternColor = motionBackgroundDrawable.getPatternColor(); - } - motionBackgroundDrawable.setPatternBitmap(34, SvgHelper.getBitmap(R.raw.default_pattern, w, h, patternColor)); + motionBackgroundDrawable.setPatternBitmap(34, SvgHelper.getBitmap(R.raw.default_pattern, w, h, Color.BLACK)); + motionBackgroundDrawable.setPatternColorFilter(motionBackgroundDrawable.getPatternColor()); return motionBackgroundDrawable; } @@ -9020,6 +9560,7 @@ public class Theme { intensity = 100; } motionBackgroundDrawable.setPatternBitmap(intensity, bitmap); + motionBackgroundDrawable.setPatternColorFilter(motionBackgroundDrawable.getPatternColor()); return motionBackgroundDrawable; } if (bitmap != null) { @@ -9155,7 +9696,7 @@ public class Theme { chat_status_drawables[2] = new SendingFileDrawable(true); break; case 3: - chat_status_drawables[3] = new PlayingGameDrawable(true); + chat_status_drawables[3] = new PlayingGameDrawable(true, null); break; case 4: chat_status_drawables[4] = new RoundStatusDrawable(true); @@ -9183,4 +9724,56 @@ public class Theme { } return roundPlayDrawable; } + + public static HashMap getFallbackKeys() { + return fallbackKeys; + } + + public static String getFallbackKey(String key) { + return fallbackKeys.get(key); + } + + public static Map getThemeDrawablesMap() { + return defaultChatDrawables; + } + + public static Drawable getThemeDrawable(String drawableKey) { + return defaultChatDrawables.get(drawableKey); + } + + public static String getThemeDrawableColorKey(String drawableKey) { + return defaultChatDrawableColorKeys.get(drawableKey); + } + + public static Map getThemePaintsMap() { + return defaultChatPaints; + } + + public static Paint getThemePaint(String paintKey) { + return defaultChatPaints.get(paintKey); + } + + public static String getThemePaintColorKey(String paintKey) { + return defaultChatPaintColors.get(paintKey); + } + + private static void addChatDrawable(String key, Drawable drawable, String colorKey) { + defaultChatDrawables.put(key, drawable); + if (colorKey != null) { + defaultChatDrawableColorKeys.put(key, colorKey); + } + } + + private static void addChatPaint(String key, Paint paint, String colorKey) { + defaultChatPaints.put(key, paint); + if (colorKey != null) { + defaultChatPaintColors.put(key, colorKey); + } + } + + public static void setColorToPaint(Paint paint, int color) { + if (paint.getColor() != color) { + paint.setColor(color); + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ThemeDescription.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ThemeDescription.java index a61dcad1c..68999bd3d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ThemeDescription.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ThemeDescription.java @@ -19,6 +19,7 @@ import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.os.Build; +import android.text.Spanned; import android.text.SpannedString; import android.text.TextPaint; import android.view.View; @@ -30,6 +31,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.FileLog; +import org.telegram.ui.Components.AnimatedArrowDrawable; import org.telegram.ui.Components.AudioPlayerAlert; import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.BackupImageView; @@ -115,9 +117,11 @@ public class ThemeDescription { private HashMap cachedFields; private HashMap notFoundCachedFields; + public Theme.ResourcesProvider resourcesProvider; public interface ThemeDescriptionDelegate { void didSetColor(); + default void onAnimationProgress(float progress) {} } public ThemeDescription(View view, int flags, Class[] classes, Paint[] paint, Drawable[] drawables, ThemeDescriptionDelegate themeDescriptionDelegate, String key, Object unused) { @@ -254,6 +258,8 @@ public class ThemeDescription { } } else if (drawablesToUpdate[a] instanceof AvatarDrawable) { ((AvatarDrawable) drawablesToUpdate[a]).setColor(color); + } else if (drawablesToUpdate[a] instanceof AnimatedArrowDrawable) { + ((AnimatedArrowDrawable) drawablesToUpdate[a]).setColor(color); } else { drawablesToUpdate[a].setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); } @@ -734,6 +740,15 @@ public class ThemeDescription { TextView textView = i == 0 ? ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getTextView() : ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getNextTextView(); if (textView != null) { textView.setTextColor(color); + CharSequence text = textView.getText(); + if (text instanceof SpannedString) { + TypefaceSpan[] spans = ((SpannedString) text).getSpans(0, text.length(), TypefaceSpan.class); + if (spans != null && spans.length > 0) { + for (int spanIdx = 0; spanIdx < spans.length; spanIdx++) { + spans[spanIdx].setColor(color); + } + } + } } } } @@ -765,7 +780,16 @@ public class ThemeDescription { } public int getSetColor() { - return Theme.getColor(currentKey); + Integer color = resourcesProvider != null ? resourcesProvider.getColor(currentKey) : null; + return color != null ? color : Theme.getColor(currentKey); + } + + public void setAnimatedColor(int color) { + if (resourcesProvider != null) { + resourcesProvider.setAnimatedColor(getCurrentKey(), color); + } else { + Theme.setAnimatedColor(getCurrentKey(), color); + } } public void setDefaultColor() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionIntroActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionIntroActivity.java index 0198a518c..caf0a1ab9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionIntroActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionIntroActivity.java @@ -460,7 +460,7 @@ public class ActionIntroActivity extends BaseFragment implements LocationControl desctiptionLines[a * 2 + 1].setText(spanned); } else if (a == 1) { desctiptionLines[a * 2 + 1].setText(LocaleController.getString("AuthAnotherClientInfo2", R.string.AuthAnotherClientInfo2)); - } else if (a == 2) { + } else { desctiptionLines[a * 2 + 1].setText(LocaleController.getString("AuthAnotherClientInfo3", R.string.AuthAnotherClientInfo3)); } if (LocaleController.isRTL) { @@ -555,9 +555,8 @@ public class ActionIntroActivity extends BaseFragment implements LocationControl return; } Bundle args = new Bundle(); - ArrayList result = new ArrayList<>(); - result.add(getUserConfig().getClientUserId()); - args.putIntegerArrayList("result", result); + long[] array = new long[]{getUserConfig().getClientUserId()}; + args.putLongArray("result", array); args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP); args.putString("address", currentGroupCreateAddress); args.putParcelable("location", currentGroupCreateLocation); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java index ac1638844..5d6577604 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java @@ -12,6 +12,7 @@ import android.location.Location; import android.os.Build; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.UserConfig; @@ -144,12 +145,10 @@ public abstract class BaseLocationAdapter extends RecyclerListView.SelectionAdap req.geo_point._long = AndroidUtilities.fixLocationCoord(coordinate.getLongitude()); req.flags |= 1; - int lower_id = (int) dialogId; - int high_id = (int) (dialogId >> 32); - if (lower_id != 0) { - req.peer = MessagesController.getInstance(currentAccount).getInputPeer(lower_id); - } else { + if (DialogObject.isEncryptedDialog(dialogId)) { req.peer = new TLRPC.TL_inputPeerEmpty(); + } else { + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); } currentRequestNum = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsAdapter.java index b4122eeda..ac2d743b0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/ContactsAdapter.java @@ -12,7 +12,6 @@ import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; -import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; @@ -44,6 +43,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.RecyclerView; public class ContactsAdapter extends RecyclerListView.SectionsAdapter { @@ -52,8 +52,8 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter { private Context mContext; private int onlyUsers; private boolean needPhonebook; - private SparseArray ignoreUsers; - private SparseArray checkedMap; + private LongSparseArray ignoreUsers; + private LongSparseArray checkedMap; private ArrayList onlineContacts; private boolean scrolling; private boolean isAdmin; @@ -63,7 +63,7 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter { private boolean hasGps; private boolean isEmpty; - public ContactsAdapter(Context context, int onlyUsersType, boolean showPhoneBook, SparseArray usersToIgnore, int flags, boolean gps) { + public ContactsAdapter(Context context, int onlyUsersType, boolean showPhoneBook, LongSparseArray usersToIgnore, int flags, boolean gps) { mContext = context; onlyUsers = onlyUsersType; needPhonebook = showPhoneBook; @@ -82,7 +82,7 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter { if (sortType == 2) { if (onlineContacts == null || force) { onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts); - int selfId = UserConfig.getInstance(currentAccount).clientUserId; + long selfId = UserConfig.getInstance(currentAccount).clientUserId; for (int a = 0, N = onlineContacts.size(); a < N; a++) { if (onlineContacts.get(a).user_id == selfId) { onlineContacts.remove(a); @@ -149,7 +149,7 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter { } } - public void setCheckedMap(SparseArray map) { + public void setCheckedMap(LongSparseArray map) { checkedMap = map; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsAdapter.java index ef4eaff3c..e3d54ae59 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsAdapter.java @@ -184,9 +184,9 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter { onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts); prevContactsCount = onlineContacts.size(); prevDialogsCount = messagesController.dialogs_dict.size(); - int selfId = UserConfig.getInstance(currentAccount).clientUserId; + long selfId = UserConfig.getInstance(currentAccount).clientUserId; for (int a = 0, N = onlineContacts.size(); a < N; a++) { - int userId = onlineContacts.get(a).user_id; + long userId = onlineContacts.get(a).user_id; if (userId == selfId || messagesController.dialogs_dict.get(userId) != null) { onlineContacts.remove(a); a--; @@ -354,7 +354,7 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter { View view; switch (viewType) { case 0: - DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount); + DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount, null); dialogCell.setArchivedPullAnimation(pullForegroundDrawable); dialogCell.setPreloader(preloader); view = dialogCell; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java index 1d2b79c6f..7c43164fd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java @@ -12,8 +12,6 @@ import android.content.Context; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; -import android.util.LongSparseArray; -import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; @@ -24,12 +22,12 @@ import org.telegram.SQLite.SQLitePreparedStatement; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; -import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; @@ -55,6 +53,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -84,7 +83,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { private int dialogsType; private SearchAdapterHelper searchAdapterHelper; private RecyclerListView innerListView; - private int selfUserId; + private long selfUserId; private int currentAccount = UserConfig.selectedAccount; @@ -93,8 +92,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { private ArrayList localTipDates = new ArrayList<>(); private boolean localTipArchive; private FilteredSearchView.Delegate filtersDelegate; - private int folderId; private int currentItemCount; + private int folderId; public boolean isSearching() { return waitingResponseCount > 0; @@ -115,7 +114,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { public interface DialogsSearchAdapterDelegate { void searchStateChanged(boolean searching, boolean animated); void didPressedOnSubDialog(long did); - void needRemoveHint(int did); + void needRemoveHint(long did); void needClearList(); void runResultsEnterAnimation(); boolean isSelected(long dialogId); @@ -157,7 +156,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { TLRPC.Dialog dialog = new TLRPC.TL_dialog(); TLRPC.Chat chat = null; TLRPC.User user = null; - int did = 0; + long did = 0; if (peer.peer.user_id != 0) { did = peer.peer.user_id; user = MessagesController.getInstance(currentAccount).getUser(peer.peer.user_id); @@ -184,8 +183,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { } } - public DialogsSearchAdapter(Context context, int messagesSearch, int type, int folderId) { - this.folderId = folderId; + public DialogsSearchAdapter(Context context, int messagesSearch, int type) { searchAdapterHelper = new SearchAdapterHelper(false); searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() { @Override @@ -282,14 +280,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1); req.offset_id = lastMessage.getId(); req.offset_rate = nextSearchRate; - int id; - if (lastMessage.messageOwner.peer_id.channel_id != 0) { - id = -lastMessage.messageOwner.peer_id.channel_id; - } else if (lastMessage.messageOwner.peer_id.chat_id != 0) { - id = -lastMessage.messageOwner.peer_id.chat_id; - } else { - id = lastMessage.messageOwner.peer_id.user_id; - } + long id = MessageObject.getPeerId(lastMessage.messageOwner.peer_id); req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id); } else { req.offset_rate = 0; @@ -302,8 +293,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { final ArrayList messageObjects = new ArrayList<>(); if (error == null) { TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; - SparseArray chatsMap = new SparseArray<>(); - SparseArray usersMap = new SparseArray<>(); + LongSparseArray chatsMap = new LongSparseArray<>(); + LongSparseArray usersMap = new LongSparseArray<>(); for (int a = 0; a < res.chats.size(); a++) { TLRPC.Chat chat = res.chats.get(a); chatsMap.put(chat.id, chat); @@ -335,8 +326,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { for (int a = 0; a < res.messages.size(); a++) { TLRPC.Message message = res.messages.get(a); long did = MessageObject.getDialogId(message); - Integer maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did); - if (maxId != null && message.id <= maxId) { + int maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did); + if (maxId != 0 && message.id <= maxId) { continue; } searchResultMessages.add(messageObjects.get(a)); @@ -391,8 +382,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { try { SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1"); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedToLoad = new ArrayList<>(); ArrayList encUsers = new ArrayList<>(); @@ -402,23 +393,22 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { long did = cursor.longValue(0); boolean add = false; - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - if (dialogsType != 2 && !usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - add = true; - } - } else { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); + if (DialogObject.isEncryptedDialog(did)) { + if (dialogsType == 0 || dialogsType == 3) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + if (!encryptedToLoad.contains(encryptedChatId)) { + encryptedToLoad.add(encryptedChatId); add = true; } } - } else if (dialogsType == 0 || dialogsType == 3) { - if (!encryptedToLoad.contains(high_id)) { - encryptedToLoad.add(high_id); + } else if (DialogObject.isUserDialog(did)) { + if (dialogsType != 2 && !usersToLoad.contains(did)) { + usersToLoad.add(did); + add = true; + } + } else { + if (!chatsToLoad.contains(-did)) { + chatsToLoad.add(-did); add = true; } } @@ -439,7 +429,10 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { ArrayList encryptedChats = new ArrayList<>(); MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad); for (int a = 0; a < encryptedChats.size(); a++) { - hashMap.get((long) encryptedChats.get(a).id << 32).object = encryptedChats.get(a); + RecentSearchObject recentSearchObject = hashMap.get(DialogObject.makeEncryptedDialogId(encryptedChats.get(a).id)); + if (recentSearchObject != null) { + recentSearchObject.object = encryptedChats.get(a); + } } } @@ -456,7 +449,10 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { arrayList.remove(recentSearchObject); } } else { - hashMap.get(did).object = chat; + RecentSearchObject recentSearchObject = hashMap.get(did); + if (recentSearchObject != null) { + recentSearchObject.object = chat; + } } } } @@ -611,7 +607,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { searchWas = true; for (int a = 0; a < result.size(); a++) { Object obj = result.get(a); - int dialogId = 0; + long dialogId = 0; if (obj instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) obj; MessagesController.getInstance(currentAccount).putUser(user, true); @@ -628,7 +624,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { if (dialogId != 0) { TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId); if (dialog == null) { - int finalDialogId = dialogId; + long finalDialogId = dialogId; MessagesStorage.getInstance(currentAccount).getDialogFolderId(dialogId, param -> { if (param != -1) { TLRPC.Dialog newDialog = new TLRPC.TL_dialog(); @@ -908,7 +904,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new ProfileSearchCell(mContext); @@ -953,12 +949,12 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { horizontalListView.setAdapter(new CategoryAdapterRecycler(mContext, currentAccount, false)); horizontalListView.setOnItemClickListener((view1, position) -> { if (delegate != null) { - delegate.didPressedOnSubDialog((Integer) view1.getTag()); + delegate.didPressedOnSubDialog((Long) view1.getTag()); } }); horizontalListView.setOnItemLongClickListener((view12, position) -> { if (delegate != null) { - delegate.needRemoveHint((Integer) view12.getTag()); + delegate.needRemoveHint((Long) view12.getTag()); } return true; }); @@ -966,6 +962,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter { innerListView = horizontalListView; break; case 6: + default: view = new TextCell(mContext, 16, false); break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java index f526912ca..a2792ac4e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java @@ -75,8 +75,8 @@ public class FiltersView extends RecyclerListView { private ArrayList oldItems = new ArrayList<>(); LinearLayoutManager layoutManager; - public FiltersView(Context context) { - super(context); + public FiltersView(Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); layoutManager = new LinearLayoutManager(context) { @Override public boolean supportsPredictiveItemAnimations() { @@ -199,7 +199,7 @@ public class FiltersView extends RecyclerListView { setWillNotDraw(false); setHideIfEmpty(false); setSelectorRadius(AndroidUtilities.dp(28)); - setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector)); + setSelectorDrawableColor(getThemedColor(Theme.key_listSelector)); } @@ -619,7 +619,7 @@ public class FiltersView extends RecyclerListView { ((FilterView) view).updateColors(); } } - setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector)); + setSelectorDrawableColor(getThemedColor(Theme.key_listSelector)); } private class Adapter extends RecyclerListView.SelectionAdapter { @@ -627,7 +627,7 @@ public class FiltersView extends RecyclerListView { @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - ViewHolder holder = new ViewHolder(new FilterView(parent.getContext())); + ViewHolder holder = new ViewHolder(new FilterView(parent.getContext(), resourcesProvider)); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, AndroidUtilities.dp(32)); lp.topMargin = AndroidUtilities.dp(6); holder.itemView.setLayoutParams(lp); @@ -692,13 +692,16 @@ public class FiltersView extends RecyclerListView { public static class FilterView extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; + BackupImageView avatarImageView; TextView titleView; CombinedDrawable thumbDrawable; MediaFilterData data; - public FilterView(Context context) { + public FilterView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; avatarImageView = new BackupImageView(context); addView(avatarImageView, LayoutHelper.createFrame(32, 32)); @@ -709,15 +712,15 @@ public class FiltersView extends RecyclerListView { } private void updateColors() { - setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(28), Theme.getColor(Theme.key_groupcreate_spanBackground))); - titleView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(28), getThemedColor(Theme.key_groupcreate_spanBackground))); + titleView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); if (thumbDrawable != null) { if (data.filterType == FILTER_TYPE_ARCHIVE) { - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); } else { - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); } } } @@ -728,23 +731,23 @@ public class FiltersView extends RecyclerListView { if (data.filterType == FILTER_TYPE_ARCHIVE) { thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive); thumbDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); avatarImageView.setImageDrawable(thumbDrawable); titleView.setText(data.title); return; } thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); - Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false); + Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); if (data.filterType == FILTER_TYPE_CHAT) { if (data.chat instanceof TLRPC.User) { TLRPC.User user = (TLRPC.User) data.chat; if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) { CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundSaved), false); - Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundSaved), false); + Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true); avatarImageView.setImageDrawable(combinedDrawable); } else { avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16)); @@ -760,6 +763,11 @@ public class FiltersView extends RecyclerListView { } titleView.setText(data.title); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } private class ViewHolder extends RecyclerListView.ViewHolder { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java index 8755fadc9..3315a9510 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java @@ -63,13 +63,15 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca private boolean needEmptyView; private Runnable updateRunnable; + private final Theme.ResourcesProvider resourcesProvider; - public LocationActivityAdapter(Context context, int type, long did, boolean emptyView) { + public LocationActivityAdapter(Context context, int type, long did, boolean emptyView, Theme.ResourcesProvider resourcesProvider) { super(); mContext = context; locationType = type; dialogId = did; needEmptyView = emptyView; + this.resourcesProvider = resourcesProvider; } public void setOverScrollHeight(int value) { @@ -119,7 +121,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca public void setLiveLocations(ArrayList liveLocations) { currentLiveLocations = new ArrayList<>(liveLocations); - int uid = UserConfig.getInstance(currentAccount).getClientUserId(); + long uid = UserConfig.getInstance(currentAccount).getClientUserId(); for (int a = 0; a < currentLiveLocations.size(); a++) { if (currentLiveLocations.get(a).id == uid || currentLiveLocations.get(a).object.out) { currentLiveLocations.remove(a); @@ -261,31 +263,31 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca }; break; case 1: - view = new SendLocationCell(mContext, false); + view = new SendLocationCell(mContext, false, resourcesProvider); break; case 2: - view = new HeaderCell(mContext); + view = new HeaderCell(mContext, resourcesProvider); break; case 3: - view = new LocationCell(mContext, false); + view = new LocationCell(mContext, false, resourcesProvider); break; case 4: - view = new LocationLoadingCell(mContext); + view = new LocationLoadingCell(mContext, resourcesProvider); break; case 5: - view = new LocationPoweredCell(mContext); + view = new LocationPoweredCell(mContext, resourcesProvider); break; case 6: { - SendLocationCell cell = new SendLocationCell(mContext, true); + SendLocationCell cell = new SendLocationCell(mContext, true, resourcesProvider); cell.setDialogId(dialogId); view = cell; break; } case 7: - view = new SharingLiveLocationCell(mContext, true, locationType == LocationActivity.LOCATION_TYPE_GROUP || locationType == LocationActivity.LOCATION_TYPE_GROUP_VIEW ? 16 : 54); + view = new SharingLiveLocationCell(mContext, true, locationType == LocationActivity.LOCATION_TYPE_GROUP || locationType == LocationActivity.LOCATION_TYPE_GROUP_VIEW ? 16 : 54, resourcesProvider); break; case 8: { - LocationDirectionCell cell = new LocationDirectionCell(mContext); + LocationDirectionCell cell = new LocationDirectionCell(mContext, resourcesProvider); cell.setOnButtonClick(v -> onDirectionClick()); view = cell; break; @@ -293,7 +295,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca case 9: { view = new ShadowSectionCell(mContext); Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); view.setBackgroundDrawable(combinedDrawable); break; @@ -478,4 +480,9 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca } return viewType == 1 || viewType == 3 || viewType == 7; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivitySearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivitySearchAdapter.java index 3190e19ad..5aa49317f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivitySearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivitySearchAdapter.java @@ -33,7 +33,7 @@ public class LocationActivitySearchAdapter extends BaseLocationAdapter { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - return new RecyclerListView.Holder(new LocationCell(mContext, false)); + return new RecyclerListView.Holder(new LocationCell(mContext, false, null)); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MentionsAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MentionsAdapter.java index a5595a586..e2200fc84 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MentionsAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MentionsAdapter.java @@ -15,7 +15,6 @@ import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.text.TextUtils; -import android.util.SparseArray; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; @@ -24,6 +23,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageLocation; @@ -49,6 +49,7 @@ import org.telegram.ui.Cells.ContextLinkCell; import org.telegram.ui.Cells.MentionCell; import org.telegram.ui.Cells.StickerCell; import org.telegram.ui.ChatActivity; +import org.telegram.ui.Components.EmojiView; import org.telegram.ui.Components.RecyclerListView; import java.io.File; @@ -58,6 +59,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.RecyclerView; public class MentionsAdapter extends RecyclerListView.SelectionAdapter implements NotificationCenter.NotificationCenterDelegate { @@ -71,10 +73,11 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement private int currentAccount = UserConfig.selectedAccount; private Context mContext; private long dialog_id; + private int threadMessageId; private TLRPC.ChatFull info; private SearchAdapterHelper searchAdapterHelper; private ArrayList searchResultUsernames; - private SparseArray searchResultUsernamesMap; + private LongSparseArray searchResultUsernamesMap; private Runnable searchGlobalRunnable; private ArrayList searchResultHashtags; private ArrayList searchResultCommands; @@ -85,7 +88,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement private ArrayList searchResultBotContext; private TLRPC.TL_inlineBotSwitchPM searchResultBotContextSwitch; private MentionsAdapterDelegate delegate; - private SparseArray botInfo; + private LongSparseArray botInfo; private int resultStartPosition; private int resultLength; private String lastText; @@ -102,6 +105,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement private int channelReqId; private boolean isSearchingMentions; + private EmojiView.ChooseStickerActionTracker mentionsStickersActionTracker; + private boolean visibleByStickersSearch; private final static String punctuationsChars = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n"; @@ -127,6 +132,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement private boolean delayLocalResults; private ChatActivity parentFragment; + private final Theme.ResourcesProvider resourcesProvider; private static class StickerResult { public TLRPC.Document sticker; @@ -159,11 +165,13 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement } }; - public MentionsAdapter(Context context, boolean darkTheme, long did, MentionsAdapterDelegate mentionsAdapterDelegate) { + public MentionsAdapter(Context context, boolean darkTheme, long did, int threadMessageId, MentionsAdapterDelegate mentionsAdapterDelegate, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; mContext = context; delegate = mentionsAdapterDelegate; isDarkTheme = darkTheme; dialog_id = did; + this.threadMessageId = threadMessageId; searchAdapterHelper = new SearchAdapterHelper(true); searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() { @Override @@ -211,6 +219,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement } stickers.add(new StickerResult(document, parent)); stickersMap.put(key, document); + if (mentionsStickersActionTracker != null) { + mentionsStickersActionTracker.checkVisibility(); + } } private void addStickersToResult(ArrayList documents, Object parent) { @@ -306,6 +317,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement ConnectionsManager.getInstance(currentAccount).cancelRequest(lastReqId, true); lastReqId = 0; } + if (mentionsStickersActionTracker != null) { + mentionsStickersActionTracker.checkVisibility(); + } } public void onDestroy() { @@ -367,7 +381,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement needBotContext = value; } - public void setBotInfo(SparseArray info) { + public void setBotInfo(LongSparseArray info) { botInfo = info; } @@ -388,7 +402,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement return searchResultBotContextSwitch; } - public int getContextBotId() { + public long getContextBotId() { return foundContextBot != null ? foundContextBot.id : 0; } @@ -623,7 +637,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement if (user.bot_inline_geo && lastKnownLocation == null) { return; } - final String key = dialog_id + "_" + query + "_" + offset + "_" + dialog_id + "_" + user.id + "_" + (user.bot_inline_geo && lastKnownLocation != null && lastKnownLocation.getLatitude() != -1000 ? lastKnownLocation.getLatitude() + lastKnownLocation.getLongitude() : ""); + final String key = dialog_id + "_" + query + "_" + offset + "_" + dialog_id + "_" + user.id + "_" + (user.bot_inline_geo && lastKnownLocation.getLatitude() != -1000 ? lastKnownLocation.getLatitude() + lastKnownLocation.getLongitude() : ""); final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (!query.equals(searchingContextQuery)) { @@ -699,12 +713,10 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement req.geo_point.lat = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLatitude()); req.geo_point._long = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLongitude()); } - int lower_id = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); - if (lower_id != 0) { - req.peer = MessagesController.getInstance(currentAccount).getInputPeer(lower_id); - } else { + if (DialogObject.isEncryptedDialog(dialog_id)) { req.peer = new TLRPC.TL_inputPeerEmpty(); + } else { + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialog_id); } contextQueryReqid = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors); } @@ -966,9 +978,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement return; } if (foundType == 0) { - final ArrayList users = new ArrayList<>(); + final ArrayList users = new ArrayList<>(); for (int a = 0; a < Math.min(100, messageObjects.size()); a++) { - int from_id = messageObjects.get(a).getFromChatId(); + long from_id = messageObjects.get(a).getFromChatId(); if (from_id > 0 && !users.contains(from_id)) { users.add(from_id); } @@ -976,8 +988,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement final String usernameString = result.toString().toLowerCase(); boolean hasSpace = usernameString.indexOf(' ') >= 0; ArrayList newResult = new ArrayList<>(); - final SparseArray newResultsHashMap = new SparseArray<>(); - final SparseArray newMap = new SparseArray<>(); + final LongSparseArray newResultsHashMap = new LongSparseArray<>(); + final LongSparseArray newMap = new LongSparseArray<>(); ArrayList inlineBots = MediaDataController.getInstance(currentAccount).inlineBots; if (!usernameOnly && needBotContext && dogPostion == 0 && !inlineBots.isEmpty()) { int count = 0; @@ -1015,11 +1027,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement String firstName; String lastName; TLObject object; - int id; + long id; if (a == -1) { - if (chat == null) { - continue; - } if (usernameString.length() == 0) { newResult.add(chat); continue; @@ -1058,7 +1067,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement } Collections.sort(newResult, new Comparator() { - private int getId(TLObject object) { + private long getId(TLObject object) { if (object instanceof TLRPC.User) { return ((TLRPC.User) object).id; } else { @@ -1068,8 +1077,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement @Override public int compare(TLObject lhs, TLObject rhs) { - int id1 = getId(lhs); - int id2 = getId(rhs); + long id1 = getId(lhs); + long id2 = getId(rhs); if (newMap.indexOfKey(id1) >= 0 && newMap.indexOfKey(id2) >= 0) { return 0; } else if (newMap.indexOfKey(id1) >= 0) { @@ -1133,10 +1142,10 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement messagesController.putChats(res.chats, false); boolean hasResults = !searchResultUsernames.isEmpty(); if (!res.participants.isEmpty()) { - int currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); for (int a = 0; a < res.participants.size(); a++) { TLRPC.ChannelParticipant participant = res.participants.get(a); - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); if (searchResultUsernamesMap.indexOfKey(peerId) >= 0 || !isSearchingMentions && peerId == currentUserId) { continue; } @@ -1241,7 +1250,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement } } - private void showUsersResult(ArrayList newResult, SparseArray newMap, boolean notify) { + private void showUsersResult(ArrayList newResult, LongSparseArray newMap, boolean notify) { searchResultUsernames = newResult; searchResultUsernamesMap = newMap; if (cancelDelayRunnable != null) { @@ -1412,7 +1421,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement TextView textView = new TextView(mContext); textView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); + textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText2)); view = textView; break; case 4: @@ -1484,4 +1493,24 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement } } } + + public void doSomeStickersAction() { + if (isStickers()) { + if (mentionsStickersActionTracker == null) { + mentionsStickersActionTracker = new EmojiView.ChooseStickerActionTracker(currentAccount, dialog_id, threadMessageId) { + @Override + public boolean isShown() { + return isStickers(); + } + }; + mentionsStickersActionTracker.checkVisibility(); + } + mentionsStickersActionTracker.doSomeAction(); + } + } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MessagesSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MessagesSearchAdapter.java index 6ec6b1a3c..2e9018add 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MessagesSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/MessagesSearchAdapter.java @@ -15,6 +15,7 @@ import android.view.ViewGroup; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.UserConfig; +import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.DialogCell; import org.telegram.ui.Cells.LoadingCell; import org.telegram.ui.Components.RecyclerListView; @@ -29,8 +30,10 @@ public class MessagesSearchAdapter extends RecyclerListView.SelectionAdapter { private ArrayList searchResultMessages = new ArrayList<>(); private int currentAccount = UserConfig.selectedAccount; + private final Theme.ResourcesProvider resourcesProvider; - public MessagesSearchAdapter(Context context) { + public MessagesSearchAdapter(Context context, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; mContext = context; } @@ -67,7 +70,7 @@ public class MessagesSearchAdapter extends RecyclerListView.SelectionAdapter { View view = null; switch (viewType) { case 0: - view = new DialogCell(null, mContext, false, true); + view = new DialogCell(null, mContext, false, true, currentAccount, resourcesProvider); break; case 1: view = new LoadingCell(mContext); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java index 1193ab185..8fda5b0ab 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapter.java @@ -12,7 +12,6 @@ import android.content.Context; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; -import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; @@ -40,16 +39,17 @@ import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.RecyclerView; public class SearchAdapter extends RecyclerListView.SelectionAdapter { private Context mContext; - private SparseArray ignoreUsers; + private LongSparseArray ignoreUsers; private ArrayList searchResult = new ArrayList<>(); private ArrayList searchResultNames = new ArrayList<>(); private SearchAdapterHelper searchAdapterHelper; - private SparseArray checkedMap; + private LongSparseArray checkedMap; private Timer searchTimer; private boolean allowUsernameSearch; private boolean useUserCell; @@ -58,13 +58,13 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter { private boolean allowBots; private boolean allowSelf; private boolean allowPhoneNumbers; - private int channelId; + private long channelId; private boolean searchInProgress; private int searchReqId; private int searchPointer; - public SearchAdapter(Context context, SparseArray arg1, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) { + public SearchAdapter(Context context, LongSparseArray arg1, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) { mContext = context; ignoreUsers = arg1; onlyMutual = mutual; @@ -85,13 +85,13 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter { } @Override - public SparseArray getExcludeUsers() { + public LongSparseArray getExcludeUsers() { return ignoreUsers; } }); } - public void setCheckedMap(SparseArray map) { + public void setCheckedMap(LongSparseArray map) { checkedMap = map; } @@ -312,7 +312,7 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter { case 0: { TLObject object = (TLObject) getItem(position); if (object != null) { - int id = 0; + long id = 0; String un = null; boolean self = false; if (object instanceof TLRPC.User) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapterHelper.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapterHelper.java index 58ae29ac2..db764e9dd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapterHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/SearchAdapterHelper.java @@ -8,8 +8,6 @@ package org.telegram.ui.Adapters; -import android.util.SparseArray; - import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLitePreparedStatement; @@ -33,6 +31,8 @@ import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; +import androidx.collection.LongSparseArray; + public class SearchAdapterHelper { public static class HashtagObject { @@ -47,11 +47,11 @@ public class SearchAdapterHelper { } - default SparseArray getExcludeUsers() { + default LongSparseArray getExcludeUsers() { return null; } - default SparseArray getExcludeCallParticipants() { + default LongSparseArray getExcludeCallParticipants() { return null; } @@ -67,10 +67,10 @@ public class SearchAdapterHelper { private String lastFoundUsername = null; private ArrayList localServerSearch = new ArrayList<>(); private ArrayList globalSearch = new ArrayList<>(); - private SparseArray globalSearchMap = new SparseArray<>(); + private LongSparseArray globalSearchMap = new LongSparseArray<>(); private ArrayList groupSearch = new ArrayList<>(); - private SparseArray groupSearchMap = new SparseArray<>(); - private SparseArray phoneSearchMap = new SparseArray<>(); + private LongSparseArray groupSearchMap = new LongSparseArray<>(); + private LongSparseArray phoneSearchMap = new LongSparseArray<>(); private ArrayList phonesSearch = new ArrayList<>(); private ArrayList localSearchResults; @@ -105,7 +105,7 @@ public class SearchAdapterHelper { return reqId != 0 || channelReqId != 0; } - public void queryServerSearch(String query, boolean allowUsername, boolean allowChats, boolean allowBots, boolean allowSelf, boolean canAddGroupsOnly, int channelId, boolean phoneNumbers, int type, int searchId) { + public void queryServerSearch(String query, boolean allowUsername, boolean allowChats, boolean allowBots, boolean allowSelf, boolean canAddGroupsOnly, long channelId, boolean phoneNumbers, int type, int searchId) { if (reqId != 0) { ConnectionsManager.getInstance(currentAccount).cancelRequest(reqId, true); reqId = 0; @@ -155,10 +155,10 @@ public class SearchAdapterHelper { groupSearch.clear(); groupSearchMap.clear(); groupSearch.addAll(res.participants); - int currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); for (int a = 0, N = res.participants.size(); a < N; a++) { TLRPC.ChannelParticipant participant = res.participants.get(a); - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); if (!allowSelf && peerId == currentUserId) { groupSearch.remove(participant); continue; @@ -201,8 +201,8 @@ public class SearchAdapterHelper { MessagesController.getInstance(currentAccount).putChats(res.chats, false); MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, true, true); - SparseArray chatsMap = new SparseArray<>(); - SparseArray usersMap = new SparseArray<>(); + LongSparseArray chatsMap = new LongSparseArray<>(); + LongSparseArray usersMap = new LongSparseArray<>(); for (int a = 0; a < res.chats.size(); a++) { TLRPC.Chat chat = res.chats.get(a); chatsMap.put(chat.id, chat); @@ -325,7 +325,7 @@ public class SearchAdapterHelper { return; } for (int a = 0, N = groupSearchMap.size(); a < N; a++) { - int uid = groupSearchMap.keyAt(a); + long uid = groupSearchMap.keyAt(a); TLRPC.User u = (TLRPC.User) globalSearchMap.get(uid); if (u != null) { globalSearch.remove(u); @@ -439,7 +439,7 @@ public class SearchAdapterHelper { if (delegate == null) { return; } - SparseArray ignoreUsers = delegate.getExcludeUsers(); + LongSparseArray ignoreUsers = delegate.getExcludeUsers(); if (ignoreUsers != null) { for (int a = 0, size = ignoreUsers.size(); a < size; a++) { TLRPC.User u = (TLRPC.User) globalSearchMap.get(ignoreUsers.keyAt(a)); @@ -450,7 +450,7 @@ public class SearchAdapterHelper { } } } - SparseArray ignoreParticipants = delegate.getExcludeCallParticipants(); + LongSparseArray ignoreParticipants = delegate.getExcludeCallParticipants(); if (ignoreParticipants != null) { for (int a = 0, size = ignoreParticipants.size(); a < size; a++) { TLRPC.User u = (TLRPC.User) globalSearchMap.get(ignoreParticipants.keyAt(a)); @@ -534,7 +534,7 @@ public class SearchAdapterHelper { }); } - public void removeUserId(int userId) { + public void removeUserId(long userId) { Object object = globalSearchMap.get(userId); if (object != null) { globalSearch.remove(object); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersAdapter.java index dede2f497..a00962659 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersAdapter.java @@ -20,6 +20,7 @@ import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.UserConfig; import org.telegram.messenger.FileLoader; import org.telegram.tgnet.TLRPC; +import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.EmojiReplacementCell; import org.telegram.ui.Components.RecyclerListView; @@ -42,14 +43,16 @@ public class StickersAdapter extends RecyclerListView.SelectionAdapter implement private String[] lastSearchKeyboardLanguage; private Runnable searchRunnable; + private final Theme.ResourcesProvider resourcesProvider; public interface StickersAdapterDelegate { void needChangePanelVisibility(boolean show); } - public StickersAdapter(Context context, StickersAdapterDelegate delegate) { + public StickersAdapter(Context context, StickersAdapterDelegate delegate, Theme.ResourcesProvider resourcesProvider) { mContext = context; this.delegate = delegate; + this.resourcesProvider = resourcesProvider; MediaDataController.getInstance(currentAccount).checkStickers(MediaDataController.TYPE_IMAGE); MediaDataController.getInstance(currentAccount).checkStickers(MediaDataController.TYPE_MASK); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.newEmojiSuggestionsAvailable); @@ -189,7 +192,7 @@ public class StickersAdapter extends RecyclerListView.SelectionAdapter implement @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { - return new RecyclerListView.Holder(new EmojiReplacementCell(mContext)); + return new RecyclerListView.Holder(new EmojiReplacementCell(mContext, resourcesProvider)); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersSearchAdapter.java index 120c5d91a..b920fc6b1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/StickersSearchAdapter.java @@ -265,13 +265,15 @@ public class StickersSearchAdapter extends RecyclerListView.SelectionAdapter { notifyDataSetChanged(); } }; + private final Theme.ResourcesProvider resourcesProvider; - public StickersSearchAdapter(Context context, Delegate delegate, TLRPC.StickerSetCovered[] primaryInstallingStickerSets, LongSparseArray installingStickerSets, LongSparseArray removingStickerSets) { + public StickersSearchAdapter(Context context, Delegate delegate, TLRPC.StickerSetCovered[] primaryInstallingStickerSets, LongSparseArray installingStickerSets, LongSparseArray removingStickerSets, Theme.ResourcesProvider resourcesProvider) { this.context = context; this.delegate = delegate; this.primaryInstallingStickerSets = primaryInstallingStickerSets; this.installingStickerSets = installingStickerSets; this.removingStickerSets = removingStickerSets; + this.resourcesProvider = resourcesProvider; } @Override @@ -348,10 +350,10 @@ public class StickersSearchAdapter extends RecyclerListView.SelectionAdapter { view = new EmptyCell(context); break; case 2: - view = new StickerSetNameCell(context, false, true); + view = new StickerSetNameCell(context, false, true, resourcesProvider); break; case 3: - view = new FeaturedStickerSetInfoCell(context, 17, true); + view = new FeaturedStickerSetInfoCell(context, 17, true, true, resourcesProvider); ((FeaturedStickerSetInfoCell) view).setAddOnClickListener(v -> { final FeaturedStickerSetInfoCell cell = (FeaturedStickerSetInfoCell) v.getParent(); TLRPC.StickerSetCovered pack = cell.getStickerSet(); @@ -377,7 +379,7 @@ public class StickersSearchAdapter extends RecyclerListView.SelectionAdapter { emptyImageView = new ImageView(context); emptyImageView.setScaleType(ImageView.ScaleType.CENTER); emptyImageView.setImageResource(R.drawable.stickers_empty); - emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); + emptyImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); layout.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); layout.addView(new Space(context), LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 15)); @@ -385,7 +387,7 @@ public class StickersSearchAdapter extends RecyclerListView.SelectionAdapter { emptyTextView = new TextView(context); emptyTextView.setText(LocaleController.getString("NoStickersFound", R.string.NoStickersFound)); emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - emptyTextView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText)); + emptyTextView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelEmptyText)); layout.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); view = layout; @@ -672,4 +674,9 @@ public class StickersSearchAdapter extends RecyclerListView.SelectionAdapter { descriptions.add(new ThemeDescription(emptyImageView, ThemeDescription.FLAG_IMAGECOLOR, null, null, null, null, Theme.key_chat_emojiPanelEmptyText)); descriptions.add(new ThemeDescription(emptyTextView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_chat_emojiPanelEmptyText)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ArchivedStickersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ArchivedStickersActivity.java index 1fe761130..6ef15a438 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ArchivedStickersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ArchivedStickersActivity.java @@ -9,7 +9,6 @@ package org.telegram.ui; import android.content.Context; -import android.util.LongSparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; @@ -35,6 +34,7 @@ import org.telegram.ui.Components.StickersAlert; import java.util.ArrayList; import java.util.List; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java index f8b99b10d..3f33b0c55 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java @@ -47,7 +47,6 @@ import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.MetricAffectingSpan; import android.text.style.URLSpan; -import android.util.LongSparseArray; import android.util.Property; import android.util.SparseArray; import android.util.TypedValue; @@ -86,6 +85,7 @@ import android.widget.Toast; import androidx.annotation.Keep; import androidx.annotation.NonNull; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.GridLayoutManagerFixed; @@ -3659,7 +3659,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg @Override public void onTextCopied() { - BulletinFactory.of(containerView).createCopyBulletin(LocaleController.getString("TextCopied", R.string.TextCopied)).show(); + BulletinFactory.of(containerView, null).createCopyBulletin(LocaleController.getString("TextCopied", R.string.TextCopied)).show(); } }); containerView.addView(textSelectionHelper.getOverlayView(activity)); @@ -4024,7 +4024,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg return; } Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); args.putString("botUser", "webpage" + wid); ((LaunchActivity) parentActivity).presentFragment(new ChatActivity(args), false, true); close(false, true); @@ -4671,7 +4671,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg } AndroidUtilities.runOnUIThread(() -> cell.setState(2, false)); AndroidUtilities.runOnUIThread(() -> MessagesController.getInstance(currentAccount).loadFullChat(channel.id, 0, true), 1000); - MessagesStorage.getInstance(currentAccount).updateDialogsWithDeletedMessages(new ArrayList<>(), null, true, channel.id); + MessagesStorage.getInstance(currentAccount).updateDialogsWithDeletedMessages(-channel.id, channel.id, new ArrayList<>(), null, true); }); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewPagerIndicator.java b/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewPagerIndicator.java index 1e9fcfab6..034bef7b7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewPagerIndicator.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewPagerIndicator.java @@ -17,8 +17,6 @@ import android.os.SystemClock; import android.text.TextPaint; import android.view.View; -import com.google.android.exoplayer2.util.Log; - import org.telegram.messenger.AndroidUtilities; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.Components.CubicBezierInterpolator; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewer.java b/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewer.java index 552bdf3ee..a3d403ad9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/AvatarPreviewer.java @@ -250,7 +250,7 @@ public class AvatarPreviewer { @Override protected void onReceiveNotification(Object... args) { - Integer uid = (Integer) args[0]; + Long uid = (Long) args[0]; if (uid == argument.id) { onResult((TLRPC.UserFull) args[1]); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/BubbleActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/BubbleActivity.java index 0cddec48e..9f4e465de 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/BubbleActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/BubbleActivity.java @@ -161,15 +161,15 @@ public class BubbleActivity extends Activity implements ActionBarLayout.ActionBa } BaseFragment chatActivity = null; if (intent.getAction() != null && intent.getAction().startsWith("com.tmessages.openchat")) { - int chatId = intent.getIntExtra("chatId", 0); - int userId = intent.getIntExtra("userId", 0); + long chatId = intent.getLongExtra("chatId", 0); + long userId = intent.getLongExtra("userId", 0); Bundle args = new Bundle(); if (userId != 0) { dialogId = userId; - args.putInt("user_id", userId); + args.putLong("user_id", userId); } else { dialogId = -chatId; - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); } chatActivity = new ChatActivity(args); chatActivity.setInBubbleMode(true); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java index 6bd6fbbb7..a5e315c9b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/CacheControlActivity.java @@ -34,6 +34,7 @@ import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteDatabase; import org.telegram.SQLite.SQLitePreparedStatement; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; @@ -63,6 +64,8 @@ import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SlideChooseView; +import org.telegram.ui.Components.StorageDiagramView; +import org.telegram.ui.Components.StroageUsageView; import org.telegram.ui.Components.UndoView; import java.io.File; @@ -424,9 +427,9 @@ public class CacheControlActivity extends BaseFragment { linearLayout.addView(circleDiagramView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL, 0, 16, 0, 16)); CheckBoxCell lastCreatedCheckbox = null; for (int a = 0; a < 7; a++) { - long size = 0; - String name = null; - String color = null; + long size; + String name; + String color; if (a == 0) { size = photoSize; name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache); @@ -451,7 +454,7 @@ public class CacheControlActivity extends BaseFragment { size = stickersSize; name = LocaleController.getString("AnimatedStickers", R.string.AnimatedStickers); color = Theme.key_statisticChartLine_lightgreen; - } else if (a == 6) { + } else { size = cacheSize; name = LocaleController.getString("LocalCache", R.string.LocalCache); color = Theme.key_statisticChartLine_lightblue; @@ -460,7 +463,7 @@ public class CacheControlActivity extends BaseFragment { clearViewData[a] = new StorageDiagramView.ClearViewData(circleDiagramView); clearViewData[a].size = size; clearViewData[a].color = color; - CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 4, 21); + CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 4, 21, null); lastCreatedCheckbox = checkBoxCell; checkBoxCell.setTag(a); checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); @@ -544,9 +547,7 @@ public class CacheControlActivity extends BaseFragment { StringBuilder ids = new StringBuilder(); while (cursor.next()) { long did = cursor.longValue(0); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0 && high_id != 1) { + if (!DialogObject.isEncryptedDialog(did)) { dialogsToCleanup.add(did); } } @@ -559,7 +560,7 @@ public class CacheControlActivity extends BaseFragment { for (int a = 0; a < dialogsToCleanup.size(); a++) { Long did = dialogsToCleanup.get(a); int messagesCount = 0; - cursor = database.queryFinalized("SELECT COUNT(mid) FROM messages WHERE uid = " + did); + cursor = database.queryFinalized("SELECT COUNT(mid) FROM messages_v2 WHERE uid = " + did); if (cursor.next()) { messagesCount = cursor.intValue(0); } @@ -573,17 +574,17 @@ public class CacheControlActivity extends BaseFragment { if (cursor.next()) { long last_mid_i = cursor.longValue(0); long last_mid = cursor.longValue(1); - SQLiteCursor cursor2 = database.queryFinalized("SELECT data FROM messages WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")"); + SQLiteCursor cursor2 = database.queryFinalized("SELECT data FROM messages_v2 WHERE uid = " + did + " AND mid IN (" + last_mid_i + "," + last_mid + ")"); try { while (cursor2.next()) { NativeByteBuffer data = cursor2.byteBufferValue(0); if (data != null) { TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false); - message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId); - data.reuse(); if (message != null) { messageId = message.id; + message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId); } + data.reuse(); } } } catch (Exception e) { @@ -591,11 +592,11 @@ public class CacheControlActivity extends BaseFragment { } cursor2.dispose(); - database.executeFast("DELETE FROM messages WHERE uid = " + did + " AND mid != " + last_mid_i + " AND mid != " + last_mid).stepThis().dispose(); + database.executeFast("DELETE FROM messages_v2 WHERE uid = " + did + " AND mid != " + last_mid_i + " AND mid != " + last_mid).stepThis().dispose(); database.executeFast("DELETE FROM messages_holes WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM bot_keyboard WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose(); - database.executeFast("DELETE FROM media_v2 WHERE uid = " + did).stepThis().dispose(); + database.executeFast("DELETE FROM media_v3 WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid = " + did).stepThis().dispose(); MediaDataController.getInstance(currentAccount).clearBotKeyboard(did, null); if (messageId != -1) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/CallLogActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/CallLogActivity.java index e7523b0fb..bfb72ae42 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/CallLogActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/CallLogActivity.java @@ -19,7 +19,6 @@ import android.os.Bundle; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; -import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.View; @@ -67,6 +66,7 @@ import org.telegram.ui.Components.voip.VoIPHelper; import java.util.ArrayList; import java.util.Iterator; +import androidx.collection.LongSparseArray; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -92,7 +92,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. private ProgressButton waitingForLoadButton; - private ArrayList activeGroupCalls; + private ArrayList activeGroupCalls; private ArrayList selectedIds = new ArrayList<>(); @@ -109,7 +109,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. private TLRPC.User lastCallUser; private TLRPC.Chat lastCallChat; - private Integer waitingForCallChatId; + private Long waitingForCallChatId; private boolean openTransitionStarted; @@ -211,8 +211,8 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. ArrayList arr = (ArrayList) args[1]; for (MessageObject msg : arr) { if (msg.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall) { - int fromId = msg.getFromChatId(); - int userID = fromId == getUserConfig().getClientUserId() ? msg.messageOwner.peer_id.user_id : fromId; + long fromId = msg.getFromChatId(); + long userID = fromId == getUserConfig().getClientUserId() ? msg.messageOwner.peer_id.user_id : fromId; int callType = fromId == getUserConfig().getClientUserId() ? TYPE_OUT : TYPE_IN; TLRPC.PhoneCallDiscardReason reason = msg.messageOwner.action.reason; if (callType == TYPE_IN && (reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed || reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy)) { @@ -260,8 +260,9 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. msgs.remove(); } } - if (row.calls.size() == 0) + if (row.calls.size() == 0) { itrtr.remove(); + } } if (didChange && listViewAdapter != null) { listViewAdapter.notifyDataSetChanged(); @@ -290,7 +291,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. if (waitingForCallChatId == null) { return; } - Integer chatId = (Integer) args[0]; + Long chatId = (Long) args[0]; if (waitingForCallChatId.equals(chatId)) { if (waitingForLoadButton != null) { waitingForLoadButton.setDrawProgress(false, false); @@ -374,7 +375,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. if (waitingForLoadButton != null) { waitingForLoadButton.setDrawProgress(false, true); } - Integer tag = (Integer) v.getTag(); + Long tag = (Long) v.getTag(); ChatObject.Call call = getMessagesController().getGroupCall(tag, false); lastCallChat = getMessagesController().getChat(tag); if (call != null) { @@ -483,7 +484,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. addOrRemoveSelectedDialog(row.calls, (CallCell) view); } else { Bundle args = new Bundle(); - args.putInt("user_id", row.user.id); + args.putLong("user_id", row.user.id); args.putInt("message_id", row.calls.get(0).id); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); presentFragment(new ChatActivity(args), true); @@ -491,7 +492,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. } else if (view instanceof GroupCallCell) { GroupCallCell cell = (GroupCallCell) view; Bundle args = new Bundle(); - args.putInt("chat_id", cell.currentChat.id); + args.putLong("chat_id", cell.currentChat.id); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); presentFragment(new ChatActivity(args), true); } @@ -626,7 +627,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. otherItem.setVisibility(View.GONE); listViewAdapter.notifyDataSetChanged(); } else { - getMessagesController().deleteMessages(new ArrayList<>(selectedIds), null, null, 0, 0, checks[0], false); + getMessagesController().deleteMessages(new ArrayList<>(selectedIds), null, null, 0, checks[0], false); } hideActionMode(false); }); @@ -777,7 +778,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. int reqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { int oldCount = Math.max(listViewAdapter.callsStartRow, 0) + calls.size(); if (error == null) { - SparseArray users = new SparseArray<>(); + LongSparseArray users = new LongSparseArray<>(); TLRPC.messages_Messages msgs = (TLRPC.messages_Messages) response; endReached = msgs.messages.isEmpty(); for (int a = 0; a < msgs.users.size(); a++) { @@ -795,8 +796,9 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. if (callType == TYPE_IN && (reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed || reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy)) { callType = TYPE_MISSED; } - int fromId = MessageObject.getFromChatId(msg); - int userID = fromId == getUserConfig().getClientUserId() ? msg.peer_id.user_id : fromId; + + long fromId = MessageObject.getFromChatId(msg); + long userID = fromId == getUserConfig().getClientUserId() ? msg.peer_id.user_id : fromId; if (currentRow == null || currentRow.user.id != userID || currentRow.type != callType) { if (currentRow != null && !calls.contains(currentRow)) { calls.add(currentRow); @@ -1080,7 +1082,7 @@ public class CallLogActivity extends BaseFragment implements NotificationCenter. } case 4: { position -= activeStartRow; - Integer chatId = activeGroupCalls.get(position); + Long chatId = activeGroupCalls.get(position); TLRPC.Chat chat = getMessagesController().getChat(chatId); GroupCallCell cell = (GroupCallCell) holder.itemView; cell.setChat(chat); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/AudioPlayerCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/AudioPlayerCell.java index 49d941a0e..fd323a858 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/AudioPlayerCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/AudioPlayerCell.java @@ -68,12 +68,14 @@ public class AudioPlayerCell extends View implements DownloadController.FileDown public final static int VIEW_TYPE_GLOBAL_SEARCH = 1; private SpannableStringBuilder dotSpan; + private final Theme.ResourcesProvider resourcesProvider; - public AudioPlayerCell(Context context, int viewType) { + public AudioPlayerCell(Context context, int viewType, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; this.viewType = viewType; - radialProgress = new RadialProgress2(this); + radialProgress = new RadialProgress2(this, resourcesProvider); radialProgress.setColors(Theme.key_chat_inLoader, Theme.key_chat_inLoaderSelected, Theme.key_chat_inMediaIcon, Theme.key_chat_inMediaIconSelected); TAG = DownloadController.getInstance(currentAccount).generateObserverTag(); setFocusable(true); @@ -270,14 +272,14 @@ public class AudioPlayerCell extends View implements DownloadController.FileDown } if (descriptionLayout != null) { - Theme.chat_contextResult_descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); + Theme.chat_contextResult_descriptionTextPaint.setColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText2)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), descriptionY); descriptionLayout.draw(canvas); canvas.restore(); } - radialProgress.setProgressColor(Theme.getColor(buttonPressed ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + radialProgress.setProgressColor(getThemedColor(buttonPressed ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); radialProgress.draw(canvas); } @@ -330,7 +332,7 @@ public class AudioPlayerCell extends View implements DownloadController.FileDown miniButtonState = -1; } if (hasMiniProgress != 0) { - radialProgress.setMiniProgressBackgroundColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); + radialProgress.setMiniProgressBackgroundColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); boolean playing = MediaController.getInstance().isPlayingMessage(currentMessageObject); if (!playing || playing && MediaController.getInstance().isMessagePaused()) { buttonState = 0; @@ -433,4 +435,9 @@ public class AudioPlayerCell extends View implements DownloadController.FileDown info.setText(titleLayout.getText() + ", " + descriptionLayout.getText()); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/BotHelpCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/BotHelpCell.java index 2a87117f1..8128e5b5c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/BotHelpCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/BotHelpCell.java @@ -48,6 +48,7 @@ public class BotHelpCell extends View { private LinkPath urlPath = new LinkPath(); private BotHelpCellDelegate delegate; + private final Theme.ResourcesProvider resourcesProvider; private boolean animating; @@ -55,8 +56,9 @@ public class BotHelpCell extends View { void didPressUrl(String url); } - public BotHelpCell(Context context) { + public BotHelpCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; } public void setDelegate(BotHelpCellDelegate botHelpCellDelegate) { @@ -214,11 +216,12 @@ public class BotHelpCell extends View { w = view.getMeasuredWidth(); h = view.getMeasuredHeight(); } - Theme.chat_msgInMediaDrawable.setTop((int) getY(), w, h, false, false); - Theme.chat_msgInMediaDrawable.setBounds(x, y, width + x, height + y); - Theme.chat_msgInMediaDrawable.draw(canvas); - Theme.chat_msgTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_msgTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkIn); + Theme.MessageDrawable drawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMedia); + drawable.setTop((int) getY(), w, h, false, false); + drawable.setBounds(x, y, width + x, height + y); + drawable.draw(canvas); + Theme.chat_msgTextPaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); + Theme.chat_msgTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkIn); canvas.save(); canvas.translate(textX = AndroidUtilities.dp(2 + 9) + x, textY = AndroidUtilities.dp(2 + 9) + y); if (pressedLink != null) { @@ -251,4 +254,14 @@ public class BotHelpCell extends View { public void setAnimating(boolean animating) { this.animating = animating; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Drawable getThemedDrawable(String drawableKey) { + Drawable drawable = resourcesProvider != null ? resourcesProvider.getDrawable(drawableKey) : null; + return drawable != null ? drawable : Theme.getThemeDrawable(drawableKey); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/BrightnessControlCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/BrightnessControlCell.java index 85a4743bc..97ada487a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/BrightnessControlCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/BrightnessControlCell.java @@ -37,7 +37,7 @@ public class BrightnessControlCell extends FrameLayout { leftImageView.setImageResource(R.drawable.brightness_low); addView(leftImageView, LayoutHelper.createFrame(24, 24, Gravity.LEFT | Gravity.TOP, 17, 12, 0, 0)); - seekBarView = new SeekBarView(context, /* inPercents = */ true) { + seekBarView = new SeekBarView(context, /* inPercents = */ true, null) { @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java index 2e0f0bfcf..3eeec95ba 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java @@ -12,6 +12,7 @@ import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; +import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; @@ -19,6 +20,7 @@ import android.graphics.RectF; import android.text.Layout; import android.text.Spannable; import android.text.StaticLayout; +import android.text.TextPaint; import android.text.TextUtils; import android.text.style.URLSpan; import android.view.MotionEvent; @@ -26,6 +28,8 @@ import android.view.SoundEffectConstants; import android.view.ViewGroup; import android.view.accessibility.AccessibilityNodeInfo; +import com.google.android.exoplayer2.util.Log; + import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; @@ -57,7 +61,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD default void didLongPress(ChatActionCell cell, float x, float y) { } - default void needOpenUserProfile(int uid) { + default void needOpenUserProfile(long uid) { } default void didPressBotButton(MessageObject messageObject, TLRPC.KeyboardButton button) { @@ -71,6 +75,11 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD } } + public interface ThemeDelegate extends Theme.ResourcesProvider { + + int getCurrentColor(); + } + private int TAG; private URLSpan pressedLink; @@ -105,18 +114,26 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD private String overrideBackground; private String overrideText; - private ColorFilter overrideColorFilter; + private Paint overrideBackgroundPaint; + private TextPaint overrideTextPaint; private int overrideColor; private ArrayList lineWidths = new ArrayList<>(); private ArrayList lineHeights = new ArrayList<>(); private Path backgroundPath = new Path(); private RectF rect = new RectF(); private boolean invalidatePath = true; + private boolean invalidateColors = false; private ChatActionCellDelegate delegate; + private ThemeDelegate themeDelegate; public ChatActionCell(Context context) { + this(context, null); + } + + public ChatActionCell(Context context, ThemeDelegate themeDelegate) { super(context); + this.themeDelegate = themeDelegate; imageReceiver = new ImageReceiver(this); imageReceiver.setRoundRadius(AndroidUtilities.roundMessageSize / 2); avatarDrawable = new AvatarDrawable(); @@ -186,7 +203,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this); previousWidth = 0; if (currentMessageObject.type == 11) { - int id = (int) messageObject.getDialogId(); + long id = messageObject.getDialogId(); avatarDrawable.setInfo(id, null, null); if (currentMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { imageReceiver.setImage(null, null, avatarDrawable, null, currentMessageObject, 0); @@ -240,7 +257,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD visiblePartSet = true; backgroundHeight = parentH; viewTop = visibleTop; - if (Theme.hasGradientService()) { + if (hasGradientService()) { invalidate(); } } @@ -392,7 +409,7 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD private void createLayout(CharSequence text, int width) { int maxWidth = width - AndroidUtilities.dp(30); invalidatePath = true; - textLayout = new StaticLayout(text, Theme.chat_actionTextPaint, maxWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); + textLayout = new StaticLayout(text, (TextPaint) getThemedPaint(Theme.key_paint_chatActionText), maxWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); textHeight = 0; textWidth = 0; try { @@ -472,14 +489,20 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD return; } + Paint backgroundPaint = getThemedPaint(Theme.key_paint_chatActionBackground); + TextPaint textPaint = (TextPaint) getThemedPaint(Theme.key_paint_chatActionText); if (overrideBackground != null) { - int color = Theme.getColor(overrideBackground); - if (color != overrideColor) { - overrideColor = color; - overrideColorFilter = new PorterDuffColorFilter(overrideColor, PorterDuff.Mode.MULTIPLY); + int color = getThemedColor(overrideBackground); + if (overrideBackgroundPaint == null) { + overrideBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + overrideBackgroundPaint.setColor(color); + overrideTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); + overrideTextPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + overrideTextPaint.setTextSize(AndroidUtilities.dp(Math.max(16, SharedConfig.fontSize) - 2)); + overrideTextPaint.setColor(getThemedColor(overrideText)); } - Theme.chat_actionBackgroundPaint.setColor(overrideColor); - Theme.chat_actionTextPaint.setColor(Theme.getColor(overrideText)); + backgroundPaint = overrideBackgroundPaint; + textPaint = overrideTextPaint; } if (invalidatePath) { invalidatePath = false; @@ -613,21 +636,27 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD ViewGroup parent = (ViewGroup) getParent(); backgroundHeight = parent.getMeasuredHeight(); } - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, 0, viewTop + AndroidUtilities.dp(4)); - canvas.drawPath(backgroundPath, Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + if (themeDelegate != null) { + themeDelegate.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, 0, viewTop + AndroidUtilities.dp(4)); + } else { + Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, 0, viewTop + AndroidUtilities.dp(4)); + } + canvas.drawPath(backgroundPath, backgroundPaint); + if (hasGradientService()) { canvas.drawPath(backgroundPath, Theme.chat_actionBackgroundGradientDarkenPaint); } canvas.save(); canvas.translate(textXLeft, textY); + if (textLayout.getPaint() != textPaint) { + buildLayout(); + } textLayout.draw(canvas); canvas.restore(); + } - if (overrideColorFilter != null) { - Theme.chat_actionBackgroundPaint.setColor(Theme.currentColor); - Theme.chat_actionTextPaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); - } + protected boolean hasGradientService() { + return themeDelegate != null ? themeDelegate.hasGradientService() : Theme.hasGradientService(); } @Override @@ -675,4 +704,22 @@ public class ChatActionCell extends BaseCell implements DownloadController.FileD info.setText(!TextUtils.isEmpty(customText) ? customText : currentMessageObject.messageText); info.setEnabled(true); } + + public void setInvalidateColors(boolean invalidate) { + if (invalidateColors == invalidate) { + return; + } + invalidateColors = invalidate; + invalidate(); + } + + private int getThemedColor(String key) { + Integer color = themeDelegate != null ? themeDelegate.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = themeDelegate != null ? themeDelegate.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatLoadingCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatLoadingCell.java index 7658e72cf..b58ab6903 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatLoadingCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatLoadingCell.java @@ -9,6 +9,7 @@ package org.telegram.ui.Cells; import android.content.Context; +import android.graphics.Paint; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; @@ -22,17 +23,19 @@ public class ChatLoadingCell extends FrameLayout { private FrameLayout frameLayout; private RadialProgressView progressBar; + private Theme.ResourcesProvider resourcesProvider; - public ChatLoadingCell(Context context, View parent) { + public ChatLoadingCell(Context context, View parent, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; frameLayout = new FrameLayout(context); - frameLayout.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), frameLayout, parent)); + frameLayout.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), frameLayout, parent, getThemedPaint(Theme.key_paint_chatActionBackground))); addView(frameLayout, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); - progressBar = new RadialProgressView(context); + progressBar = new RadialProgressView(context, resourcesProvider); progressBar.setSize(AndroidUtilities.dp(28)); - progressBar.setProgressColor(Theme.getColor(Theme.key_chat_serviceText)); + progressBar.setProgressColor(getThemedColor(Theme.key_chat_serviceText)); frameLayout.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); } @@ -44,4 +47,14 @@ public class ChatLoadingCell extends FrameLayout { public void setProgressVisible(boolean value) { frameLayout.setVisibility(value ? VISIBLE : INVISIBLE); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java index f7abc9a11..fdf9e0da1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java @@ -68,12 +68,11 @@ import android.widget.Toast; import androidx.core.graphics.ColorUtils; -import com.google.android.exoplayer2.util.Log; - import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.DocumentObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.Emoji; @@ -116,6 +115,7 @@ import org.telegram.ui.Components.LinkPath; import org.telegram.ui.Components.MediaActionDrawable; import org.telegram.ui.Components.MessageBackgroundDrawable; import org.telegram.ui.Components.MotionBackgroundDrawable; +import org.telegram.ui.Components.MsgClockDrawable; import org.telegram.ui.Components.Point; import org.telegram.ui.Components.RLottieDrawable; import org.telegram.ui.Components.RadialProgress2; @@ -222,7 +222,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate default void didPressHint(ChatMessageCell cell, int type) { } - default String getAdminRank(int uid) { + default String getAdminRank(long uid) { return null; } @@ -611,7 +611,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate public boolean hasDiscussion; public boolean isPinned; private boolean wasPinned; - public int linkedChatId; + public long linkedChatId; public boolean isRepliesChat; public boolean isPinnedChat; private boolean isPressed; @@ -828,8 +828,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate VideoForwardDrawable videoForwardDrawable; VideoPlayerRewinder videoPlayerRewinder; + private final Theme.ResourcesProvider resourcesProvider; + public ChatMessageCell(Context context) { + this(context, null); + } + + public ChatMessageCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; backgroundDrawable = new MessageBackgroundDrawable(this); avatarImage = new ImageReceiver(); @@ -844,8 +851,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate contactAvatarDrawable = new AvatarDrawable(); photoImage = new ImageReceiver(this); photoImage.setDelegate(this); - radialProgress = new RadialProgress2(this); - videoRadialProgress = new RadialProgress2(this); + radialProgress = new RadialProgress2(this, resourcesProvider); + videoRadialProgress = new RadialProgress2(this, resourcesProvider); videoRadialProgress.setDrawBackground(false); videoRadialProgress.setCircleRadius(AndroidUtilities.dp(15)); seekBar = new SeekBar(this); @@ -886,7 +893,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate invalidate(); } }; - roundVideoPlayingDrawable = new RoundVideoPlayingDrawable(this); + roundVideoPlayingDrawable = new RoundVideoPlayingDrawable(this, resourcesProvider); } private void createPollUI() { @@ -904,7 +911,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } pollCheckBox = new CheckBoxBase[10]; for (int a = 0; a < pollCheckBox.length; a++) { - pollCheckBox[a] = new CheckBoxBase(this, 20); + pollCheckBox[a] = new CheckBoxBase(this, 20, resourcesProvider); pollCheckBox[a].setDrawUnchecked(false); pollCheckBox[a].setBackgroundType(9); } @@ -2563,7 +2570,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate parentHeight = parentH; backgroundHeight = parentH; - if (currentMessageObject != null && (Theme.hasGradientService() && currentMessageObject.shouldDrawWithoutBackground() || drawSideButton != 0 || !botButtons.isEmpty()) || currentBackgroundDrawable != null && currentBackgroundDrawable.getGradientShader() != null) { + if (currentMessageObject != null && (hasGradientService() && currentMessageObject.shouldDrawWithoutBackground() || drawSideButton != 0 || !botButtons.isEmpty()) || currentBackgroundDrawable != null && currentBackgroundDrawable.getGradientShader() != null) { invalidate(); } } @@ -2577,7 +2584,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate this.parentViewTopOffset = parentOffset; parentHeight = parent; } - if (currentMessageObject != null && (Theme.hasGradientService() && currentMessageObject.shouldDrawWithoutBackground() || drawSideButton != 0 || !botButtons.isEmpty()) || currentBackgroundDrawable != null && currentBackgroundDrawable.getGradientShader() != null) { + if (currentMessageObject != null && (hasGradientService() && currentMessageObject.shouldDrawWithoutBackground() || drawSideButton != 0 || !botButtons.isEmpty()) || currentBackgroundDrawable != null && currentBackgroundDrawable.getGradientShader() != null) { invalidate(); } @@ -2897,7 +2904,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate public int getChecksY() { if (currentMessageObject.shouldDrawWithoutBackground()) { - return (int) (drawTimeY - Theme.chat_msgStickerCheckDrawable.getIntrinsicHeight()); + return (int) (drawTimeY - getThemedDrawable(Theme.key_drawable_msgStickerCheck).getIntrinsicHeight()); } else { return (int) (drawTimeY - Theme.chat_msgMediaCheckDrawable.getIntrinsicHeight()); } @@ -3321,12 +3328,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate for (int a = 0; a < commentAvatarImages.length; a++) { if (a < size) { commentAvatarImages[a].setImageCoords(0, 0, AndroidUtilities.dp(24), AndroidUtilities.dp(24)); - int id = MessageObject.getPeerId(recentRepliers.get(a)); + long id = MessageObject.getPeerId(recentRepliers.get(a)); TLRPC.User user = null; TLRPC.Chat chat = null; - if (id > 0) { + if (DialogObject.isUserDialog(id)) { user = MessagesController.getInstance(currentAccount).getUser(id); - } else if (id < 0) { + } else if (DialogObject.isChatDialog(id)) { chat = MessagesController.getInstance(currentAccount).getChat(-id); } if (user != null) { @@ -3428,7 +3435,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate boolean slideshow = false; String webpageType = hasLinkPreview ? messageObject.messageOwner.media.webpage.type : null; TLRPC.Document androidThemeDocument = null; - TLRPC.TL_themeSettings androidThemeSettings = null; + TLRPC.ThemeSettings androidThemeSettings = null; if (!drawInstantView) { if ("telegram_livestream".equals(webpageType)) { drawInstantView = true; @@ -4405,7 +4412,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } availableTimeWidth = backgroundWidth - AndroidUtilities.dp(31); - int uid = messageObject.messageOwner.media.user_id; + long uid = messageObject.messageOwner.media.user_id; TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid); int maxWidth = getMaxNameWidth() - AndroidUtilities.dp(80); @@ -4610,7 +4617,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate for (int a = 0; a < pollAvatarImages.length; a++) { if (!isBot && a < size) { pollAvatarImages[a].setImageCoords(0, 0, AndroidUtilities.dp(16), AndroidUtilities.dp(16)); - Integer id = media.results.recent_voters.get(a); + Long id = media.results.recent_voters.get(a); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id); if (user != null) { pollAvatarDrawables[a].setInfo(user); @@ -5823,7 +5830,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate drawInstantViewType = 1; long id = MessageObject.getPeerId(messageObject.messageOwner.from_id); if (id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser((int) id); //TODO long + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id); if (user != null && user.bot) { drawInstantViewType = 10; } @@ -5903,13 +5910,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate botButton.width = buttonWidth; botButton.height = AndroidUtilities.dp(44); CharSequence buttonText; + TextPaint botButtonPaint = (TextPaint) getThemedPaint(Theme.key_paint_chatBotButton); if (botButton.button instanceof TLRPC.TL_keyboardButtonBuy && (messageObject.messageOwner.media.flags & 4) != 0) { buttonText = LocaleController.getString("PaymentReceipt", R.string.PaymentReceipt); } else { - buttonText = Emoji.replaceEmoji(botButton.button.text, Theme.chat_botButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false); - buttonText = TextUtils.ellipsize(buttonText, Theme.chat_botButtonPaint, buttonWidth - AndroidUtilities.dp(10), TextUtils.TruncateAt.END); + buttonText = Emoji.replaceEmoji(botButton.button.text, botButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false); + buttonText = TextUtils.ellipsize(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), TextUtils.TruncateAt.END); } - botButton.title = new StaticLayout(buttonText, Theme.chat_botButtonPaint, buttonWidth - AndroidUtilities.dp(10), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); + botButton.title = new StaticLayout(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); botButtons.add(botButton); if (b == row.buttons.size() - 1) { maxButtonsWidth = Math.max(maxButtonsWidth, botButton.x + botButton.width); @@ -5945,10 +5953,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate botButton.width = buttonWidth; botButton.height = AndroidUtilities.dp(44); - CharSequence buttonText = Emoji.replaceEmoji(String.format("%d %s", reaction.count, reaction.reaction), Theme.chat_botButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false); - buttonText = TextUtils.ellipsize(buttonText, Theme.chat_botButtonPaint, buttonWidth - AndroidUtilities.dp(10), TextUtils.TruncateAt.END); + TextPaint botButtonPaint = (TextPaint) getThemedPaint(Theme.key_paint_chatBotButton); + CharSequence buttonText = Emoji.replaceEmoji(String.format("%d %s", reaction.count, reaction.reaction), botButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false); + buttonText = TextUtils.ellipsize(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), TextUtils.TruncateAt.END); - botButton.title = new StaticLayout(buttonText, Theme.chat_botButtonPaint, buttonWidth - AndroidUtilities.dp(10), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); + botButton.title = new StaticLayout(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); botButtons.add(botButton); if (b == buttonsCount - 1) { maxButtonsWidth = Math.max(maxButtonsWidth, botButton.x + botButton.width); @@ -6753,9 +6762,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } int color; if (psaHintPressed) { - color = Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outViews : Theme.key_chat_inViews); + color = getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outViews : Theme.key_chat_inViews); } else { - color = Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText); + color = getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText); } if (selectorDrawable[num] == null) { final Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -6815,7 +6824,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate }; ColorStateList colorStateList = new ColorStateList( new int[][]{StateSet.WILD_CARD}, - new int[]{Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText) & 0x19ffffff} + new int[]{getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText) & 0x19ffffff} ); selectorDrawable[num] = new RippleDrawable(colorStateList, null, maskDrawable); selectorDrawable[num].setCallback(this); @@ -7388,8 +7397,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate lastControlsAlphaChangeTime = System.currentTimeMillis(); totalChangeTime = 0; } - radialProgress.setProgressColor(Theme.getColor(Theme.key_chat_mediaProgress)); - videoRadialProgress.setProgressColor(Theme.getColor(Theme.key_chat_mediaProgress)); + radialProgress.setProgressColor(getThemedColor(Theme.key_chat_mediaProgress)); + videoRadialProgress.setProgressColor(getThemedColor(Theme.key_chat_mediaProgress)); imageDrawn = false; radialProgress.setCircleCrossfadeColor(null, 0.0f, 1.0f); @@ -7465,12 +7474,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate Theme.chat_roundVideoShadow.draw(canvas); if (!photoImage.hasBitmapImage() || photoImage.getCurrentAlpha() != 1) { - Theme.chat_docBackPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outBubble : Theme.key_chat_inBubble)); + Theme.chat_docBackPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outBubble : Theme.key_chat_inBubble)); canvas.drawCircle(photoImage.getCenterX(), photoImage.getCenterY(), photoImage.getImageWidth() / 2, Theme.chat_docBackPaint); } } else if (currentMessageObject.type == 4) { rect.set(photoImage.getImageX(), photoImage.getImageY(), photoImage.getImageX2(), photoImage.getImageY2()); - Theme.chat_docBackPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLocationBackground : Theme.key_chat_inLocationBackground)); + Theme.chat_docBackPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLocationBackground : Theme.key_chat_inLocationBackground)); int[] rad = photoImage.getRoundRadius(); rectPath.reset(); for (int a = 0; a < rad.length; a++) { @@ -7487,7 +7496,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate drawMediaCheckBox = mediaCheckBox != null && (checkBoxVisible || mediaCheckBox.getProgress() != 0 || checkBoxAnimationInProgress) && currentMessagesGroup != null; if (drawMediaCheckBox && (mediaCheckBox.isChecked() || mediaCheckBox.getProgress() != 0 || checkBoxAnimationInProgress) && (!textIsSelectionMode())) { if (!currentMessagesGroup.isDocuments) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outBubbleSelected : Theme.key_chat_inBubbleSelected)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outBubbleSelected : Theme.key_chat_inBubbleSelected)); rect.set(photoImage.getImageX(), photoImage.getImageY(), photoImage.getImageX2(), photoImage.getImageY2()); int[] rad = photoImage.getRoundRadius(); rectPath.reset(); @@ -7586,15 +7595,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { if (currentMessageObject.isOutOwner()) { - Theme.chat_audioTitlePaint.setColor(Theme.getColor(Theme.key_chat_outAudioTitleText)); - Theme.chat_audioPerformerPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioPerformerSelectedText : Theme.key_chat_outAudioPerformerText)); - Theme.chat_audioTimePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioDurationSelectedText : Theme.key_chat_outAudioDurationText)); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); + Theme.chat_audioTitlePaint.setColor(getThemedColor(Theme.key_chat_outAudioTitleText)); + Theme.chat_audioPerformerPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioPerformerSelectedText : Theme.key_chat_outAudioPerformerText)); + Theme.chat_audioTimePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioDurationSelectedText : Theme.key_chat_outAudioDurationText)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); } else { - Theme.chat_audioTitlePaint.setColor(Theme.getColor(Theme.key_chat_inAudioTitleText)); - Theme.chat_audioPerformerPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioPerformerSelectedText : Theme.key_chat_inAudioPerformerText)); - Theme.chat_audioTimePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioDurationSelectedText : Theme.key_chat_inAudioDurationText)); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + Theme.chat_audioTitlePaint.setColor(getThemedColor(Theme.key_chat_inAudioTitleText)); + Theme.chat_audioPerformerPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioPerformerSelectedText : Theme.key_chat_inAudioPerformerText)); + Theme.chat_audioTimePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioDurationSelectedText : Theme.key_chat_inAudioDurationText)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); } radialProgress.setBackgroundDrawable(isDrawSelectionBackground() ? currentBackgroundSelectedDrawable : currentBackgroundDrawable); @@ -7654,7 +7663,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (shouldDrawMenuDrawable()) { Drawable menuDrawable; if (currentMessageObject.isOutOwner()) { - menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgOutMenuSelectedDrawable : Theme.chat_msgOutMenuDrawable; + menuDrawable = getThemedDrawable(isDrawSelectionBackground() ? Theme.key_drawable_msgOutMenuSelected : Theme.key_drawable_msgOutMenu); } else { menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgInMenuSelectedDrawable : Theme.chat_msgInMenuDrawable; } @@ -7669,11 +7678,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { if (currentMessageObject.isOutOwner()) { - Theme.chat_audioTimePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioDurationSelectedText : Theme.key_chat_outAudioDurationText)); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); + Theme.chat_audioTimePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outAudioDurationSelectedText : Theme.key_chat_outAudioDurationText)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); } else { - Theme.chat_audioTimePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioDurationSelectedText : Theme.key_chat_inAudioDurationText)); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + Theme.chat_audioTimePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inAudioDurationSelectedText : Theme.key_chat_inAudioDurationText)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); } AudioVisualizerDrawable audioVisualizerDrawable; if (MediaController.getInstance().isPlayingMessage(currentMessageObject)) { @@ -7715,7 +7724,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.restore(); if (currentMessageObject.type != 0 && currentMessageObject.isContentUnread()) { - Theme.chat_docBackPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarFill : Theme.key_chat_inVoiceSeekbarFill)); + Theme.chat_docBackPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarFill : Theme.key_chat_inVoiceSeekbarFill)); canvas.drawCircle(timeAudioX + timeWidthAudio + AndroidUtilities.dp(6), AndroidUtilities.dp(51) + namesOffset + mediaOffsetY, AndroidUtilities.dp(3), Theme.chat_docBackPaint); } } @@ -7737,11 +7746,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int startY = totalHeight - AndroidUtilities.dp(drawPinnedTop ? 9 : 10) - linkPreviewHeight - AndroidUtilities.dp(8); int linkPreviewY = startY; - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewLine : Theme.key_chat_inPreviewLine)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewLine : Theme.key_chat_inPreviewLine)); canvas.drawRect(linkX, linkPreviewY - AndroidUtilities.dp(3), linkX + AndroidUtilities.dp(2), linkPreviewY + linkPreviewHeight, Theme.chat_replyLinePaint); if (siteNameLayout != null) { - Theme.chat_replyNamePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outSiteNameText : Theme.key_chat_inSiteNameText)); + Theme.chat_replyNamePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outSiteNameText : Theme.key_chat_inSiteNameText)); canvas.save(); int x; if (siteNameRtl) { @@ -7756,9 +7765,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } if (currentMessageObject.isOutOwner()) { - Theme.chat_replyTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); + Theme.chat_replyTextPaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); } else { - Theme.chat_replyTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); + Theme.chat_replyTextPaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); } if (descriptionLayout != null) { @@ -7777,14 +7786,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT) { Drawable menuDrawable; if (currentMessageObject.isOutOwner()) { - Theme.chat_docNamePaint.setColor(Theme.getColor(Theme.key_chat_outFileNameText)); - Theme.chat_infoPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outFileInfoSelectedText : Theme.key_chat_outFileInfoText)); - Theme.chat_docBackPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outFileBackgroundSelected : Theme.key_chat_outFileBackground)); - menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgOutMenuSelectedDrawable : Theme.chat_msgOutMenuDrawable; + Theme.chat_docNamePaint.setColor(getThemedColor(Theme.key_chat_outFileNameText)); + Theme.chat_infoPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outFileInfoSelectedText : Theme.key_chat_outFileInfoText)); + Theme.chat_docBackPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outFileBackgroundSelected : Theme.key_chat_outFileBackground)); + menuDrawable = getThemedDrawable(isDrawSelectionBackground() ? Theme.key_drawable_msgOutMenuSelected : Theme.key_drawable_msgOutMenu); } else { - Theme.chat_docNamePaint.setColor(Theme.getColor(Theme.key_chat_inFileNameText)); - Theme.chat_infoPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inFileInfoSelectedText : Theme.key_chat_inFileInfoText)); - Theme.chat_docBackPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inFileBackgroundSelected : Theme.key_chat_inFileBackground)); + Theme.chat_docNamePaint.setColor(getThemedColor(Theme.key_chat_inFileNameText)); + Theme.chat_infoPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inFileInfoSelectedText : Theme.key_chat_inFileInfoText)); + Theme.chat_docBackPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inFileBackgroundSelected : Theme.key_chat_inFileBackground)); menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgInMenuSelectedDrawable : Theme.chat_msgInMenuDrawable; } @@ -7804,14 +7813,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (!imageDrawn) { if (currentMessageObject.isOutOwner()) { radialProgress.setColors(Theme.key_chat_outLoader, Theme.key_chat_outLoaderSelected, Theme.key_chat_outMediaIcon, Theme.key_chat_outMediaIconSelected); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outFileProgressSelected : Theme.key_chat_outFileProgress)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outFileProgressSelected : Theme.key_chat_outFileProgress)); videoRadialProgress.setColors(Theme.key_chat_outLoader, Theme.key_chat_outLoaderSelected, Theme.key_chat_outMediaIcon, Theme.key_chat_outMediaIconSelected); - videoRadialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outFileProgressSelected : Theme.key_chat_outFileProgress)); + videoRadialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outFileProgressSelected : Theme.key_chat_outFileProgress)); } else { radialProgress.setColors(Theme.key_chat_inLoader, Theme.key_chat_inLoaderSelected, Theme.key_chat_inMediaIcon, Theme.key_chat_inMediaIconSelected); - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inFileProgressSelected : Theme.key_chat_inFileProgress)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inFileProgressSelected : Theme.key_chat_inFileProgress)); videoRadialProgress.setColors(Theme.key_chat_inLoader, Theme.key_chat_inLoaderSelected, Theme.key_chat_inMediaIcon, Theme.key_chat_inMediaIconSelected); - videoRadialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inFileProgressSelected : Theme.key_chat_inFileProgress)); + videoRadialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inFileProgressSelected : Theme.key_chat_inFileProgress)); } rect.set(photoImage.getImageX(), photoImage.getImageY(), photoImage.getImageX() + photoImage.getImageWidth(), photoImage.getImageY() + photoImage.getImageHeight()); @@ -7827,9 +7836,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.drawPath(rectPath, Theme.chat_docBackPaint); } else { radialProgress.setColors(Theme.key_chat_mediaLoaderPhoto, Theme.key_chat_mediaLoaderPhotoSelected, Theme.key_chat_mediaLoaderPhotoIcon, Theme.key_chat_mediaLoaderPhotoIconSelected); - radialProgress.setProgressColor(Theme.getColor(Theme.key_chat_mediaProgress)); + radialProgress.setProgressColor(getThemedColor(Theme.key_chat_mediaProgress)); videoRadialProgress.setColors(Theme.key_chat_mediaLoaderPhoto, Theme.key_chat_mediaLoaderPhotoSelected, Theme.key_chat_mediaLoaderPhotoIcon, Theme.key_chat_mediaLoaderPhotoIconSelected); - videoRadialProgress.setProgressColor(Theme.getColor(Theme.key_chat_mediaProgress)); + videoRadialProgress.setProgressColor(getThemedColor(Theme.key_chat_mediaProgress)); if (buttonState == -1 && radialProgress.getIcon() != MediaActionDrawable.ICON_NONE) { radialProgress.setIcon(MediaActionDrawable.ICON_NONE, true, true); @@ -7844,11 +7853,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate subtitleY += (docTitleLayout.getLineCount() - 1) * AndroidUtilities.dp(16) + AndroidUtilities.dp(2); } if (currentMessageObject.isOutOwner()) { - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); - videoRadialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || videoButtonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); + videoRadialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || videoButtonPressed != 0 ? Theme.key_chat_outAudioSelectedProgress : Theme.key_chat_outAudioProgress)); } else { - radialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); - videoRadialProgress.setProgressColor(Theme.getColor(isDrawSelectionBackground() || videoButtonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + radialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || buttonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + videoRadialProgress.setProgressColor(getThemedColor(isDrawSelectionBackground() || videoButtonPressed != 0 ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); } } if (shouldDrawMenuDrawable()) { @@ -7922,7 +7931,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int smallImageStartY = 0; if (!hasInvoicePreview && !currentMessageObject.isSponsored()) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewLine : Theme.key_chat_inPreviewLine)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewLine : Theme.key_chat_inPreviewLine)); if (alpha != 1f) { Theme.chat_replyLinePaint.setAlpha((int) (alpha * Theme.chat_replyLinePaint.getAlpha())); } @@ -7931,7 +7940,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (siteNameLayout != null) { smallImageStartY = linkPreviewY - AndroidUtilities.dp(1); - Theme.chat_replyNamePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outSiteNameText : Theme.key_chat_inSiteNameText)); + Theme.chat_replyNamePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outSiteNameText : Theme.key_chat_inSiteNameText)); if (alpha != 1f) { Theme.chat_replyNamePaint.setAlpha((int) (alpha * Theme.chat_replyLinePaint.getAlpha())); } @@ -8030,11 +8039,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } if (currentMessageObject.isOutOwner()) { - Theme.chat_replyNamePaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messageTextOut), (int) (255 * alpha))); - Theme.chat_replyTextPaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messageTextOut), (int) (255 * alpha))); + Theme.chat_replyNamePaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messageTextOut), (int) (255 * alpha))); + Theme.chat_replyTextPaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messageTextOut), (int) (255 * alpha))); } else { - Theme.chat_replyNamePaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messageTextIn), (int) (255 * alpha))); - Theme.chat_replyTextPaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messageTextIn), (int) (255 * alpha))); + Theme.chat_replyNamePaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messageTextIn), (int) (255 * alpha))); + Theme.chat_replyTextPaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messageTextIn), (int) (255 * alpha))); } if (titleLayout != null) { if (linkPreviewY != startY) { @@ -8123,15 +8132,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate videoButtonY = (int) (photoImage.getImageY() + AndroidUtilities.dp(8)); videoRadialProgress.setProgressRect(videoButtonX, videoButtonY, videoButtonX + AndroidUtilities.dp(24), videoButtonY + AndroidUtilities.dp(24)); } + Paint timeBackgroundPaint = getThemedPaint(Theme.key_paint_chatTimeBackground); if (photosCountLayout != null && photoImage.getVisible()) { int x = (int) (photoImage.getImageX() + photoImage.getImageWidth() - AndroidUtilities.dp(8) - photosCountWidth); int y = (int) (photoImage.getImageY() + photoImage.getImageHeight() - AndroidUtilities.dp(19)); rect.set(x - AndroidUtilities.dp(4), y - AndroidUtilities.dp(1.5f), x + photosCountWidth + AndroidUtilities.dp(4), y + AndroidUtilities.dp(14.5f)); - int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); - Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * controlsAlpha)); + int oldAlpha = timeBackgroundPaint.getAlpha(); + timeBackgroundPaint.setAlpha((int) (oldAlpha * controlsAlpha)); Theme.chat_durationPaint.setAlpha((int) (255 * controlsAlpha)); - canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), Theme.chat_timeBackgroundPaint); - Theme.chat_timeBackgroundPaint.setAlpha(oldAlpha); + canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), timeBackgroundPaint); + timeBackgroundPaint.setAlpha(oldAlpha); canvas.save(); canvas.translate(x, y); photosCountLayout.draw(canvas); @@ -8147,7 +8157,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate y = (int) (photoImage.getImageY() + AndroidUtilities.dp(6)); int height = AndroidUtilities.dp(documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER ? 14.5f : 16.5f); rect.set(x - AndroidUtilities.dp(4), y - AndroidUtilities.dp(1.5f), x + durationWidth + AndroidUtilities.dp(4), y + height); - canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), Theme.chat_timeBackgroundPaint); + canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), timeBackgroundPaint); } else { x = linkX; y = linkPreviewY; @@ -8156,19 +8166,19 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate x = (int) (photoImage.getImageX() + photoImage.getImageWidth() - AndroidUtilities.dp(8) - durationWidth); y = (int) (photoImage.getImageY() + photoImage.getImageHeight() - AndroidUtilities.dp(19)); rect.set(x - AndroidUtilities.dp(4), y - AndroidUtilities.dp(1.5f), x + durationWidth + AndroidUtilities.dp(4), y + AndroidUtilities.dp(14.5f)); - canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), Theme.chat_timeBackgroundPaint); + canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), getThemedPaint(Theme.key_paint_chatTimeBackground)); } canvas.save(); canvas.translate(x, y); if (hasInvoicePreview) { if (drawPhotoImage) { - Theme.chat_shipmentPaint.setColor(Theme.getColor(Theme.key_chat_previewGameText)); + Theme.chat_shipmentPaint.setColor(getThemedColor(Theme.key_chat_previewGameText)); } else { if (currentMessageObject.isOutOwner()) { - Theme.chat_shipmentPaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); + Theme.chat_shipmentPaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); } else { - Theme.chat_shipmentPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); + Theme.chat_shipmentPaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); } } } @@ -8181,13 +8191,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int instantY = startY + linkPreviewHeight + AndroidUtilities.dp(10); Paint backPaint = Theme.chat_instantViewRectPaint; if (currentMessageObject.isOutOwner()) { - instantDrawable = Theme.chat_msgOutInstantDrawable; - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_outPreviewInstantText)); - backPaint.setColor(Theme.getColor(Theme.key_chat_outPreviewInstantText)); + instantDrawable = getThemedDrawable(Theme.key_drawable_msgOutInstant); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_outPreviewInstantText)); + backPaint.setColor(getThemedColor(Theme.key_chat_outPreviewInstantText)); } else { instantDrawable = Theme.chat_msgInInstantDrawable; - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); - backPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); + backPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); } instantButtonRect.set(linkX, instantY, linkX + instantWidth, instantY + AndroidUtilities.dp(36)); @@ -8242,9 +8252,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate float y = button.y + layoutHeight - AndroidUtilities.dp(2) + transitionParams.deltaBottom; rect.set(button.x + addX, y, button.x + addX + button.width, y + button.height); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); - canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), a == pressedBotButton ? Theme.chat_actionBackgroundSelectedPaint : Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), getThemedPaint(a == pressedBotButton ? Theme.key_paint_chatActionBackgroundSelected : Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); } @@ -8253,13 +8263,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate button.title.draw(canvas); canvas.restore(); if (button.button instanceof TLRPC.TL_keyboardButtonUrl) { - int x = button.x + button.width - AndroidUtilities.dp(3) - Theme.chat_botLinkDrawalbe.getIntrinsicWidth() + addX; - setDrawableBounds(Theme.chat_botLinkDrawalbe, x, y + AndroidUtilities.dp(3)); - Theme.chat_botLinkDrawalbe.draw(canvas); + Drawable drawable = getThemedDrawable(Theme.key_drawable_botLink); + int x = button.x + button.width - AndroidUtilities.dp(3) - drawable.getIntrinsicWidth() + addX; + setDrawableBounds(drawable, x, y + AndroidUtilities.dp(3)); + drawable.draw(canvas); } else if (button.button instanceof TLRPC.TL_keyboardButtonSwitchInline) { - int x = button.x + button.width - AndroidUtilities.dp(3) - Theme.chat_botInlineDrawable.getIntrinsicWidth() + addX; - setDrawableBounds(Theme.chat_botInlineDrawable, x, y + AndroidUtilities.dp(3)); - Theme.chat_botInlineDrawable.draw(canvas); + Drawable drawable = getThemedDrawable(Theme.key_drawable_botInline); + int x = button.x + button.width - AndroidUtilities.dp(3) - drawable.getIntrinsicWidth() + addX; + setDrawableBounds(drawable, x, y + AndroidUtilities.dp(3)); + drawable.draw(canvas); } else if (button.button instanceof TLRPC.TL_keyboardButtonCallback || button.button instanceof TLRPC.TL_keyboardButtonRequestGeoLocation || button.button instanceof TLRPC.TL_keyboardButtonGame || button.button instanceof TLRPC.TL_keyboardButtonBuy || button.button instanceof TLRPC.TL_keyboardButtonUrlAuth) { if (button.button instanceof TLRPC.TL_keyboardButtonBuy) { int x = button.x + button.width - AndroidUtilities.dp(5) - Theme.chat_botCardDrawalbe.getIntrinsicWidth() + addX; @@ -8329,7 +8341,6 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (transitionParams.animateText) { textY = transitionParams.animateFromTextY * (1f - transitionParams.animateChangeProgress) + this.textY * transitionParams.animateChangeProgress; } - textY += transitionYOffsetForDrawables; if (firstVisibleBlockNum >= 0) { int restore = Integer.MIN_VALUE; int oldAlpha = 0; @@ -8369,7 +8380,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } MessageObject.TextLayoutBlock block = textLayoutBlocks.get(a); canvas.save(); - canvas.translate(textX - (block.isRtl() ? (int) Math.ceil(currentMessageObject.textXOffset) : 0), textY + block.textYOffset); + canvas.translate(textX - (block.isRtl() ? (int) Math.ceil(currentMessageObject.textXOffset) : 0), textY + block.textYOffset + transitionYOffsetForDrawables); if (pressedLink != null && a == linkBlockNum && !drawOnlyText) { for (int b = 0; b < urlPath.size(); b++) { canvas.drawPath(urlPath.get(b), Theme.chat_urlPaint); @@ -8385,7 +8396,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate delegate.getTextSelectionHelper().draw(currentMessageObject, block, canvas); } try { + Emoji.emojiDrawingYOffset = -transitionYOffsetForDrawables; block.textLayout.draw(canvas); + Emoji.emojiDrawingYOffset = 0; } catch (Exception e) { FileLog.e(e); } @@ -8654,7 +8667,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else { if (hasMiniProgress != 0) { - radialProgress.setMiniProgressBackgroundColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); + radialProgress.setMiniProgressBackgroundColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); boolean playing = MediaController.getInstance().isPlayingMessage(currentMessageObject); if (!playing || MediaController.getInstance().isMessagePaused()) { buttonState = 0; @@ -8821,7 +8834,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } if (hasMiniProgress != 0) { - radialProgress.setMiniProgressBackgroundColor(Theme.getColor(Theme.key_chat_inLoaderPhoto)); + radialProgress.setMiniProgressBackgroundColor(getThemedColor(Theme.key_chat_inLoaderPhoto)); buttonState = 3; radialProgress.setIcon(getIconForCurrentState(), ifSame, animated); if (hasMiniProgress == 1) { @@ -9444,7 +9457,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate private void measureTime(MessageObject messageObject) { CharSequence signString; - int fromId = messageObject.getFromChatId(); + long fromId = messageObject.getFromChatId(); if (messageObject.scheduled) { signString = null; } else if (messageObject.messageOwner.post_author != null) { @@ -9591,7 +9604,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate private void updateCurrentUserAndChat() { MessagesController messagesController = MessagesController.getInstance(currentAccount); TLRPC.MessageFwdHeader fwd_from = currentMessageObject.messageOwner.fwd_from; - int currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); if (fwd_from != null && fwd_from.from_id instanceof TLRPC.TL_peerChannel && currentMessageObject.getDialogId() == currentUserId) { currentChat = MessagesController.getInstance(currentAccount).getChat(fwd_from.from_id.channel_id); } else if (fwd_from != null && fwd_from.saved_from_peer != null) { @@ -9620,10 +9633,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate currentUser = new TLRPC.TL_user(); currentUser.first_name = fwd_from.from_name; } else { - int fromId = currentMessageObject.getFromChatId(); - if (fromId > 0 && !currentMessageObject.messageOwner.post) { + long fromId = currentMessageObject.getFromChatId(); + if (DialogObject.isUserDialog(fromId) && !currentMessageObject.messageOwner.post) { currentUser = messagesController.getUser(fromId); - } else if (fromId < 0) { + } else if (DialogObject.isChatDialog(fromId)) { currentChat = messagesController.getChat(-fromId); } else if (currentMessageObject.messageOwner.post) { currentChat = messagesController.getChat(currentMessageObject.messageOwner.peer_id.channel_id); @@ -9732,9 +9745,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } int color; if (currentMessageObject.shouldDrawWithoutBackground()) { - color = Theme.getColor(Theme.key_chat_stickerViaBotNameText); + color = getThemedColor(Theme.key_chat_stickerViaBotNameText); } else { - color = Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outViaBotNameText : Theme.key_chat_inViaBotNameText); + color = getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outViaBotNameText : Theme.key_chat_inViaBotNameText); } String viaBotString = LocaleController.getString("ViaBot", R.string.ViaBot); if (currentNameString.length() > 0) { @@ -9927,7 +9940,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (messageObject.customReplyName != null) { name = messageObject.customReplyName; } else { - int fromId = messageObject.replyMessageObject.getFromChatId(); + long fromId = messageObject.replyMessageObject.getFromChatId(); if (fromId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(fromId); if (user != null) { @@ -10200,50 +10213,50 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } if (currentMessageObject.isOutOwner()) { - Theme.chat_msgTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); - Theme.chat_msgTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkOut); - Theme.chat_msgGameTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); - Theme.chat_msgGameTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkOut); - Theme.chat_replyTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkOut); + Theme.setColorToPaint(Theme.chat_msgTextPaint, getThemedColor(Theme.key_chat_messageTextOut)); + Theme.setColorToPaint(Theme.chat_msgGameTextPaint, getThemedColor(Theme.key_chat_messageTextOut)); + Theme.chat_msgGameTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkOut); + Theme.chat_replyTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkOut); + Theme.chat_msgTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkOut); } else { - Theme.chat_msgTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_msgTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkIn); - Theme.chat_msgGameTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_msgGameTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkIn); - Theme.chat_replyTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkIn); + Theme.setColorToPaint(Theme.chat_msgTextPaint, getThemedColor(Theme.key_chat_messageTextIn)); + Theme.setColorToPaint(Theme.chat_msgGameTextPaint, getThemedColor(Theme.key_chat_messageTextIn)); + Theme.chat_msgGameTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkIn); + Theme.chat_replyTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkIn); + Theme.chat_msgTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkIn); } if (documentAttach != null) { if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO) { if (currentMessageObject.isOutOwner()) { - seekBarWaveform.setColors(Theme.getColor(Theme.key_chat_outVoiceSeekbar), Theme.getColor(Theme.key_chat_outVoiceSeekbarFill), Theme.getColor(Theme.key_chat_outVoiceSeekbarSelected)); - seekBar.setColors(Theme.getColor(Theme.key_chat_outAudioSeekbar), Theme.getColor(Theme.key_chat_outAudioCacheSeekbar), Theme.getColor(Theme.key_chat_outAudioSeekbarFill), Theme.getColor(Theme.key_chat_outAudioSeekbarFill), Theme.getColor(Theme.key_chat_outAudioSeekbarSelected)); + seekBarWaveform.setColors(getThemedColor(Theme.key_chat_outVoiceSeekbar), getThemedColor(Theme.key_chat_outVoiceSeekbarFill), getThemedColor(Theme.key_chat_outVoiceSeekbarSelected)); + seekBar.setColors(getThemedColor(Theme.key_chat_outAudioSeekbar), getThemedColor(Theme.key_chat_outAudioCacheSeekbar), getThemedColor(Theme.key_chat_outAudioSeekbarFill), getThemedColor(Theme.key_chat_outAudioSeekbarFill), getThemedColor(Theme.key_chat_outAudioSeekbarSelected)); } else { - seekBarWaveform.setColors(Theme.getColor(Theme.key_chat_inVoiceSeekbar), Theme.getColor(Theme.key_chat_inVoiceSeekbarFill), Theme.getColor(Theme.key_chat_inVoiceSeekbarSelected)); - seekBar.setColors(Theme.getColor(Theme.key_chat_inAudioSeekbar), Theme.getColor(Theme.key_chat_inAudioCacheSeekbar), Theme.getColor(Theme.key_chat_inAudioSeekbarFill), Theme.getColor(Theme.key_chat_inAudioSeekbarFill), Theme.getColor(Theme.key_chat_inAudioSeekbarSelected)); + seekBarWaveform.setColors(getThemedColor(Theme.key_chat_inVoiceSeekbar), getThemedColor(Theme.key_chat_inVoiceSeekbarFill), getThemedColor(Theme.key_chat_inVoiceSeekbarSelected)); + seekBar.setColors(getThemedColor(Theme.key_chat_inAudioSeekbar), getThemedColor(Theme.key_chat_inAudioCacheSeekbar), getThemedColor(Theme.key_chat_inAudioSeekbarFill), getThemedColor(Theme.key_chat_inAudioSeekbarFill), getThemedColor(Theme.key_chat_inAudioSeekbarSelected)); } } else if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) { if (currentMessageObject.isOutOwner()) { - seekBar.setColors(Theme.getColor(Theme.key_chat_outAudioSeekbar), Theme.getColor(Theme.key_chat_outAudioCacheSeekbar), Theme.getColor(Theme.key_chat_outAudioSeekbarFill), Theme.getColor(Theme.key_chat_outAudioSeekbarFill), Theme.getColor(Theme.key_chat_outAudioSeekbarSelected)); + seekBar.setColors(getThemedColor(Theme.key_chat_outAudioSeekbar), getThemedColor(Theme.key_chat_outAudioCacheSeekbar), getThemedColor(Theme.key_chat_outAudioSeekbarFill), getThemedColor(Theme.key_chat_outAudioSeekbarFill), getThemedColor(Theme.key_chat_outAudioSeekbarSelected)); } else { - seekBar.setColors(Theme.getColor(Theme.key_chat_inAudioSeekbar), Theme.getColor(Theme.key_chat_inAudioCacheSeekbar), Theme.getColor(Theme.key_chat_inAudioSeekbarFill), Theme.getColor(Theme.key_chat_inAudioSeekbarFill), Theme.getColor(Theme.key_chat_inAudioSeekbarSelected)); + seekBar.setColors(getThemedColor(Theme.key_chat_inAudioSeekbar), getThemedColor(Theme.key_chat_inAudioCacheSeekbar), getThemedColor(Theme.key_chat_inAudioSeekbarFill), getThemedColor(Theme.key_chat_inAudioSeekbarFill), getThemedColor(Theme.key_chat_inAudioSeekbarSelected)); } } } if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO) { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + Theme.setColorToPaint(Theme.chat_timePaint, getThemedColor(Theme.key_chat_serviceText)); } else { if (mediaBackground) { if (currentMessageObject.shouldDrawWithoutBackground()) { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + Theme.setColorToPaint(Theme.chat_timePaint, getThemedColor(Theme.key_chat_serviceText)); } else { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_mediaTimeText)); + Theme.setColorToPaint(Theme.chat_timePaint, getThemedColor(Theme.key_chat_mediaTimeText)); } } else { if (currentMessageObject.isOutOwner()) { - Theme.chat_timePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); + Theme.setColorToPaint(Theme.chat_timePaint, getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); } else { - Theme.chat_timePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); + Theme.setColorToPaint(Theme.chat_timePaint, getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); } } } @@ -10254,12 +10267,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate boolean forceMediaByGroup = currentPosition != null && (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0 && currentMessagesGroup.isDocuments && !drawPinnedBottom; if (currentMessageObject.isOutOwner()) { if (transitionParams.changePinnedBottomProgress >= 1 && !mediaBackground && !drawPinnedBottom && !forceMediaByGroup) { - currentBackgroundDrawable = Theme.chat_msgOutDrawable; - currentBackgroundSelectedDrawable = Theme.chat_msgOutSelectedDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOut); + currentBackgroundSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutSelected); transitionParams.drawPinnedBottomBackground = false; } else { - currentBackgroundDrawable = Theme.chat_msgOutMediaDrawable; - currentBackgroundSelectedDrawable = Theme.chat_msgOutMediaSelectedDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMedia); + currentBackgroundSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMediaSelected); transitionParams.drawPinnedBottomBackground = true; } setBackgroundTopY(true); @@ -10321,12 +10334,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate setDrawableBoundsInner(currentBackgroundShadowDrawable, backgroundLeft, backgroundDrawableTop, backgroundDrawableRight, backgroundHeight); } else { if (transitionParams.changePinnedBottomProgress >= 1 && !mediaBackground && !drawPinnedBottom && !forceMediaByGroup) { - currentBackgroundDrawable = Theme.chat_msgInDrawable; - currentBackgroundSelectedDrawable = Theme.chat_msgInSelectedDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgIn); + currentBackgroundSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInSelected); transitionParams.drawPinnedBottomBackground = false; } else { - currentBackgroundDrawable = Theme.chat_msgInMediaDrawable; - currentBackgroundSelectedDrawable = Theme.chat_msgInMediaSelectedDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMedia); + currentBackgroundSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMediaSelected); transitionParams.drawPinnedBottomBackground = true; } setBackgroundTopY(true); @@ -10509,7 +10522,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (transitionParams.changePinnedBottomProgress != 1f && currentPosition == null) { if (currentMessageObject.isOutOwner()) { - Theme.MessageDrawable drawable = Theme.chat_msgOutDrawable; + Theme.MessageDrawable drawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOut); Rect rect = currentBackgroundDrawable.getBounds(); drawable.setBounds(rect.left, rect.top, rect.right + AndroidUtilities.dp(6), rect.bottom); @@ -10535,9 +10548,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } else { Theme.MessageDrawable drawable; if (transitionParams.drawPinnedBottomBackground) { - drawable = Theme.chat_msgInDrawable; + drawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgIn); } else { - drawable = Theme.chat_msgInMediaDrawable; + drawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMedia); } float alpha = !mediaBackground && !pinnedBottom ? transitionParams.changePinnedBottomProgress : (1f - transitionParams.changePinnedBottomProgress); drawable.setAlpha((int) (255 * alpha)); @@ -10659,27 +10672,29 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else { rect.set(sideStartX, sideStartY, sideStartX + AndroidUtilities.dp(32), sideStartY + AndroidUtilities.dp(32)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); - canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), sideButtonPressed ? Theme.chat_actionBackgroundSelectedPaint : Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), getThemedPaint(sideButtonPressed ? Theme.key_paint_chatActionBackgroundSelected : Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundGradientDarkenPaint); } if (drawSideButton == 2) { + Drawable goIconDrawable = getThemedDrawable(Theme.key_drawable_goIcon); if (currentMessageObject.isOutOwner()) { - setDrawableBounds(Theme.chat_goIconDrawable, sideStartX + AndroidUtilities.dp(10), sideStartY + AndroidUtilities.dp(9)); + setDrawableBounds(goIconDrawable, sideStartX + AndroidUtilities.dp(10), sideStartY + AndroidUtilities.dp(9)); canvas.save(); - canvas.scale(-1, 1, Theme.chat_goIconDrawable.getBounds().centerX(), Theme.chat_goIconDrawable.getBounds().centerY()); + canvas.scale(-1, 1, goIconDrawable.getBounds().centerX(), goIconDrawable.getBounds().centerY()); } else { - setDrawableBounds(Theme.chat_goIconDrawable, sideStartX + AndroidUtilities.dp(12), sideStartY + AndroidUtilities.dp(9)); + setDrawableBounds(goIconDrawable, sideStartX + AndroidUtilities.dp(12), sideStartY + AndroidUtilities.dp(9)); } - Theme.chat_goIconDrawable.draw(canvas); + goIconDrawable.draw(canvas); if (currentMessageObject.isOutOwner()) { canvas.restore(); } } else { - setDrawableBounds(Theme.chat_shareIconDrawable, sideStartX + AndroidUtilities.dp(8), sideStartY + AndroidUtilities.dp(9)); - Theme.chat_shareIconDrawable.draw(canvas); + Drawable drawable = getThemedDrawable(Theme.key_drawable_shareIcon); + setDrawableBounds(drawable, sideStartX + AndroidUtilities.dp(8), sideStartY + AndroidUtilities.dp(9)); + drawable.draw(canvas); } } } @@ -10761,16 +10776,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } rect.set(sideStartX, sideStartY, sideStartX + AndroidUtilities.dp(32), sideStartY + height); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); if (alpha != 1f) { - int oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); - Theme.chat_actionBackgroundPaint.setAlpha((int) (alpha * oldAlpha)); - canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundPaint); - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); + int oldAlpha = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (alpha * oldAlpha)); + canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), getThemedPaint(Theme.key_paint_chatActionBackground)); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha); } else { - canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), sideButtonPressed ? Theme.chat_actionBackgroundSelectedPaint : Theme.chat_actionBackgroundPaint); + canvas.drawRoundRect(rect, AndroidUtilities.dp(16), AndroidUtilities.dp(16), getThemedPaint(sideButtonPressed ? Theme.key_paint_chatActionBackgroundSelected : Theme.key_paint_chatActionBackground)); } - if (Theme.hasGradientService()) { + if (hasGradientService()) { if (alpha != 1f) { int oldAlpha = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (alpha * oldAlpha)); @@ -10781,18 +10796,18 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } - - setDrawableBounds(Theme.chat_commentStickerDrawable, sideStartX + AndroidUtilities.dp(4), sideStartY + AndroidUtilities.dp(4)); + Drawable commentStickerDrawable = Theme.getThemeDrawable(Theme.key_drawable_commentSticker); + setDrawableBounds(commentStickerDrawable, sideStartX + AndroidUtilities.dp(4), sideStartY + AndroidUtilities.dp(4)); if (alpha != 1f) { - Theme.chat_commentStickerDrawable.setAlpha((int) (255 * alpha)); - Theme.chat_commentStickerDrawable.draw(canvas); - Theme.chat_commentStickerDrawable.setAlpha(255); + commentStickerDrawable.setAlpha((int) (255 * alpha)); + commentStickerDrawable.draw(canvas); + commentStickerDrawable.setAlpha(255); } else { - Theme.chat_commentStickerDrawable.draw(canvas); + commentStickerDrawable.draw(canvas); } if (commentLayout != null) { - Theme.chat_stickerCommentCountPaint.setColor(Theme.getColor(Theme.key_chat_stickerReplyNameText)); + Theme.chat_stickerCommentCountPaint.setColor(getThemedColor(Theme.key_chat_stickerReplyNameText)); Theme.chat_stickerCommentCountPaint.setAlpha((int) (255 * alpha)); if (transitionParams.animateComments) { if (transitionParams.animateCommentsLayout != null) { @@ -10811,6 +10826,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } + private void applyServiceShaderMatrix(int measuredWidth, int backgroundHeight, float x, float viewTop) { + if (resourcesProvider != null) { + resourcesProvider.applyServiceShaderMatrix(measuredWidth, backgroundHeight, x, viewTop); + } else { + Theme.applyServiceShaderMatrix(measuredWidth, backgroundHeight, x, viewTop); + } + } + public void drawOutboundsContent(Canvas canvas) { if (transitionParams.animateBackgroundBoundsInner) { if (!transitionParams.transitionBotButtons.isEmpty()) { @@ -10893,15 +10916,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate public void drawBackground(Canvas canvas, int left, int top, int right, int bottom, boolean pinnedTop, boolean pinnedBottom, boolean selected, int keyboardHeight) { if (currentMessageObject.isOutOwner()) { if (!mediaBackground && !pinnedBottom) { - currentBackgroundDrawable = selected ? Theme.chat_msgOutSelectedDrawable : Theme.chat_msgOutDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(selected ? Theme.key_drawable_msgOutSelected : Theme.key_drawable_msgOut); } else { - currentBackgroundDrawable = selected ? Theme.chat_msgOutMediaSelectedDrawable : Theme.chat_msgOutMediaDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(selected ? Theme.key_drawable_msgOutMediaSelected : Theme.key_drawable_msgOutMedia); } } else { if (!mediaBackground && !pinnedBottom) { - currentBackgroundDrawable = selected ? Theme.chat_msgInSelectedDrawable : Theme.chat_msgInDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(selected ? Theme.key_drawable_msgInSelected : Theme.key_drawable_msgIn); } else { - currentBackgroundDrawable = selected ? Theme.chat_msgInMediaSelectedDrawable : Theme.chat_msgInMediaDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(selected ? Theme.key_drawable_msgInMediaSelected : Theme.key_drawable_msgInMedia); } } @@ -10971,7 +10994,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int oldAlpha; if (currentMessageObject.shouldDrawWithoutBackground()) { - Theme.chat_namePaint.setColor(Theme.getColor(Theme.key_chat_stickerNameText)); + Theme.chat_namePaint.setColor(getThemedColor(Theme.key_chat_stickerNameText)); if (currentMessageObject.isOutOwner()) { nameX = AndroidUtilities.dp(28); } else { @@ -10981,27 +11004,29 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate float alphaProgress = currentMessageObject.isOut() && (checkBoxVisible || checkBoxAnimationInProgress) ? (1.0f - checkBoxAnimationProgress) : 1.0f; rect.set((int) nameX - AndroidUtilities.dp(12), (int) nameY - AndroidUtilities.dp(5), (int) nameX + AndroidUtilities.dp(12) + nameWidth, (int) nameY + AndroidUtilities.dp(22)); - oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); - Theme.chat_actionBackgroundPaint.setAlpha((int) (alphaProgress * oldAlpha)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); - canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + oldAlpha = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (alphaProgress * oldAlpha)); + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { int oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * timeAlpha)); canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2); } + if (viaSpan1 != null || viaSpan2 != null) { + int color = getThemedColor(Theme.key_chat_stickerViaBotNameText); + color = (getThemedColor(Theme.key_chat_stickerViaBotNameText) & 0x00ffffff) | ((int) (Color.alpha(color) * alphaProgress) << 24); + if (viaSpan1 != null) { + viaSpan1.setColor(color); + } + if (viaSpan2 != null) { + viaSpan2.setColor(color); + } + } nameX -= nameOffsetX; - int color = Theme.getColor(Theme.key_chat_stickerViaBotNameText); - color = (Theme.getColor(Theme.key_chat_stickerViaBotNameText) & 0x00ffffff) | ((int) (Color.alpha(color) * alphaProgress) << 24); - if (viaSpan1 != null) { - viaSpan1.setColor(color); - } - if (viaSpan2 != null) { - viaSpan2.setColor(color); - } - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha); } else { if (mediaBackground || currentMessageObject.isOutOwner()) { nameX = backgroundDrawableLeft + transitionParams.deltaLeft + AndroidUtilities.dp(11) - nameOffsetX + getExtraTextX(); @@ -11010,22 +11035,31 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } if (currentUser != null) { if (currentBackgroundDrawable != null && currentBackgroundDrawable.hasGradient()) { - Theme.chat_namePaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); + Theme.chat_namePaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); } else { - Theme.chat_namePaint.setColor(AvatarDrawable.getNameColorForId(currentUser.id)); + Theme.chat_namePaint.setColor(getThemedColor(AvatarDrawable.getNameColorNameForId(currentUser.id))); } } else if (currentChat != null) { if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) { - Theme.chat_namePaint.setColor(Theme.changeColorAccent(AvatarDrawable.getNameColorForId(5))); + Theme.chat_namePaint.setColor(Theme.changeColorAccent(getThemedColor(AvatarDrawable.getNameColorNameForId(5)))); } else if (currentMessageObject.isOutOwner()) { - Theme.chat_namePaint.setColor(Theme.getColor(Theme.key_chat_outForwardedNameText)); + Theme.chat_namePaint.setColor(getThemedColor(Theme.key_chat_outForwardedNameText)); } else { - Theme.chat_namePaint.setColor(AvatarDrawable.getNameColorForId(currentChat.id)); + Theme.chat_namePaint.setColor(getThemedColor(AvatarDrawable.getNameColorNameForId(currentChat.id))); } } else { - Theme.chat_namePaint.setColor(AvatarDrawable.getNameColorForId(0)); + Theme.chat_namePaint.setColor(getThemedColor(AvatarDrawable.getNameColorNameForId(0))); } nameY = AndroidUtilities.dp(drawPinnedTop ? 9 : 10); + if (viaSpan1 != null || viaSpan2 != null) { + int color = getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outViaBotNameText : Theme.key_chat_inViaBotNameText); + if (viaSpan1 != null) { + viaSpan1.setColor(color); + } + if (viaSpan2 != null) { + viaSpan2.setColor(color); + } + } } if (currentMessagesGroup != null && currentMessagesGroup.transitionParams.backgroundChangeBounds) { nameX += currentMessagesGroup.transitionParams.offsetLeft; @@ -11045,11 +11079,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (adminLayout != null) { int color; if (currentMessageObject.shouldDrawWithoutBackground()) { - color = Theme.getColor(Theme.key_chat_stickerReplyNameText); + color = getThemedColor(Theme.key_chat_stickerReplyNameText); } else if (currentMessageObject.isOutOwner()) { - color = Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outAdminSelectedText : Theme.key_chat_outAdminText); + color = getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outAdminSelectedText : Theme.key_chat_outAdminText); } else { - color = Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inAdminSelectedText : Theme.key_chat_inAdminText); + color = getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inAdminSelectedText : Theme.key_chat_inAdminText); } Theme.chat_adminPaint.setColor(color); canvas.save(); @@ -11115,7 +11149,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate float forwardNameXLocal; if (drawForwardedNameLocal && forwardedNameLayoutLocal[0] != null && forwardedNameLayoutLocal[1] != null && (currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0)) { if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO || currentMessageObject.isAnyKindOfSticker()) { - Theme.chat_forwardNamePaint.setColor(Theme.getColor(Theme.key_chat_stickerReplyNameText)); + Theme.chat_forwardNamePaint.setColor(getThemedColor(Theme.key_chat_stickerReplyNameText)); if (currentMessageObject.needDrawForwarded()) { if (currentMessageObject.isOutOwner()) { forwardNameXLocal = forwardNameX = AndroidUtilities.dp(23); @@ -11133,14 +11167,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int backWidth = forwardedNameWidthLocal + AndroidUtilities.dp(14); rect.set((int) forwardNameXLocal - AndroidUtilities.dp(7), forwardNameY - AndroidUtilities.dp(6), (int) forwardNameXLocal - AndroidUtilities.dp(7) + backWidth, forwardNameY + AndroidUtilities.dp(38)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); int oldAlpha1 = -1, oldAlpha2 = -1; if (animatingAlpha != 1f) { - oldAlpha1 = Theme.chat_actionBackgroundPaint.getAlpha(); - Theme.chat_actionBackgroundPaint.setAlpha((int) (oldAlpha1 * animatingAlpha)); + oldAlpha1 = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha1 * animatingAlpha)); } - canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { if (animatingAlpha != 1f) { oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * animatingAlpha)); @@ -11148,7 +11182,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); } if (oldAlpha1 >= 0) { - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha1); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha1); } if (oldAlpha2 >= 0) { Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2); @@ -11157,9 +11191,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate forwardNameY = AndroidUtilities.dp(10 + (drawNameLayout ? 19 : 0)); if (currentMessageObject.isOutOwner()) { if (hasPsaHint) { - Theme.chat_forwardNamePaint.setColor(Theme.getColor(Theme.key_chat_outPsaNameText)); + Theme.chat_forwardNamePaint.setColor(getThemedColor(Theme.key_chat_outPsaNameText)); } else { - Theme.chat_forwardNamePaint.setColor(Theme.getColor(Theme.key_chat_outForwardedNameText)); + Theme.chat_forwardNamePaint.setColor(getThemedColor(Theme.key_chat_outForwardedNameText)); } if (currentMessageObject.needDrawForwarded()) { forwardNameXLocal = forwardNameX = backgroundDrawableLeft + AndroidUtilities.dp(11) + getExtraTextX(); @@ -11168,9 +11202,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else { if (hasPsaHint) { - Theme.chat_forwardNamePaint.setColor(Theme.getColor(Theme.key_chat_inPsaNameText)); + Theme.chat_forwardNamePaint.setColor(getThemedColor(Theme.key_chat_inPsaNameText)); } else { - Theme.chat_forwardNamePaint.setColor(Theme.getColor(Theme.key_chat_inForwardedNameText)); + Theme.chat_forwardNamePaint.setColor(getThemedColor(Theme.key_chat_inForwardedNameText)); } if (currentMessageObject.needDrawForwarded()) { if (mediaBackground) { @@ -11269,24 +11303,24 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } if (currentMessageObject.shouldDrawWithoutBackground()) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(Theme.key_chat_stickerReplyLine)); + Theme.chat_replyLinePaint.setColor(getThemedColor(Theme.key_chat_stickerReplyLine)); int oldAlpha = Theme.chat_replyLinePaint.getAlpha(); Theme.chat_replyLinePaint.setAlpha((int) (oldAlpha * timeAlpha)); - Theme.chat_replyNamePaint.setColor(Theme.getColor(Theme.key_chat_stickerReplyNameText)); + Theme.chat_replyNamePaint.setColor(getThemedColor(Theme.key_chat_stickerReplyNameText)); oldAlpha = Theme.chat_replyNamePaint.getAlpha(); Theme.chat_replyNamePaint.setAlpha((int) (oldAlpha * timeAlpha)); - Theme.chat_replyTextPaint.setColor(Theme.getColor(Theme.key_chat_stickerReplyMessageText)); + Theme.chat_replyTextPaint.setColor(getThemedColor(Theme.key_chat_stickerReplyMessageText)); oldAlpha = Theme.chat_replyTextPaint.getAlpha(); Theme.chat_replyTextPaint.setAlpha((int) (oldAlpha * timeAlpha)); int backWidth = Math.max(replyNameWidth, replyTextWidth) + AndroidUtilities.dp(14); rect.set((int) replyStartX - AndroidUtilities.dp(7), replyStartY - AndroidUtilities.dp(6), (int) replyStartX - AndroidUtilities.dp(7) + backWidth, replyStartY + AndroidUtilities.dp(41)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); - oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); - Theme.chat_actionBackgroundPaint.setAlpha((int) (oldAlpha * timeAlpha)); - canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundPaint); - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); - if (Theme.hasGradientService()) { + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + oldAlpha = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha * timeAlpha)); + canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), getThemedPaint(Theme.key_paint_chatActionBackground)); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha); + if (hasGradientService()) { oldAlpha = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha * timeAlpha)); canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); @@ -11294,20 +11328,20 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else { if (currentMessageObject.isOutOwner()) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(Theme.key_chat_outReplyLine)); - Theme.chat_replyNamePaint.setColor(Theme.getColor(Theme.key_chat_outReplyNameText)); + Theme.chat_replyLinePaint.setColor(getThemedColor(Theme.key_chat_outReplyLine)); + Theme.chat_replyNamePaint.setColor(getThemedColor(Theme.key_chat_outReplyNameText)); if (currentMessageObject.hasValidReplyMessageObject() && (currentMessageObject.replyMessageObject.type == 0 || !TextUtils.isEmpty(currentMessageObject.replyMessageObject.caption)) && !(currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame || currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice)) { - Theme.chat_replyTextPaint.setColor(Theme.getColor(Theme.key_chat_outReplyMessageText)); + Theme.chat_replyTextPaint.setColor(getThemedColor(Theme.key_chat_outReplyMessageText)); } else { - Theme.chat_replyTextPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outReplyMediaMessageSelectedText : Theme.key_chat_outReplyMediaMessageText)); + Theme.chat_replyTextPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outReplyMediaMessageSelectedText : Theme.key_chat_outReplyMediaMessageText)); } } else { - Theme.chat_replyLinePaint.setColor(Theme.getColor(Theme.key_chat_inReplyLine)); - Theme.chat_replyNamePaint.setColor(Theme.getColor(Theme.key_chat_inReplyNameText)); + Theme.chat_replyLinePaint.setColor(getThemedColor(Theme.key_chat_inReplyLine)); + Theme.chat_replyNamePaint.setColor(getThemedColor(Theme.key_chat_inReplyNameText)); if (currentMessageObject.hasValidReplyMessageObject() && (currentMessageObject.replyMessageObject.type == 0 || !TextUtils.isEmpty(currentMessageObject.replyMessageObject.caption)) && !(currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame || currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice)) { - Theme.chat_replyTextPaint.setColor(Theme.getColor(Theme.key_chat_inReplyMessageText)); + Theme.chat_replyTextPaint.setColor(getThemedColor(Theme.key_chat_inReplyMessageText)); } else { - Theme.chat_replyTextPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inReplyMediaMessageSelectedText : Theme.key_chat_inReplyMediaMessageText)); + Theme.chat_replyTextPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inReplyMediaMessageSelectedText : Theme.key_chat_inReplyMediaMessageText)); } } } @@ -11371,13 +11405,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate public void setCheckBoxVisible(boolean visible, boolean animated) { if (visible && checkBox == null) { - checkBox = new CheckBoxBase(this, 21); + checkBox = new CheckBoxBase(this, 21, resourcesProvider); if (attachedToWindow) { checkBox.onAttachedToWindow(); } } if (visible && mediaCheckBox == null && ((currentMessagesGroup != null && currentMessagesGroup.messages.size() > 1) || (groupedMessagesToSet != null && groupedMessagesToSet.messages.size() > 1))) { - mediaCheckBox = new CheckBoxBase(this, 21); + mediaCheckBox = new CheckBoxBase(this, 21, resourcesProvider); mediaCheckBox.setUseDefaultCheck(true); if (attachedToWindow) { mediaCheckBox.onAttachedToWindow(); @@ -11425,15 +11459,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate boolean forceMediaByGroup = currentPosition != null && (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0 && currentMessagesGroup.isDocuments && !drawPinnedBottom; if (currentMessageObject.isOutOwner()) { if (!mediaBackground && !drawPinnedBottom && !forceMediaByGroup) { - currentBackgroundDrawable = Theme.chat_msgOutDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOut); } else { - currentBackgroundDrawable = Theme.chat_msgOutMediaDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMedia); } } else { if (!mediaBackground && !drawPinnedBottom && !forceMediaByGroup) { - currentBackgroundDrawable = Theme.chat_msgInDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgIn); } else { - currentBackgroundDrawable = Theme.chat_msgInMediaDrawable; + currentBackgroundDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMedia); } } } @@ -11505,7 +11539,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate selectorDrawable[1].draw(canvas); } if (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0 && currentPosition.minX == 0 && currentPosition.maxX == 0) { - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); boolean drawnAvatars = false; int avatarsOffset = 2; if (commentAvatarImages != null) { @@ -11529,15 +11563,15 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } if (!mediaBackground || captionLayout != null) { if (isDrawSelectionBackground()) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarSelected : Theme.key_chat_inVoiceSeekbarSelected)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarSelected : Theme.key_chat_inVoiceSeekbarSelected)); } else { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbar : Theme.key_chat_inVoiceSeekbar)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbar : Theme.key_chat_inVoiceSeekbar)); } float ly = layoutHeight - AndroidUtilities.dp(45.1f - h2); canvas.drawLine(x, ly, endX - AndroidUtilities.dp(14), ly, Theme.chat_replyLinePaint); } if (commentLayout != null && drawSideButton != 3) { - Theme.chat_replyNamePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText)); + Theme.chat_replyNamePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPreviewInstantText : Theme.key_chat_inPreviewInstantText)); commentX = x + AndroidUtilities.dp(33 + avatarsOffset); if (drawCommentNumber) { commentX += commentNumberWidth + AndroidUtilities.dp(4); @@ -11587,7 +11621,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (drawCommentNumber) { commentUnreadX += commentNumberWidth + AndroidUtilities.dp(4); } - TLRPC.TL_messageReplies replies = null; + TLRPC.MessageReplies replies = null; if (currentMessagesGroup != null && !currentMessagesGroup.messages.isEmpty()) { MessageObject messageObject = currentMessagesGroup.messages.get(0); if (messageObject.hasReplies()) { @@ -11599,7 +11633,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } if (commentDrawUnread = (replies != null && replies.read_max_id != 0 && replies.read_max_id < replies.max_id)) { - int color = Theme.getColor(Theme.key_chat_inInstant); + int color = getThemedColor(Theme.key_chat_inInstant); Theme.chat_docBackPaint.setColor(color); int unreadX; if (transitionParams.animateComments) { @@ -11655,7 +11689,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } if ((drawProgress || commentProgressAlpha > 0.0f) && commentProgress != null) { - commentProgress.setColor(Theme.getColor(Theme.key_chat_inInstant)); + commentProgress.setColor(getThemedColor(Theme.key_chat_inInstant)); commentProgress.setAlpha(commentProgressAlpha); commentProgress.draw(canvas, commentX + AndroidUtilities.dp(11), commentY + AndroidUtilities.dp(12), commentProgressAlpha); invalidate(); @@ -11676,11 +11710,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate return; } if (currentMessageObject.isOutOwner()) { - Theme.chat_msgTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); - Theme.chat_msgTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkOut); + Theme.chat_msgTextPaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); + Theme.chat_msgTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkOut); } else { - Theme.chat_msgTextPaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_msgTextPaint.linkColor = Theme.getColor(Theme.key_chat_messageLinkIn); + Theme.chat_msgTextPaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); + Theme.chat_msgTextPaint.linkColor = getThemedColor(Theme.key_chat_messageLinkIn); } canvas.save(); float renderingAlpha = alpha; @@ -11717,7 +11751,20 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate rect.set(captionX, captionY, captionX + captionLayout.getWidth(), captionY + captionLayout.getHeight()); restore = canvas.saveLayerAlpha(rect, (int) (255 * renderingAlpha), Canvas.ALL_SAVE_FLAG); } - + if (transitionParams.animateBackgroundBoundsInner && currentBackgroundDrawable != null && currentMessagesGroup == null) { + Rect r = currentBackgroundDrawable.getBounds(); + if (currentMessageObject.isOutOwner() && !mediaBackground && !pinnedBottom) { + canvas.clipRect( + r.left + AndroidUtilities.dp(4), r.top + AndroidUtilities.dp(4), + r.right - AndroidUtilities.dp(10), r.bottom - AndroidUtilities.dp(4) + ); + } else { + canvas.clipRect( + r.left + AndroidUtilities.dp(4), r.top + AndroidUtilities.dp(4), + r.right - AndroidUtilities.dp(4), r.bottom - AndroidUtilities.dp(4) + ); + } + } canvas.translate(captionX, captionY); if (pressedLink != null) { @@ -11735,7 +11782,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (getDelegate().getTextSelectionHelper() != null && getDelegate().getTextSelectionHelper().isSelected(currentMessageObject)) { getDelegate().getTextSelectionHelper().drawCaption(currentMessageObject.isOutOwner(), captionLayout, canvas); } + Emoji.emojiDrawingYOffset = -transitionYOffsetForDrawables; captionLayout.draw(canvas); + Emoji.emojiDrawingYOffset = 0; } catch (Exception e) { FileLog.e(e); } @@ -11811,19 +11860,19 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate return; } if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO) { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + Theme.chat_timePaint.setColor(getThemedColor(Theme.key_chat_serviceText)); } else { if (shouldDrawTimeOnMedia()) { if (currentMessageObject.shouldDrawWithoutBackground()) { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + Theme.chat_timePaint.setColor(getThemedColor(Theme.key_chat_serviceText)); } else { - Theme.chat_timePaint.setColor(Theme.getColor(Theme.key_chat_mediaTimeText)); + Theme.chat_timePaint.setColor(getThemedColor(Theme.key_chat_mediaTimeText)); } } else { if (currentMessageObject.isOutOwner()) { - Theme.chat_timePaint.setColor(Theme.getColor(drawSelectionBackground ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); + Theme.chat_timePaint.setColor(getThemedColor(drawSelectionBackground ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); } else { - Theme.chat_timePaint.setColor(Theme.getColor(drawSelectionBackground ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); + Theme.chat_timePaint.setColor(getThemedColor(drawSelectionBackground ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); } } } @@ -11861,9 +11910,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate timeYOffset = -(drawCommentButton ? AndroidUtilities.dp(41.3f) : 0); Paint paint; if (currentMessageObject.shouldDrawWithoutBackground()) { - paint = Theme.chat_actionBackgroundPaint; + paint = getThemedPaint(Theme.key_paint_chatActionBackground); } else { - paint = Theme.chat_timeBackgroundPaint; + paint = getThemedPaint(Theme.key_paint_chatTimeBackground); } int oldAlpha = paint.getAlpha(); paint.setAlpha((int) (oldAlpha * timeAlpha * alpha)); @@ -11882,9 +11931,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate float y1 = timeY - AndroidUtilities.dp(23); rect.set(x1, y1, x1 + timeWidth + AndroidUtilities.dp((bigRadius ? 12 : 8) + (currentMessageObject.isOutOwner() ? 20 : 0)), y1 + AndroidUtilities.dp(17)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); canvas.drawRoundRect(rect, r, r, paint); - if (paint == Theme.chat_actionBackgroundPaint && Theme.hasGradientService()) { + if (paint == getThemedPaint(Theme.key_paint_chatActionBackground) && hasGradientService()) { int oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * timeAlpha * alpha)); canvas.drawRoundRect(rect, r, r, Theme.chat_actionBackgroundGradientDarkenPaint); @@ -12128,12 +12177,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate alpha *= progress; if (drawTime) { if (!currentMessageObject.isOutOwner()) { - Drawable clockDrawable; + MsgClockDrawable clockDrawable = Theme.chat_msgClockDrawable; + int clockColor; if (shouldDrawTimeOnMedia()) { - clockDrawable = Theme.chat_msgMediaClockDrawable; + clockColor = getThemedColor(Theme.key_chat_mediaSentClock); } else { - clockDrawable = drawSelectionBackground ? Theme.chat_msgInSelectedClockDrawable : Theme.chat_msgInClockDrawable; + clockColor = getThemedColor(drawSelectionBackground ? Theme.key_chat_outSentClockSelected : Theme.key_chat_mediaSentClock); } + clockDrawable.setColor(clockColor); float timeY = shouldDrawTimeOnMedia() ? photoImage.getImageY2() + additionalTimeOffsetY - AndroidUtilities.dp(9.0f) : layoutHeight - AndroidUtilities.dp(pinnedBottom || pinnedTop ? 9.5f : 8.5f) + timeYOffset; setDrawableBounds(clockDrawable, timeX + (currentMessageObject.scheduled ? 0 : AndroidUtilities.dp(11)), timeY - clockDrawable.getIntrinsicHeight()); clockDrawable.setAlpha((int) (255 * alpha)); @@ -12161,10 +12212,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } canvas.drawRoundRect(rect, AndroidUtilities.dp(1), AndroidUtilities.dp(1), Theme.chat_msgErrorPaint); Theme.chat_msgErrorPaint.setAlpha(oldAlpha); - setDrawableBounds(Theme.chat_msgErrorDrawable, x + AndroidUtilities.dp(6), y + AndroidUtilities.dp(2)); - Theme.chat_msgErrorDrawable.setAlpha((int) (255 * alpha)); - Theme.chat_msgErrorDrawable.draw(canvas); - Theme.chat_msgErrorDrawable.setAlpha(255); + Drawable errorDrawable = getThemedDrawable(Theme.key_drawable_msgError); + setDrawableBounds(errorDrawable, x + AndroidUtilities.dp(6), y + AndroidUtilities.dp(2)); + errorDrawable.setAlpha((int) (255 * alpha)); + errorDrawable.draw(canvas); + errorDrawable.setAlpha(255); if (useScale) { canvas.restore(); } @@ -12203,7 +12255,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate Drawable repliesDrawable; if (shouldDrawTimeOnMedia()) { if (currentMessageObject.shouldDrawWithoutBackground()) { - repliesDrawable = Theme.chat_msgStickerRepliesDrawable; + repliesDrawable = getThemedDrawable(Theme.key_drawable_msgStickerReplies); } else { repliesDrawable = Theme.chat_msgMediaRepliesDrawable; } @@ -12211,7 +12263,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (!currentMessageObject.isOutOwner()) { repliesDrawable = drawSelectionBackground ? Theme.chat_msgInRepliesSelectedDrawable : Theme.chat_msgInRepliesDrawable; } else { - repliesDrawable = drawSelectionBackground ? Theme.chat_msgOutRepliesSelectedDrawable : Theme.chat_msgOutRepliesDrawable; + repliesDrawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutRepliesSelected : Theme.key_drawable_msgOutReplies); } } setDrawableBounds(repliesDrawable, repliesX, timeY); @@ -12277,7 +12329,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate Drawable viewsDrawable; if (shouldDrawTimeOnMedia()) { if (currentMessageObject.shouldDrawWithoutBackground()) { - viewsDrawable = Theme.chat_msgStickerViewsDrawable; + viewsDrawable = getThemedDrawable(Theme.key_drawable_msgStickerViews); } else { viewsDrawable = Theme.chat_msgMediaViewsDrawable; } @@ -12285,7 +12337,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (!currentMessageObject.isOutOwner()) { viewsDrawable = drawSelectionBackground ? Theme.chat_msgInViewsSelectedDrawable : Theme.chat_msgInViewsDrawable; } else { - viewsDrawable = drawSelectionBackground ? Theme.chat_msgOutViewsSelectedDrawable : Theme.chat_msgOutViewsDrawable; + viewsDrawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutViewsSelected : Theme.key_drawable_msgOutViews); } } float y = shouldDrawTimeOnMedia() ? photoImage.getImageY2() + additionalTimeOffsetY - AndroidUtilities.dp(5.5f) - timeLayout.getHeight() : layoutHeight - AndroidUtilities.dp(pinnedBottom || pinnedTop ? 5.5f : 4.5f) - timeLayout.getHeight() + timeYOffset; @@ -12346,7 +12398,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate Drawable pinnedDrawable; if (shouldDrawTimeOnMedia()) { if (currentMessageObject.shouldDrawWithoutBackground()) { - pinnedDrawable = Theme.chat_msgStickerPinnedDrawable; + pinnedDrawable = getThemedDrawable(Theme.key_drawable_msgStickerPinned); } else { pinnedDrawable = Theme.chat_msgMediaPinnedDrawable; } @@ -12354,7 +12406,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (!currentMessageObject.isOutOwner()) { pinnedDrawable = drawSelectionBackground ? Theme.chat_msgInPinnedSelectedDrawable : Theme.chat_msgInPinnedDrawable; } else { - pinnedDrawable = drawSelectionBackground ? Theme.chat_msgOutPinnedSelectedDrawable : Theme.chat_msgOutPinnedDrawable; + pinnedDrawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutPinnedSelected : Theme.key_drawable_msgOutPinned); } } if (transitionParams.animatePinned) { @@ -12392,22 +12444,24 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } float timeY = photoImage.getImageY2() + additionalTimeOffsetY - AndroidUtilities.dp(8.5f); if (drawClock) { - Drawable drawable; + MsgClockDrawable drawable = Theme.chat_msgClockDrawable; + int color; if (shouldDrawTimeOnMedia()) { if (currentMessageObject.shouldDrawWithoutBackground()) { - Theme.chat_msgStickerClockDrawable.setAlpha((int) (255 * timeAlpha * alpha)); - setDrawableBounds(Theme.chat_msgStickerClockDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 24 : 22) - Theme.chat_msgStickerClockDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgStickerClockDrawable.getIntrinsicHeight() + timeYOffset); - drawable = Theme.chat_msgStickerClockDrawable; + color = getThemedColor(Theme.key_chat_serviceText); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 24 : 22) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); + drawable.setAlpha((int) (255 * timeAlpha * alpha)); } else { - setDrawableBounds(Theme.chat_msgMediaClockDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 24 : 22) - Theme.chat_msgMediaClockDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgMediaClockDrawable.getIntrinsicHeight() + timeYOffset); - Theme.chat_msgMediaClockDrawable.setAlpha((int) (255 * alpha)); - drawable = Theme.chat_msgMediaClockDrawable; + color = getThemedColor(Theme.key_chat_mediaSentClock); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 24 : 22) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); + drawable.setAlpha((int) (255 * alpha)); } } else { - setDrawableBounds(Theme.chat_msgOutClockDrawable, layoutWidth - AndroidUtilities.dp(18.5f) - Theme.chat_msgOutClockDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - Theme.chat_msgOutClockDrawable.getIntrinsicHeight() + timeYOffset); - Theme.chat_msgOutClockDrawable.setAlpha((int) (255 * alpha)); - drawable = Theme.chat_msgOutClockDrawable; + color = getThemedColor(Theme.key_chat_outSentClock); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(18.5f) - drawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - drawable.getIntrinsicHeight() + timeYOffset); + drawable.setAlpha((int) (255 * alpha)); } + drawable.setColor(color); if (useScale) { canvas.save(); @@ -12450,16 +12504,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.save(); } if (currentMessageObject.shouldDrawWithoutBackground()) { + drawable = getThemedDrawable(Theme.key_drawable_msgStickerCheck); if (drawCheck1) { if (moveCheck) { canvas.translate(AndroidUtilities.dp(4.8f) * (1f - progress), 0); } - setDrawableBounds(Theme.chat_msgStickerCheckDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 28.3f : 26.3f) - Theme.chat_msgStickerCheckDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgStickerCheckDrawable.getIntrinsicHeight() + timeYOffset); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 28.3f : 26.3f) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); } else { - setDrawableBounds(Theme.chat_msgStickerCheckDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - Theme.chat_msgStickerCheckDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgStickerCheckDrawable.getIntrinsicHeight() + timeYOffset); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); } - Theme.chat_msgStickerCheckDrawable.setAlpha((int) (255 * timeAlpha * alpha)); - drawable = Theme.chat_msgStickerCheckDrawable; + drawable.setAlpha((int) (255 * timeAlpha * alpha)); } else { if (drawCheck1) { if (moveCheck) { @@ -12493,10 +12547,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (moveCheck) { canvas.translate(AndroidUtilities.dp(4) * (1f - progress), 0); } - drawable = drawSelectionBackground ? Theme.chat_msgOutCheckReadSelectedDrawable : Theme.chat_msgOutCheckReadDrawable; + drawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutCheckReadSelected : Theme.key_drawable_msgOutCheckRead); setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(22.5f) - drawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(pinnedBottom || pinnedTop ? 9 : 8) - drawable.getIntrinsicHeight() + timeYOffset); } else { - drawable = drawSelectionBackground ? Theme.chat_msgOutCheckSelectedDrawable : Theme.chat_msgOutCheckDrawable; + drawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutCheckSelected : Theme.key_drawable_msgOutCheck); setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(18.5f) - drawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(pinnedBottom || pinnedTop ? 9 : 8) - drawable.getIntrinsicHeight() + timeYOffset); } drawable.setAlpha((int) (255 * alpha)); @@ -12518,13 +12572,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (shouldDrawTimeOnMedia()) { Drawable drawable; if (currentMessageObject.shouldDrawWithoutBackground()) { - setDrawableBounds(Theme.chat_msgStickerHalfCheckDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - Theme.chat_msgStickerHalfCheckDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgStickerHalfCheckDrawable.getIntrinsicHeight() + timeYOffset); - Theme.chat_msgStickerHalfCheckDrawable.setAlpha((int) (255 * timeAlpha * alpha)); - drawable = Theme.chat_msgStickerHalfCheckDrawable; + drawable = getThemedDrawable(Theme.key_drawable_msgStickerHalfCheck); + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); + drawable.setAlpha((int) (255 * timeAlpha * alpha)); } else { - setDrawableBounds(Theme.chat_msgMediaHalfCheckDrawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - Theme.chat_msgMediaHalfCheckDrawable.getIntrinsicWidth(), timeY - Theme.chat_msgMediaHalfCheckDrawable.getIntrinsicHeight() + timeYOffset); - Theme.chat_msgMediaHalfCheckDrawable.setAlpha((int) (255 * timeAlpha * alpha)); drawable = Theme.chat_msgMediaHalfCheckDrawable; + setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(bigRadius ? 23.5f : 21.5f) - drawable.getIntrinsicWidth(), timeY - drawable.getIntrinsicHeight() + timeYOffset); + drawable.setAlpha((int) (255 * timeAlpha * alpha)); } if (useScale || moveCheck) { canvas.save(); @@ -12536,7 +12590,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } drawable.setAlpha(255); } else { - Drawable drawable = drawSelectionBackground ? Theme.chat_msgOutHalfCheckSelectedDrawable : Theme.chat_msgOutHalfCheckDrawable; + Drawable drawable = getThemedDrawable(drawSelectionBackground ? Theme.key_drawable_msgOutHalfCheckSelected : Theme.key_drawable_msgOutHalfCheck); setDrawableBounds(drawable, layoutWidth - AndroidUtilities.dp(18) - drawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(pinnedBottom || pinnedTop ? 9 : 8) - drawable.getIntrinsicHeight() + timeYOffset); drawable.setAlpha((int) (255 * alpha)); if (useScale || moveCheck) { @@ -12656,7 +12710,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } - Theme.chat_infoPaint.setColor(Theme.getColor(Theme.key_chat_mediaInfoText)); + Theme.chat_infoPaint.setColor(getThemedColor(Theme.key_chat_mediaInfoText)); int x1 = (int) (photoImage.getImageX() + AndroidUtilities.dp(4)); int y1 = (int) (photoImage.getImageY() + AndroidUtilities.dp(4)); @@ -12682,13 +12736,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.save(); canvas.scale(loadingProgressAlpha, loadingProgressAlpha, x1, y1); - int oldAlpha = Theme.chat_timeBackgroundPaint.getAlpha(); - Theme.chat_timeBackgroundPaint.setAlpha((int) (oldAlpha * controlsAlpha * loadingProgressAlpha)); + int oldAlpha = getThemedPaint(Theme.key_paint_chatTimeBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatTimeBackground).setAlpha((int) (oldAlpha * controlsAlpha * loadingProgressAlpha)); if (drawDocTitleLayout || (drawLoadingProgress && loadingProgressLayout != null) || (!drawLoadingProgress && infoLayout != null)) { rect.set(x1, y1, x1 + w, y1 + AndroidUtilities.dp(16.5f + 15.5f * alpha)); int[] rad = photoImage.getRoundRadius(); int r = Math.min(AndroidUtilities.dp(8), Math.max(rad[0], rad[1])); - canvas.drawRoundRect(rect, r, r, Theme.chat_timeBackgroundPaint); + canvas.drawRoundRect(rect, r, r, getThemedPaint(Theme.key_paint_chatTimeBackground)); } Theme.chat_infoPaint.setAlpha((int) (255 * controlsAlpha * loadingProgressAlpha)); @@ -12724,7 +12778,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } canvas.restore(); Theme.chat_infoPaint.setAlpha(255); - Theme.chat_timeBackgroundPaint.setAlpha(oldAlpha); + getThemedPaint(Theme.key_paint_chatTimeBackground).setAlpha(oldAlpha); } } if (animatingDrawVideoImageButton == 1) { @@ -12779,11 +12833,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } else if (currentMessageObject.type == 4) { if (docTitleLayout != null) { if (currentMessageObject.isOutOwner()) { - Theme.chat_locationTitlePaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); - Theme.chat_locationAddressPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outVenueInfoSelectedText : Theme.key_chat_outVenueInfoText)); + Theme.chat_locationTitlePaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); + Theme.chat_locationAddressPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outVenueInfoSelectedText : Theme.key_chat_outVenueInfoText)); } else { - Theme.chat_locationTitlePaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_locationAddressPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inVenueInfoSelectedText : Theme.key_chat_inVenueInfoText)); + Theme.chat_locationTitlePaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); + Theme.chat_locationAddressPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inVenueInfoSelectedText : Theme.key_chat_inVenueInfoText)); } if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeoLive) { @@ -12808,11 +12862,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate rect.set(photoImage.getImageX2() - AndroidUtilities.dp(43), cy - AndroidUtilities.dp(15), photoImage.getImageX2() - AndroidUtilities.dp(13), cy + AndroidUtilities.dp(15)); if (currentMessageObject.isOutOwner()) { - Theme.chat_radialProgress2Paint.setColor(Theme.getColor(Theme.key_chat_outInstant)); - Theme.chat_livePaint.setColor(Theme.getColor(Theme.key_chat_outInstant)); + Theme.chat_radialProgress2Paint.setColor(getThemedColor(Theme.key_chat_outInstant)); + Theme.chat_livePaint.setColor(getThemedColor(Theme.key_chat_outInstant)); } else { - Theme.chat_radialProgress2Paint.setColor(Theme.getColor(Theme.key_chat_inInstant)); - Theme.chat_livePaint.setColor(Theme.getColor(Theme.key_chat_inInstant)); + Theme.chat_radialProgress2Paint.setColor(getThemedColor(Theme.key_chat_inInstant)); + Theme.chat_livePaint.setColor(getThemedColor(Theme.key_chat_inInstant)); } int docTitleAlpha = Theme.chat_locationTitlePaint.getAlpha(); @@ -12880,11 +12934,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } else if (currentMessageObject.type == 16) { if (currentMessageObject.isOutOwner()) { - Theme.chat_audioTitlePaint.setColor(Theme.getColor(Theme.key_chat_messageTextOut)); - Theme.chat_contactPhonePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); + Theme.chat_audioTitlePaint.setColor(getThemedColor(Theme.key_chat_messageTextOut)); + Theme.chat_contactPhonePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText)); } else { - Theme.chat_audioTitlePaint.setColor(Theme.getColor(Theme.key_chat_messageTextIn)); - Theme.chat_contactPhonePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); + Theme.chat_audioTitlePaint.setColor(getThemedColor(Theme.key_chat_messageTextIn)); + Theme.chat_contactPhonePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText)); } forceNotDrawTime = true; int x; @@ -12915,7 +12969,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int idx = currentMessageObject.isVideoCall() ? 1 : 0; if (currentMessageObject.isOutOwner()) { icon = Theme.chat_msgCallUpGreenDrawable; - phone = isDrawSelectionBackground() ? Theme.chat_msgOutCallSelectedDrawable[idx] : Theme.chat_msgOutCallDrawable[idx]; + if (currentMessageObject.isVideoCall()) { + phone = getThemedDrawable(isDrawSelectionBackground() ? Theme.key_drawable_msgOutCallVideoSelected : Theme.key_drawable_msgOutCallVideo); + } else { + phone = getThemedDrawable(isDrawSelectionBackground() ? Theme.key_drawable_msgOutCallAudioSelected : Theme.key_drawable_msgOutCallAudio); + } } else { TLRPC.PhoneCallDiscardReason reason = currentMessageObject.messageOwner.action.reason; if (reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed || reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy) { @@ -12954,11 +13012,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int color1; int color2; if (currentMessageObject.isOutOwner()) { - color1 = Theme.getColor(Theme.key_chat_messageTextOut); - color2 = Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText); + color1 = getThemedColor(Theme.key_chat_messageTextOut); + color2 = getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outTimeSelectedText : Theme.key_chat_outTimeText); } else { - color1 = Theme.getColor(Theme.key_chat_messageTextIn); - color2 = Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText); + color1 = getThemedColor(Theme.key_chat_messageTextIn); + color2 = getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inTimeSelectedText : Theme.key_chat_inTimeText); } Theme.chat_audioTitlePaint.setColor(color1); Theme.chat_audioPerformerPaint.setColor(color1); @@ -13071,7 +13129,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } int tx = currentBackgroundDrawable.getBounds().right - closeTimeWidth - AndroidUtilities.dp(currentMessageObject.isOutOwner() ? 40 : 34); if (time <= 5000) { - Theme.chat_timePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPollWrongAnswer : Theme.key_chat_inPollWrongAnswer)); + Theme.chat_timePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outPollWrongAnswer : Theme.key_chat_inPollWrongAnswer)); } if (animatePollAnswer) { Theme.chat_timePaint.setAlpha((int) (255 * (1.0f - pollAnimationProgress))); @@ -13129,12 +13187,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate key = currentMessageObject.isOutOwner() ? Theme.key_chat_outPollWrongAnswer : Theme.key_chat_inPollWrongAnswer; } if (!currentBackgroundDrawable.hasGradient() || Theme.hasThemeKey(key)) { - Theme.chat_docBackPaint.setColor(Theme.getColor(key)); + Theme.chat_docBackPaint.setColor(getThemedColor(key)); } else { - Theme.chat_docBackPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); + Theme.chat_docBackPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); } } else { - Theme.chat_docBackPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); + Theme.chat_docBackPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); } if (animatePollAnswerAlpha) { float oldAlpha = Theme.chat_instantViewPaint.getAlpha() / 255.0f; @@ -13171,9 +13229,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate if (!pollVoted && !pollClosed || animatePollAnswerAlpha) { if (isDrawSelectionBackground()) { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarSelected : Theme.key_chat_inVoiceSeekbarSelected)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbarSelected : Theme.key_chat_inVoiceSeekbarSelected)); } else { - Theme.chat_replyLinePaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbar : Theme.key_chat_inVoiceSeekbar)); + Theme.chat_replyLinePaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outVoiceSeekbar : Theme.key_chat_inVoiceSeekbar)); } if (animatePollAnswerAlpha) { float oldAlpha = Theme.chat_replyLinePaint.getAlpha() / 255.0f; @@ -13181,7 +13239,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } canvas.drawLine(-AndroidUtilities.dp(2), button.height + AndroidUtilities.dp(13), backgroundWidth - AndroidUtilities.dp(58), button.height + AndroidUtilities.dp(13), Theme.chat_replyLinePaint); if (pollVoteInProgress && a == pollVoteInProgressNum) { - Theme.chat_instantViewRectPaint.setColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); + Theme.chat_instantViewRectPaint.setColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outAudioSeekbarFill : Theme.key_chat_inAudioSeekbarFill)); if (animatePollAnswerAlpha) { float oldAlpha = Theme.chat_instantViewRectPaint.getAlpha() / 255.0f; Theme.chat_instantViewRectPaint.setAlpha((int) ((255 - alpha) * oldAlpha)); @@ -13190,9 +13248,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.drawArc(rect, voteRadOffset, voteCurrentCircleLength, false, Theme.chat_instantViewRectPaint); } else { if (currentMessageObject.isOutOwner()) { - Theme.chat_instantViewRectPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outMenuSelected : Theme.key_chat_outMenu)); + Theme.chat_instantViewRectPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outMenuSelected : Theme.key_chat_outMenu)); } else { - Theme.chat_instantViewRectPaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inMenuSelected : Theme.key_chat_inMenu)); + Theme.chat_instantViewRectPaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inMenuSelected : Theme.key_chat_inMenu)); } if (animatePollAnswerAlpha) { float oldAlpha = Theme.chat_instantViewRectPaint.getAlpha() / 255.0f; @@ -13203,7 +13261,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int size = AndroidUtilities.dp(8.5f); String key = Theme.key_checkboxCheck; if (currentMessageObject.isOutOwner()) { - if (Theme.getColor(key) == 0xffffffff) { + if (getThemedColor(key) == 0xffffffff) { key = Theme.key_chat_outBubble; } } @@ -13222,9 +13280,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int textX = getCurrentBackgroundLeft() + AndroidUtilities.dp(currentMessageObject.isOutOwner() || mediaBackground || drawPinnedBottom ? 2 : 8); int instantY = lastVoteY + AndroidUtilities.dp(13); if (currentMessageObject.isOutOwner()) { - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_outPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_outPreviewInstantText)); } else { - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); } instantButtonRect.set(textX, instantY, textX + instantWidth, instantY + AndroidUtilities.dp(44)); @@ -13251,11 +13309,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate canvas.restore(); } else if (currentMessageObject.type == 12) { if (currentMessageObject.isOutOwner()) { - Theme.chat_contactNamePaint.setColor(Theme.getColor(Theme.key_chat_outContactNameText)); - Theme.chat_contactPhonePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_outContactPhoneSelectedText : Theme.key_chat_outContactPhoneText)); + Theme.chat_contactNamePaint.setColor(getThemedColor(Theme.key_chat_outContactNameText)); + Theme.chat_contactPhonePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_outContactPhoneSelectedText : Theme.key_chat_outContactPhoneText)); } else { - Theme.chat_contactNamePaint.setColor(Theme.getColor(Theme.key_chat_inContactNameText)); - Theme.chat_contactPhonePaint.setColor(Theme.getColor(isDrawSelectionBackground() ? Theme.key_chat_inContactPhoneSelectedText : Theme.key_chat_inContactPhoneText)); + Theme.chat_contactNamePaint.setColor(getThemedColor(Theme.key_chat_inContactNameText)); + Theme.chat_contactPhonePaint.setColor(getThemedColor(isDrawSelectionBackground() ? Theme.key_chat_inContactPhoneSelectedText : Theme.key_chat_inContactPhoneText)); } if (titleLayout != null) { canvas.save(); @@ -13272,7 +13330,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate Drawable menuDrawable; if (currentMessageObject.isOutOwner()) { - menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgOutMenuSelectedDrawable : Theme.chat_msgOutMenuDrawable; + menuDrawable = getThemedDrawable(isDrawSelectionBackground() ? Theme.key_drawable_msgOutMenuSelected : Theme.key_drawable_msgOutMenu); } else { menuDrawable = isDrawSelectionBackground() ? Theme.chat_msgInMenuSelectedDrawable : Theme.chat_msgInMenuDrawable; } @@ -13284,11 +13342,11 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate int instantY = currentBackgroundDrawable.getBounds().bottom - AndroidUtilities.dp(36 + 28); Paint backPaint = Theme.chat_instantViewRectPaint; if (currentMessageObject.isOutOwner()) { - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_outPreviewInstantText)); - backPaint.setColor(Theme.getColor(Theme.key_chat_outPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_outPreviewInstantText)); + backPaint.setColor(getThemedColor(Theme.key_chat_outPreviewInstantText)); } else { - Theme.chat_instantViewPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); - backPaint.setColor(Theme.getColor(Theme.key_chat_inPreviewInstantText)); + Theme.chat_instantViewPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); + backPaint.setColor(getThemedColor(Theme.key_chat_inPreviewInstantText)); } instantButtonRect.set(textX, instantY, textX + instantWidth, instantY + AndroidUtilities.dp(36)); @@ -13373,17 +13431,17 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate y1 = layoutHeight + transitionParams.deltaBottom - AndroidUtilities.dp(28 - (drawPinnedBottom ? 2 : 0)); rect.set(x1, y1, x1 + timeWidthAudio + AndroidUtilities.dp(8 + 12 + 2), y1 + AndroidUtilities.dp(17)); - int oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); - Theme.chat_actionBackgroundPaint.setAlpha((int) (oldAlpha * timeAlpha)); - Theme.applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); - canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + int oldAlpha = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha * timeAlpha)); + applyServiceShaderMatrix(getMeasuredWidth(), backgroundHeight, getX(), viewTop); + canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { int oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * timeAlpha)); canvas.drawRoundRect(rect, AndroidUtilities.dp(6), AndroidUtilities.dp(6), Theme.chat_actionBackgroundGradientDarkenPaint); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2); } - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha); boolean showPlayingDrawable = playing || !currentMessageObject.isContentUnread(); @@ -13414,7 +13472,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate float cy = y1 + AndroidUtilities.dp(8.3f); canvas.save(); canvas.scale((1f - roundPlayingDrawableProgress), (1f - roundPlayingDrawableProgress), cx, cy); - Theme.chat_docBackPaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + Theme.chat_docBackPaint.setColor(getThemedColor(Theme.key_chat_serviceText)); Theme.chat_docBackPaint.setAlpha((int) (255 * timeAlpha * (1f - roundPlayingDrawableProgress))); canvas.drawCircle(cx, cy, AndroidUtilities.dp(3), Theme.chat_docBackPaint); canvas.restore(); @@ -14900,7 +14958,6 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate boolean drawCheck2 = false; boolean drawClock = false; boolean drawError = false; - boolean isBroadcast = (int) (currentMessageObject.getDialogId() >> 32) == 1; if (currentMessageObject.isSending() || currentMessageObject.isEditing()) { drawCheck2 = false; @@ -14920,7 +14977,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate drawClock = false; drawError = false; } - return (drawCheck1 ? 1 : 0) | (drawCheck2 ? 2 : 0) | (drawClock ? 4 : 0) | (drawError ? 8 : 0) | (isBroadcast ? 16 : 0); + return (drawCheck1 ? 1 : 0) | (drawCheck2 ? 2 : 0) | (drawClock ? 4 : 0) | (drawError ? 8 : 0); } else { boolean drawClock = currentMessageObject.isSending() || currentMessageObject.isEditing(); boolean drawError = currentMessageObject.isSendError(); @@ -14929,4 +14986,23 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Drawable getThemedDrawable(String key) { + Drawable drawable = resourcesProvider != null ? resourcesProvider.getDrawable(key) : null; + return drawable != null ? drawable : Theme.getThemeDrawable(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } + + private boolean hasGradientService() { + return resourcesProvider != null ? resourcesProvider.hasGradientService() : Theme.hasGradientService(); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatUnreadCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatUnreadCell.java index 5b939673d..1d5918e30 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatUnreadCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatUnreadCell.java @@ -27,25 +27,27 @@ public class ChatUnreadCell extends FrameLayout { private TextView textView; private ImageView imageView; private FrameLayout backgroundLayout; + private Theme.ResourcesProvider resourcesProvider; - public ChatUnreadCell(Context context) { + public ChatUnreadCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; backgroundLayout = new FrameLayout(context); backgroundLayout.setBackgroundResource(R.drawable.newmsg_divider); - backgroundLayout.getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_unreadMessagesStartBackground), PorterDuff.Mode.MULTIPLY)); + backgroundLayout.getBackground().setColorFilter(new PorterDuffColorFilter(getColor(Theme.key_chat_unreadMessagesStartBackground), PorterDuff.Mode.MULTIPLY)); addView(backgroundLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 27, Gravity.LEFT | Gravity.TOP, 0, 7, 0, 0)); imageView = new ImageView(context); imageView.setImageResource(R.drawable.ic_ab_new); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_unreadMessagesStartArrowIcon), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getColor(Theme.key_chat_unreadMessagesStartArrowIcon), PorterDuff.Mode.MULTIPLY)); imageView.setPadding(0, AndroidUtilities.dp(2), 0, 0); backgroundLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 10, 0)); textView = new TextView(context); textView.setPadding(0, 0, 0, AndroidUtilities.dp(1)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(Theme.getColor(Theme.key_chat_unreadMessagesStartText)); + textView.setTextColor(getColor(Theme.key_chat_unreadMessagesStartText)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); } @@ -70,4 +72,9 @@ public class ChatUnreadCell extends FrameLayout { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY)); } + + private int getColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxCell.java index 9920634f1..f76be77c6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxCell.java @@ -27,6 +27,9 @@ import org.telegram.ui.Components.LayoutHelper; public class CheckBoxCell extends FrameLayout { + public final static int TYPE_CHECK_BOX_ROUND = 4; + + private final Theme.ResourcesProvider resourcesProvider; private TextView textView; private TextView valueTextView; private View checkBox; @@ -35,24 +38,26 @@ public class CheckBoxCell extends FrameLayout { private boolean needDivider; private boolean isMultiline; private int currentType; - private int checkBoxSize = 18; - public final static int TYPE_CHECK_BOX_ROUND = 4; - public CheckBoxCell(Context context, int type) { - this(context, type, 17); + this(context, type, 17, null); } - public CheckBoxCell(Context context, int type, int padding) { + public CheckBoxCell(Context context, int type, Theme.ResourcesProvider resourcesProvider) { + this(context, type, 17, resourcesProvider); + } + + public CheckBoxCell(Context context, int type, int padding, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; currentType = type; textView = new TextView(context); - textView.setTextColor(Theme.getColor(type == 1 || type == 5 ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); - textView.setLinkTextColor(Theme.getColor(type == 1 || type == 5 ? Theme.key_dialogTextLink : Theme.key_windowBackgroundWhiteLinkText)); - textView.setTag(Theme.getColor(type == 1 || type == 5 ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); + textView.setTextColor(getThemedColor(type == 1 || type == 5 ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); + textView.setLinkTextColor(getThemedColor(type == 1 || type == 5 ? Theme.key_dialogTextLink : Theme.key_windowBackgroundWhiteLinkText)); + textView.setTag(getThemedColor(type == 1 || type == 5 ? Theme.key_dialogTextBlack : Theme.key_windowBackgroundWhiteBlackText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setLines(1); textView.setMaxLines(1); @@ -73,7 +78,7 @@ public class CheckBoxCell extends FrameLayout { } valueTextView = new TextView(context); - valueTextView.setTextColor(Theme.getColor(type == 1 || type == 5 ? Theme.key_dialogTextBlue : Theme.key_windowBackgroundWhiteValueText)); + valueTextView.setTextColor(getThemedColor(type == 1 || type == 5 ? Theme.key_dialogTextBlue : Theme.key_windowBackgroundWhiteValueText)); valueTextView.setTag(type == 1 || type == 5 ? Theme.key_dialogTextBlue : Theme.key_windowBackgroundWhiteValueText); valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); valueTextView.setLines(1); @@ -84,14 +89,14 @@ public class CheckBoxCell extends FrameLayout { addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, padding, 0, padding, 0)); if (type == TYPE_CHECK_BOX_ROUND) { - checkBox = checkBoxRound = new CheckBox2(context, 21); + checkBox = checkBoxRound = new CheckBox2(context, 21, resourcesProvider); checkBoxRound.setDrawUnchecked(true); checkBoxRound.setChecked(true, false); checkBoxRound.setDrawBackgroundAsArc(10); checkBoxSize = 21; addView(checkBox, LayoutHelper.createFrame(checkBoxSize, checkBoxSize, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : padding), 16, (LocaleController.isRTL ? padding : 0), 0)); } else { - checkBox = checkBoxSquare = new CheckBoxSquare(context, type == 1 || type == 5); + checkBox = checkBoxSquare = new CheckBoxSquare(context, type == 1 || type == 5, resourcesProvider); checkBoxSize = 18; if (type == 5) { addView(checkBox, LayoutHelper.createFrame(checkBoxSize, checkBoxSize, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, (LocaleController.isRTL ? 0 : padding), 0, (LocaleController.isRTL ? padding : 0), 0)); @@ -234,4 +239,9 @@ public class CheckBoxCell extends FrameLayout { info.setCheckable(true); info.setChecked(isChecked()); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxUserCell.java index 11dd842de..f6e2010a9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/CheckBoxUserCell.java @@ -55,7 +55,7 @@ public class CheckBoxUserCell extends FrameLayout { imageView.setRoundRadius(AndroidUtilities.dp(36)); addView(imageView, LayoutHelper.createFrame(36, 36, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 48, 7, 48, 0)); - checkBox = new CheckBoxSquare(context, alert); + checkBox = new CheckBoxSquare(context, alert, null); addView(checkBox, LayoutHelper.createFrame(18, 18, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 21), 16, (LocaleController.isRTL ? 21 : 0), 0)); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java index f5343de38..19019686b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/DialogCell.java @@ -35,6 +35,7 @@ import android.view.animation.OvershootInterpolator; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.ChatThemeController; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.MediaDataController; @@ -67,7 +68,7 @@ import org.telegram.ui.Components.StaticLayoutEx; import org.telegram.ui.Components.StatusDrawable; import org.telegram.ui.Components.TypefaceSpan; import org.telegram.ui.DialogsActivity; -import org.telegram.ui.SwipeGestureSettingsView; +import org.telegram.ui.Components.SwipeGestureSettingsView; import java.util.ArrayList; @@ -308,11 +309,14 @@ public class DialogCell extends BaseCell { } public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines) { - this(fragment, context, needCheck, forceThreeLines, UserConfig.selectedAccount); + this(fragment, context, needCheck, forceThreeLines, UserConfig.selectedAccount, null); } - public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines, int account) { + private final Theme.ResourcesProvider resourcesProvider; + + public DialogCell(DialogsActivity fragment, Context context, boolean needCheck, boolean forceThreeLines, int account, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; parentFragment = fragment; Theme.createDialogsResources(context); avatarImage.setRoundRadius(AndroidUtilities.dp(28)); @@ -356,6 +360,7 @@ public class DialogCell extends BaseCell { update(0, false); checkOnline(); checkGroupCall(); + checkChatTheme(); } public void setDialogIndex(int i) { @@ -368,6 +373,7 @@ public class DialogCell extends BaseCell { update(0); checkOnline(); checkGroupCall(); + checkChatTheme(); } private void checkOnline() { @@ -401,6 +407,13 @@ public class DialogCell extends BaseCell { chatCallProgress = hasCall ? 1.0f : 0.0f; } + private void checkChatTheme() { + if (message != null && message.messageOwner != null && message.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme && lastUnreadState) { + TLRPC.TL_messageActionSetChatTheme setThemeAction = (TLRPC.TL_messageActionSetChatTheme) message.messageOwner.action; + ChatThemeController.getInstance(currentAccount).setDialogTheme(currentDialogId, setThemeAction.emoticon, false); + } + } + public void setDialog(long dialog_id, MessageObject messageObject, int date, boolean useMe) { if (currentDialogId != dialog_id) { lastStatusDrawableParams = -1; @@ -523,17 +536,16 @@ public class DialogCell extends BaseCell { TLRPC.Dialog dialog = dialogs.get(a); TLRPC.User currentUser = null; TLRPC.Chat currentChat = null; - if (DialogObject.isSecretDialogId(dialog.id)) { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat((int) (dialog.id >> 32)); + if (DialogObject.isEncryptedDialog(dialog.id)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialog.id)); if (encryptedChat != null) { currentUser = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); } } else { - int lowerId = (int) dialog.id; - if (lowerId > 0) { - currentUser = MessagesController.getInstance(currentAccount).getUser(lowerId); + if (DialogObject.isUserDialog(dialog.id)) { + currentUser = MessagesController.getInstance(currentAccount).getUser(dialog.id); } else { - currentChat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + currentChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); } } String title; @@ -555,7 +567,7 @@ public class DialogCell extends BaseCell { int boldEnd = boldStart + title.length(); builder.append(title); if (dialog.unread_count > 0) { - builder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_chats_nameArchived)), boldStart, boldEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider)), boldStart, boldEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (builder.length() > 150) { break; @@ -573,7 +585,7 @@ public class DialogCell extends BaseCell { Theme.dialogs_messagePaint[1].setTextSize(AndroidUtilities.dp(15)); Theme.dialogs_messagePrintingPaint[1].setTextSize(AndroidUtilities.dp(15)); - Theme.dialogs_messagePaint[1].setColor(Theme.dialogs_messagePaint[1].linkColor = Theme.getColor(Theme.key_chats_message_threeLines)); + Theme.dialogs_messagePaint[1].setColor(Theme.dialogs_messagePaint[1].linkColor = Theme.getColor(Theme.key_chats_message_threeLines, resourcesProvider)); paintIndex = 1; thumbSize = 18; } else { @@ -582,7 +594,7 @@ public class DialogCell extends BaseCell { Theme.dialogs_messagePaint[0].setTextSize(AndroidUtilities.dp(16)); Theme.dialogs_messagePrintingPaint[0].setTextSize(AndroidUtilities.dp(16)); - Theme.dialogs_messagePaint[0].setColor(Theme.dialogs_messagePaint[0].linkColor = Theme.getColor(Theme.key_chats_message)); + Theme.dialogs_messagePaint[0].setColor(Theme.dialogs_messagePaint[0].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider)); paintIndex = 0; thumbSize = 19; } @@ -706,7 +718,7 @@ public class DialogCell extends BaseCell { if (customDialog.isMedia) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, message.messageText)); - stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { String mess = customDialog.message; if (mess.length() > 150) { @@ -892,13 +904,14 @@ public class DialogCell extends BaseCell { } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); + printingString = TextUtils.replace(printingString, new String[]{"..."}, new String[]{""}); if (printingStringType == 5) { printigStingReplaceIndex = printingString.toString().indexOf("**oo**"); } - if (printigStingReplaceIndex > 0) { - spannableStringBuilder.append(TextUtils.replace(printingString, new String[]{"..."}, new String[]{""})).setSpan(new FixedWidthSpan(Theme.getChatStatusDrawable(printingStringType).getIntrinsicWidth()), printigStingReplaceIndex, printigStingReplaceIndex + 6, 0); + if (printigStingReplaceIndex >= 0) { + spannableStringBuilder.append(printingString).setSpan(new FixedWidthSpan(Theme.getChatStatusDrawable(printingStringType).getIntrinsicWidth()), printigStingReplaceIndex, printigStingReplaceIndex + 6, 0); } else { - spannableStringBuilder.append(" ").append(TextUtils.replace(printingString, new String[]{"..."}, new String[]{""})).setSpan(new FixedWidthSpan(startPadding), 0, 1, 0); + spannableStringBuilder.append(" ").append(printingString).setSpan(new FixedWidthSpan(startPadding), 0, 1, 0); } messageString = spannableStringBuilder; @@ -914,7 +927,7 @@ public class DialogCell extends BaseCell { messageString = ""; } else { SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(messageNameString); - stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft), 0, messageNameString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); messageString = stringBuilder; } } else { @@ -924,7 +937,7 @@ public class DialogCell extends BaseCell { } SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, mess.replace('\n', ' '), messageNameString)); if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout) { - stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_draft, resourcesProvider), 0, messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(20), false); } @@ -961,8 +974,8 @@ public class DialogCell extends BaseCell { String restrictionReason = MessagesController.getRestrictionReason(message.messageOwner.restriction_reason); TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; - int fromId = message.getFromChatId(); - if (fromId > 0) { + long fromId = message.getFromChatId(); + if (DialogObject.isUserDialog(fromId)) { fromUser = MessagesController.getInstance(currentAccount).getUser(fromId); } else { fromChat = MessagesController.getInstance(currentAccount).getChat(-fromId); @@ -1027,8 +1040,6 @@ public class DialogCell extends BaseCell { } else { messageNameString = UserObject.getFirstName(fromUser).replace("\n", ""); } - } else if (fromChat != null) { - messageNameString = fromChat.title.replace("\n", ""); } else { messageNameString = "DELETED"; } @@ -1086,7 +1097,7 @@ public class DialogCell extends BaseCell { innerMessage = innerMessage.replace('\n', ' '); stringBuilder = SpannableStringBuilder.valueOf(String.format(messageFormat, innerMessage, messageNameString)); try { - stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage), hasNameInMessage ? messageNameString.length() + 2 : 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_attachMessage, resourcesProvider), hasNameInMessage ? messageNameString.length() + 2 : 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception e) { FileLog.e(e); } @@ -1119,7 +1130,7 @@ public class DialogCell extends BaseCell { int thumbInsertIndex = 0; if (!useForceThreeLines && !SharedConfig.useThreeLinesLayout || currentDialogFolderId != 0 && stringBuilder.length() > 0) { try { - stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage), 0, thumbInsertIndex = messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + stringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_chats_nameMessage, resourcesProvider), 0, thumbInsertIndex = messageNameString.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); offsetName = thumbInsertIndex; } catch (Exception e) { FileLog.e(e); @@ -1127,7 +1138,7 @@ public class DialogCell extends BaseCell { } messageString = Emoji.replaceEmoji(stringBuilder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(20), false); if (message.hasHighlightedWords()) { - CharSequence messageH = AndroidUtilities.highlightText(messageString, message.highlightedWords); + CharSequence messageH = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); if (messageH != null) { messageString = messageH; } @@ -1203,7 +1214,7 @@ public class DialogCell extends BaseCell { } else { messageString = message.messageText; } - AndroidUtilities.highlightText(messageString, message.highlightedWords); + AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); } if (message.messageOwner.media != null && !message.isMediaEmpty()) { currentMessagePaint = Theme.dialogs_messagePrintingPaint[paintIndex]; @@ -1232,7 +1243,7 @@ public class DialogCell extends BaseCell { builder.setSpan(new FixedWidthSpan(AndroidUtilities.dp(thumbSize + 6)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Emoji.replaceEmoji(builder, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(17), false); if (message.hasHighlightedWords()) { - CharSequence s = AndroidUtilities.highlightText(builder, message.highlightedWords); + CharSequence s = AndroidUtilities.highlightText(builder, message.highlightedWords, resourcesProvider); if (s != null) { messageString = s; } @@ -1460,7 +1471,7 @@ public class DialogCell extends BaseCell { try { CharSequence nameStringFinal = TextUtils.ellipsize(nameString.replace('\n', ' '), Theme.dialogs_namePaint[paintIndex], nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END); if (message != null && message.hasHighlightedWords()) { - CharSequence s = AndroidUtilities.highlightText(nameStringFinal, message.highlightedWords); + CharSequence s = AndroidUtilities.highlightText(nameStringFinal, message.highlightedWords, resourcesProvider); if (s != null) { nameStringFinal = s; } @@ -1597,7 +1608,7 @@ public class DialogCell extends BaseCell { } messageString = Emoji.replaceEmoji(mess, Theme.dialogs_messagePaint[paintIndex].getFontMetricsInt(), AndroidUtilities.dp(17), false); if (message != null) { - CharSequence s = AndroidUtilities.highlightText(messageString, message.highlightedWords); + CharSequence s = AndroidUtilities.highlightText(messageString, message.highlightedWords, resourcesProvider); if (s != null) { messageString = s; } @@ -1607,7 +1618,7 @@ public class DialogCell extends BaseCell { if ((useForceThreeLines || SharedConfig.useThreeLinesLayout) && messageNameString != null && (currentDialogFolderId == 0 || currentDialogFolderDialogsCount == 1)) { try { if (message != null && message.hasHighlightedWords()) { - CharSequence s = AndroidUtilities.highlightText(messageNameString, message.highlightedWords); + CharSequence s = AndroidUtilities.highlightText(messageNameString, message.highlightedWords, resourcesProvider); if (s != null) { messageNameString = s; } @@ -1654,6 +1665,7 @@ public class DialogCell extends BaseCell { messageLayout = new StaticLayout(messageStringFinal, currentMessagePaint, messageWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } } catch (Exception e) { + messageLayout = null; FileLog.e(e); } @@ -1750,7 +1762,7 @@ public class DialogCell extends BaseCell { } if (messageLayout != null && printingStringType >= 0) { float x1, x2; - if (printigStingReplaceIndex >= 0){ + if (printigStingReplaceIndex >= 0 && printigStingReplaceIndex + 1 < messageLayout.getText().length() ){ x1 = messageLayout.getPrimaryHorizontal(printigStingReplaceIndex); x2 = messageLayout.getPrimaryHorizontal(printigStingReplaceIndex + 1); } else { @@ -1903,6 +1915,7 @@ public class DialogCell extends BaseCell { } checkOnline(); checkGroupCall(); + checkChatTheme(); } } } @@ -2109,25 +2122,21 @@ public class DialogCell extends BaseCell { } if (dialogId != 0) { - int lower_id = (int) dialogId; - int high_id = (int) (dialogId >> 32); - if (lower_id != 0) { - if (lower_id < 0) { - chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (!isDialogCell && chat != null && chat.migrated_to != null) { - TLRPC.Chat chat2 = MessagesController.getInstance(currentAccount).getChat(chat.migrated_to.channel_id); - if (chat2 != null) { - chat = chat2; - } - } - } else { - user = MessagesController.getInstance(currentAccount).getUser(lower_id); - } - } else { - encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialogId)) { + encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (encryptedChat != null) { user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); } + } else if (DialogObject.isUserDialog(dialogId)) { + user = MessagesController.getInstance(currentAccount).getUser(dialogId); + } else { + chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); + if (!isDialogCell && chat != null && chat.migrated_to != null) { + TLRPC.Chat chat2 = MessagesController.getInstance(currentAccount).getChat(chat.migrated_to.channel_id); + if (chat2 != null) { + chat = chat2; + } + } } if (useMeForMyMessages && user != null && message.isOutOwner()) { user = MessagesController.getInstance(currentAccount).getUser(UserConfig.getInstance(currentAccount).clientUserId); @@ -2302,25 +2311,25 @@ public class DialogCell extends BaseCell { int swipeMessageStringId; if (currentDialogFolderId != 0) { if (archiveHidden) { - backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground); - revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground); + backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); + revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); swipeMessage = LocaleController.getString("UnhideFromTop", swipeMessageStringId = R.string.UnhideFromTop); translationDrawable = Theme.dialogs_unpinArchiveDrawable; } else { - backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground); - revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground); + backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); + revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); swipeMessage = LocaleController.getString("HideOnTop", swipeMessageStringId = R.string.HideOnTop); translationDrawable = Theme.dialogs_pinArchiveDrawable; } } else { if (promoDialog) { - backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground); - revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground); + backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); + revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); swipeMessage = LocaleController.getString("PsaHide", swipeMessageStringId = R.string.PsaHide); translationDrawable = Theme.dialogs_hidePsaDrawable; } else if (folderId == 0) { - backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground); - revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground); + backgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); + revealBackgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_MUTE) { if (dialogMuted) { swipeMessage = LocaleController.getString("SwipeUnmute", swipeMessageStringId = R.string.SwipeUnmute); @@ -2331,7 +2340,7 @@ public class DialogCell extends BaseCell { } } else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_DELETE) { swipeMessage = LocaleController.getString("SwipeDeleteChat", swipeMessageStringId = R.string.SwipeDeleteChat); - backgroundColor = Theme.getColor(Theme.key_dialogSwipeRemove); + backgroundColor = Theme.getColor(Theme.key_dialogSwipeRemove, resourcesProvider); translationDrawable = Theme.dialogs_swipeDeleteDrawable; } else if (SharedConfig.getChatSwipeAction(currentAccount) == SwipeGestureSettingsView.SWIPE_GESTURE_READ) { if (unreadCount > 0 || markUnread) { @@ -2354,8 +2363,8 @@ public class DialogCell extends BaseCell { translationDrawable = Theme.dialogs_archiveDrawable; } } else { - backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground); - revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground); + backgroundColor = Theme.getColor(Theme.key_chats_archivePinBackground, resourcesProvider); + revealBackgroundColor = Theme.getColor(Theme.key_chats_archiveBackground, resourcesProvider); swipeMessage = LocaleController.getString("Unarchive", swipeMessageStringId = R.string.Unarchive); translationDrawable = Theme.dialogs_unarchiveDrawable; } @@ -2477,25 +2486,25 @@ public class DialogCell extends BaseCell { canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_tabletSeletedPaint); } if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) { - Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay), archiveBackgroundProgress, 1.0f)); + Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f)); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint); } else if (drawPin || drawPinBackground) { - Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay)); + Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider)); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint); } if (translationX != 0 || cornerProgress != 0.0f) { canvas.save(); - Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); rect.set(getMeasuredWidth() - AndroidUtilities.dp(64), 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(8) * cornerProgress, AndroidUtilities.dp(8) * cornerProgress, Theme.dialogs_pinnedPaint); if (currentDialogFolderId != 0 && (!SharedConfig.archiveHidden || archiveBackgroundProgress != 0)) { - Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay), archiveBackgroundProgress, 1.0f)); + Theme.dialogs_pinnedPaint.setColor(AndroidUtilities.getOffsetColor(0, Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider), archiveBackgroundProgress, 1.0f)); canvas.drawRoundRect(rect, AndroidUtilities.dp(8) * cornerProgress, AndroidUtilities.dp(8) * cornerProgress, Theme.dialogs_pinnedPaint); } else if (drawPin || drawPinBackground) { - Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay)); + Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_chats_pinnedOverlay, resourcesProvider)); canvas.drawRoundRect(rect, AndroidUtilities.dp(8) * cornerProgress, AndroidUtilities.dp(8) * cornerProgress, Theme.dialogs_pinnedPaint); } canvas.restore(); @@ -2533,11 +2542,11 @@ public class DialogCell extends BaseCell { if (nameLayout != null) { if (currentDialogFolderId != 0) { - Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameArchived)); + Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameArchived, resourcesProvider)); } else if (encryptedChat != null || customDialog != null && customDialog.type == 2) { - Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_secretName)); + Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_secretName, resourcesProvider)); } else { - Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_name)); + Theme.dialogs_namePaint[paintIndex].setColor(Theme.dialogs_namePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_name, resourcesProvider)); } canvas.save(); canvas.translate(nameLeft, AndroidUtilities.dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 13)); @@ -2554,11 +2563,11 @@ public class DialogCell extends BaseCell { if (messageNameLayout != null) { if (currentDialogFolderId != 0) { - Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived_threeLines)); + Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived_threeLines, resourcesProvider)); } else if (draftMessage != null) { - Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_draft)); + Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_draft, resourcesProvider)); } else { - Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessage_threeLines)); + Theme.dialogs_messageNamePaint.setColor(Theme.dialogs_messageNamePaint.linkColor = Theme.getColor(Theme.key_chats_nameMessage_threeLines, resourcesProvider)); } canvas.save(); canvas.translate(messageNameLeft, messageNameTop); @@ -2573,12 +2582,12 @@ public class DialogCell extends BaseCell { if (messageLayout != null) { if (currentDialogFolderId != 0) { if (chat != null) { - Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived)); + Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_nameMessageArchived, resourcesProvider)); } else { - Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_messageArchived)); + Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_messageArchived, resourcesProvider)); } } else { - Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_message)); + Theme.dialogs_messagePaint[paintIndex].setColor(Theme.dialogs_messagePaint[paintIndex].linkColor = Theme.getColor(Theme.key_chats_message, resourcesProvider)); } canvas.save(); canvas.translate(messageLeft, messageTop); @@ -2842,9 +2851,9 @@ public class DialogCell extends BaseCell { left = (int) (avatarImage.getImageX2() - AndroidUtilities.dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawCircle(left, top, AndroidUtilities.dp(7) * onlineProgress, Theme.dialogs_onlineCirclePaint); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle)); + Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider)); canvas.drawCircle(left, top, AndroidUtilities.dp(5) * onlineProgress, Theme.dialogs_onlineCirclePaint); if (isOnline) { if (onlineProgress < 1.0f) { @@ -2876,11 +2885,11 @@ public class DialogCell extends BaseCell { left = (int) (avatarImage.getImageX2() - AndroidUtilities.dp(useForceThreeLines || SharedConfig.useThreeLinesLayout ? 10 : 6)); } - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawCircle(left, top, AndroidUtilities.dp(11) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle)); + Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle, resourcesProvider)); canvas.drawCircle(left, top, AndroidUtilities.dp(9) * chatCallProgress * checkProgress, Theme.dialogs_onlineCirclePaint); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); float size1; float size2; @@ -2983,7 +2992,7 @@ public class DialogCell extends BaseCell { if (Build.VERSION.SDK_INT != 24) { canvas.restore(); } else { - Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + Theme.dialogs_pinnedPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhite, resourcesProvider)); canvas.drawRect(0, 0, getMeasuredWidth(), topClip * clipProgress, Theme.dialogs_pinnedPaint); canvas.drawRect(0, getMeasuredHeight() - (int) (bottomClip * clipProgress), getMeasuredWidth(), getMeasuredHeight(), Theme.dialogs_pinnedPaint); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/EmojiReplacementCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/EmojiReplacementCell.java index 5d88f4ab2..d749e2c11 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/EmojiReplacementCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/EmojiReplacementCell.java @@ -26,9 +26,11 @@ public class EmojiReplacementCell extends FrameLayout { private ImageView imageView; private String emoji; + private final Theme.ResourcesProvider resourcesProvider; - public EmojiReplacementCell(Context context) { + public EmojiReplacementCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); @@ -59,7 +61,7 @@ public class EmojiReplacementCell extends FrameLayout { Drawable background = getBackground(); if (background != null) { background.setAlpha(230); - background.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY)); + background.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY)); } } @@ -72,4 +74,9 @@ public class EmojiReplacementCell extends FrameLayout { super.invalidate(); imageView.invalidate(); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetCell2.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetCell2.java index be6f12af1..b310a1b3b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetCell2.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetCell2.java @@ -61,9 +61,11 @@ public class FeaturedStickerSetCell2 extends FrameLayout { private TLRPC.StickerSetCovered stickersSet; private boolean isInstalled; private boolean needDivider; + private final Theme.ResourcesProvider resourcesProvider; - public FeaturedStickerSetCell2(Context context) { + public FeaturedStickerSetCell2(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; textView = new TextView(context); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); @@ -318,4 +320,9 @@ public class FeaturedStickerSetCell2 extends FrameLayout { descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_featuredStickers_buttonProgress)); descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_featuredStickers_addButtonPressed)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetInfoCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetInfoCell.java index 2eaf3fcd8..bdd857c2c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetInfoCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/FeaturedStickerSetInfoCell.java @@ -68,23 +68,17 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { private int urlSearchLength; float unreadProgress; + private final Theme.ResourcesProvider resourcesProvider; - public FeaturedStickerSetInfoCell(Context context, int left) { - this(context, left, false); - } - - public FeaturedStickerSetInfoCell(Context context, int left, boolean supportRtl) { - this(context, left, supportRtl, true); - } - - public FeaturedStickerSetInfoCell(Context context, int left, boolean supportRtl, boolean canAddRemove) { + public FeaturedStickerSetInfoCell(Context context, int left, boolean supportRtl, boolean canAddRemove, Theme.ResourcesProvider resourcesProvider) { super(context); this.canAddRemove = canAddRemove; + this.resourcesProvider = resourcesProvider; FrameLayout.LayoutParams lp; nameTextView = new TextView(context); - nameTextView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelTrendingTitle)); + nameTextView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelTrendingTitle)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setEllipsize(TextUtils.TruncateAt.END); @@ -97,7 +91,7 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { addView(nameTextView, lp); infoTextView = new TextView(context); - infoTextView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelTrendingDescription)); + infoTextView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelTrendingDescription)); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); infoTextView.setEllipsize(TextUtils.TruncateAt.END); infoTextView.setSingleLine(true); @@ -110,7 +104,7 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { if (canAddRemove) { addButton = new ProgressButton(context); - addButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + addButton.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); addButton.setText(LocaleController.getString("Add", R.string.Add)); if (supportRtl) { lp = LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, 28, Gravity.TOP | Gravity.END, 0, 16, 14, 0); @@ -121,7 +115,7 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { delButton = new TextView(context); delButton.setGravity(Gravity.CENTER); - delButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_removeButtonText)); + delButton.setTextColor(getThemedColor(Theme.key_featuredStickers_removeButtonText)); delButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); delButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); delButton.setText(LocaleController.getString("StickersRemove", R.string.StickersRemove)); @@ -263,7 +257,7 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { if (stickerSetNameSearchLength != 0) { SpannableStringBuilder builder = new SpannableStringBuilder(set.set.title); try { - builder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)), stickerSetNameSearchIndex, stickerSetNameSearchIndex + stickerSetNameSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_windowBackgroundWhiteBlueText4)), stickerSetNameSearchIndex, stickerSetNameSearchIndex + stickerSetNameSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { } nameTextView.setText(builder); @@ -280,8 +274,8 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { if (url != null) { SpannableStringBuilder builder = new SpannableStringBuilder(url); try { - builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelTrendingDescription)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ColorSpanUnderline(getThemedColor(Theme.key_windowBackgroundWhiteBlueText4)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ColorSpanUnderline(getThemedColor(Theme.key_chat_emojiPanelTrendingDescription)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { } infoTextView.setText(builder); @@ -322,7 +316,7 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { invalidate(); } } - paint.setColor(Theme.getColor(Theme.key_featuredStickers_unread)); + paint.setColor(getThemedColor(Theme.key_featuredStickers_unread)); canvas.drawCircle(nameTextView.getRight() + AndroidUtilities.dp(12), AndroidUtilities.dp(20), AndroidUtilities.dp(4) * unreadProgress, paint); } if (needDivider) { @@ -332,8 +326,8 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { public void updateColors() { if (canAddRemove) { - addButton.setProgressColor(Theme.getColor(Theme.key_featuredStickers_buttonProgress)); - addButton.setBackgroundRoundRect(Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed)); + addButton.setProgressColor(getThemedColor(Theme.key_featuredStickers_buttonProgress)); + addButton.setBackgroundRoundRect(getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed)); } updateStickerSetNameSearchSpan(); updateUrlSearchSpan(); @@ -352,4 +346,9 @@ public class FeaturedStickerSetInfoCell extends FrameLayout { descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_windowBackgroundWhiteBlueText4)); descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_chat_emojiPanelTrendingDescription)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GraySectionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GraySectionCell.java index 7439f2d2a..0abe3ab1c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GraySectionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GraySectionCell.java @@ -30,16 +30,22 @@ public class GraySectionCell extends FrameLayout { private TextView textView; private TextView rightTextView; + private final Theme.ResourcesProvider resourcesProvider; public GraySectionCell(Context context) { - super(context); + this(context, null); + } - setBackgroundColor(Theme.getColor(Theme.key_graySection)); + public GraySectionCell(Context context, Theme.ResourcesProvider resourcesProvider) { + super(context); + this.resourcesProvider = resourcesProvider; + + setBackgroundColor(getThemedColor(Theme.key_graySection)); textView = new TextView(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - textView.setTextColor(Theme.getColor(Theme.key_graySectionText)); + textView.setTextColor(getThemedColor(Theme.key_graySectionText)); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 16, 0, 16, 0)); @@ -50,7 +56,7 @@ public class GraySectionCell extends FrameLayout { } }; rightTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - rightTextView.setTextColor(Theme.getColor(Theme.key_graySectionText)); + rightTextView.setTextColor(getThemedColor(Theme.key_graySectionText)); rightTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL); addView(rightTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP, 16, 0, 16, 0)); @@ -63,7 +69,7 @@ public class GraySectionCell extends FrameLayout { } public void setTextColor(String key) { - int color = Theme.getColor(key); + int color = getThemedColor(key); textView.setTextColor(color); rightTextView.setTextColor(color); } @@ -89,4 +95,9 @@ public class GraySectionCell extends FrameLayout { public TextView getTextView() { return textView; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallInvitedCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallInvitedCell.java index 5fa79657a..fe4c34721 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallInvitedCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallInvitedCell.java @@ -83,7 +83,7 @@ public class GroupCallInvitedCell extends FrameLayout { return nameTextView.getText(); } - public void setData(int account, Integer uid) { + public void setData(int account, Long uid) { currentUser = MessagesController.getInstance(account).getUser(uid); avatarDrawable.setInfo(currentUser); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallUserCell.java index fe73aa500..2794c69a1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupCallUserCell.java @@ -82,7 +82,7 @@ public class GroupCallUserCell extends FrameLayout { private boolean needDivider; private boolean currentIconGray; private int currentStatus; - private int selfId; + private long selfId; private Runnable shakeHandCallback = () -> { shakeHandDrawable.setOnFinishCallback(null, 0); @@ -446,14 +446,14 @@ public class GroupCallUserCell extends FrameLayout { return avatarImageView.getImageReceiver().hasNotThumb(); } - public void setData(AccountInstance account, TLRPC.TL_groupCallParticipant groupCallParticipant, ChatObject.Call call, int self, TLRPC.FileLocation uploadingAvatar, boolean animated) { + public void setData(AccountInstance account, TLRPC.TL_groupCallParticipant groupCallParticipant, ChatObject.Call call, long self, TLRPC.FileLocation uploadingAvatar, boolean animated) { currentCall = call; accountInstance = account; selfId = self; participant = groupCallParticipant; - int id = MessageObject.getPeerId(participant.peer); + long id = MessageObject.getPeerId(participant.peer); if (id > 0) { currentUser = accountInstance.getMessagesController().getUser(id); currentChat = null; @@ -1041,7 +1041,7 @@ public class GroupCallUserCell extends FrameLayout { } } - public int getPeerId() { + public long getPeerId() { if (participant == null) { return 0; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/HeaderCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/HeaderCell.java index 39482f5e9..4cb684855 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/HeaderCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/HeaderCell.java @@ -34,17 +34,27 @@ public class HeaderCell extends FrameLayout { private TextView textView; private SimpleTextView textView2; private int height = 40; + private final Theme.ResourcesProvider resourcesProvider; public HeaderCell(Context context) { - this(context, Theme.key_windowBackgroundWhiteBlueHeader, 21, 15, false); + this(context, Theme.key_windowBackgroundWhiteBlueHeader, 21, 15, false, null); + } + + public HeaderCell(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, Theme.key_windowBackgroundWhiteBlueHeader, 21, 15, false, resourcesProvider); } public HeaderCell(Context context, int padding) { - this(context, Theme.key_windowBackgroundWhiteBlueHeader, padding, 15, false); + this(context, Theme.key_windowBackgroundWhiteBlueHeader, padding, 15, false, null); } public HeaderCell(Context context, String textColorKey, int padding, int topMargin, boolean text2) { + this(context, textColorKey, padding, topMargin, text2, null); + } + + public HeaderCell(Context context, String textColorKey, int padding, int topMargin, boolean text2, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; textView = new TextView(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); @@ -52,7 +62,7 @@ public class HeaderCell extends FrameLayout { textView.setEllipsize(TextUtils.TruncateAt.END); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setMinHeight(AndroidUtilities.dp(height - topMargin)); - textView.setTextColor(Theme.getColor(textColorKey)); + textView.setTextColor(getThemedColor(textColorKey)); textView.setTag(textColorKey); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, padding, topMargin, padding, 0)); @@ -112,4 +122,9 @@ public class HeaderCell extends FrameLayout { } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java index 5373097b1..6d4b10164 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/HintDialogCell.java @@ -19,6 +19,7 @@ import android.widget.FrameLayout; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; @@ -41,7 +42,7 @@ public class HintDialogCell extends FrameLayout { private int lastUnreadCount; private TLRPC.User currentUser; - private long dialog_id; + private long dialogId; private int currentAccount = UserConfig.selectedAccount; float showOnlineProgress; boolean wasDraw; @@ -67,7 +68,7 @@ public class HintDialogCell extends FrameLayout { nameTextView.setEllipsize(TextUtils.TruncateAt.END); addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 6, 64, 6, 0)); - counterView = new CounterView(context); + counterView = new CounterView(context, null); addView(counterView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP,0 ,4,0,0)); counterView.setColors(Theme.key_chats_unreadCounterText, Theme.key_chats_unreadCounter); counterView.setGravity(Gravity.RIGHT); @@ -106,7 +107,7 @@ public class HintDialogCell extends FrameLayout { if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) { return; } - TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialog_id); + TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId); if (dialog != null && dialog.unread_count != 0) { if (lastUnreadCount != dialog.unread_count) { lastUnreadCount = dialog.unread_count; @@ -119,24 +120,23 @@ public class HintDialogCell extends FrameLayout { } public void update() { - int uid = (int) dialog_id; - if (uid > 0) { - currentUser = MessagesController.getInstance(currentAccount).getUser(uid); + if (DialogObject.isUserDialog(dialogId)) { + currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId); avatarDrawable.setInfo(currentUser); } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-uid); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); avatarDrawable.setInfo(chat); currentUser = null; } } - public void setDialog(int uid, boolean counter, CharSequence name) { - if (dialog_id != uid) { + public void setDialog(long uid, boolean counter, CharSequence name) { + if (dialogId != uid) { wasDraw = false; invalidate(); } - dialog_id = uid; - if (uid > 0) { + dialogId = uid; + if (DialogObject.isUserDialog(uid)) { currentUser = MessagesController.getInstance(currentAccount).getUser(uid); if (name != null) { nameTextView.setText(name); @@ -220,6 +220,6 @@ public class HintDialogCell extends FrameLayout { } public long getDialogId() { - return dialog_id; + return dialogId; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationCell.java index ea1c71317..010275708 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationCell.java @@ -32,10 +32,11 @@ public class LocationCell extends FrameLayout { private ShapeDrawable circleDrawable; private boolean needDivider; private boolean wrapContent; + private final Theme.ResourcesProvider resourcesProvider; - public LocationCell(Context context, boolean wrap) { + public LocationCell(Context context, boolean wrap, Theme.ResourcesProvider resourcesProvider) { super(context); - + this.resourcesProvider = resourcesProvider; wrapContent = wrap; imageView = new BackupImageView(context); @@ -48,7 +49,7 @@ public class LocationCell extends FrameLayout { nameTextView.setMaxLines(1); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setSingleLine(true); - nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + nameTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), (LocaleController.isRTL ? 16 : 73), 10, (LocaleController.isRTL ? 73 : 16), 0)); @@ -58,7 +59,7 @@ public class LocationCell extends FrameLayout { addressTextView.setMaxLines(1); addressTextView.setEllipsize(TextUtils.TruncateAt.END); addressTextView.setSingleLine(true); - addressTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + addressTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); addressTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); addView(addressTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), (LocaleController.isRTL ? 16 : 73), 35, (LocaleController.isRTL ? 73 : 16), 0)); } @@ -119,4 +120,9 @@ public class LocationCell extends FrameLayout { canvas.drawLine(AndroidUtilities.dp(72), getHeight() - 1, getWidth(), getHeight() - 1, Theme.dividerPaint); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationDirectionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationDirectionCell.java index 8fdce3ada..9a7d4ec63 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationDirectionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationDirectionCell.java @@ -14,21 +14,23 @@ import org.telegram.ui.Components.LayoutHelper; @SuppressWarnings("FieldCanBeLocal") public class LocationDirectionCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private SimpleTextView buttonTextView; private FrameLayout frameLayout; - public LocationDirectionCell(Context context) { + public LocationDirectionCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; frameLayout = new FrameLayout(context); - frameLayout.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + frameLayout.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP, 16, 10, 16, 0)); buttonTextView = new SimpleTextView(context); buttonTextView.setPadding(AndroidUtilities.dp(34), 0, AndroidUtilities.dp(34), 0); buttonTextView.setGravity(Gravity.CENTER); buttonTextView.setDrawablePadding(AndroidUtilities.dp(8)); - buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + buttonTextView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); buttonTextView.setTextSize(14); buttonTextView.setText(LocaleController.getString("Directions", R.string.Directions)); buttonTextView.setLeftDrawable(R.drawable.navigate); @@ -44,4 +46,9 @@ public class LocationDirectionCell extends FrameLayout { public void setOnButtonClick(OnClickListener onButtonClick) { frameLayout.setOnClickListener(onButtonClick); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationLoadingCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationLoadingCell.java index 1ac53ccd4..d11056c86 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationLoadingCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationLoadingCell.java @@ -29,20 +29,22 @@ public class LocationLoadingCell extends FrameLayout { private RadialProgressView progressBar; private TextView textView; private ImageView imageView; + private final Theme.ResourcesProvider resourcesProvider; - public LocationLoadingCell(Context context) { + public LocationLoadingCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; - progressBar = new RadialProgressView(context); + progressBar = new RadialProgressView(context, resourcesProvider); addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); imageView = new ImageView(context); imageView.setImageResource(R.drawable.location_empty); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 24)); textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + textView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); textView.setGravity(Gravity.CENTER); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); @@ -60,4 +62,9 @@ public class LocationLoadingCell extends FrameLayout { textView.setVisibility(value ? INVISIBLE : VISIBLE); imageView.setVisibility(value ? INVISIBLE : VISIBLE); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationPoweredCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationPoweredCell.java index f9c832e91..4889b1caa 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationPoweredCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/LocationPoweredCell.java @@ -28,28 +28,30 @@ public class LocationPoweredCell extends FrameLayout { private TextView textView; private TextView textView2; private ImageView imageView; + private final Theme.ResourcesProvider resourcesProvider; - public LocationPoweredCell(Context context) { + public LocationPoweredCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; LinearLayout linearLayout = new LinearLayout(context); addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); textView.setText("Powered by"); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); imageView = new ImageView(context); imageView.setImageResource(R.drawable.foursquare); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3), PorterDuff.Mode.MULTIPLY)); imageView.setPadding(0, AndroidUtilities.dp(2), 0, 0); linearLayout.addView(imageView, LayoutHelper.createLinear(35, LayoutHelper.WRAP_CONTENT)); textView2 = new TextView(context); textView2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView2.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + textView2.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); textView2.setText("Foursquare"); linearLayout.addView(textView2, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); } @@ -58,4 +60,9 @@ public class LocationPoweredCell extends FrameLayout { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(56), MeasureSpec.EXACTLY)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ManageChatUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ManageChatUserCell.java index 11c6f659c..062194a7e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ManageChatUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ManageChatUserCell.java @@ -156,7 +156,7 @@ public class ManageChatUserCell extends FrameLayout { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64) + (needDivider ? 1 : 0), MeasureSpec.EXACTLY)); } - public int getUserId() { + public long getUserId() { if (currentObject instanceof TLRPC.User) { return ((TLRPC.User) currentObject).id; } @@ -200,11 +200,11 @@ public class ManageChatUserCell extends FrameLayout { if (mask != 0) { boolean continueUpdate = false; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) { - if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { + if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { continueUpdate = true; } } - if (currentUser != null && !continueUpdate && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { + if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { int newStatus = 0; if (currentUser.status != null) { newStatus = currentUser.status.expires; @@ -273,7 +273,7 @@ public class ManageChatUserCell extends FrameLayout { if (mask != 0) { boolean continueUpdate = false; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) { - if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { + if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { continueUpdate = true; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachCameraCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachCameraCell.java index 2d12536a0..1362d9951 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachCameraCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachCameraCell.java @@ -28,12 +28,14 @@ import java.io.File; @SuppressLint("NewApi") public class PhotoAttachCameraCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private ImageView imageView; private ImageView backgroundView; private int itemSize; - public PhotoAttachCameraCell(Context context) { + public PhotoAttachCameraCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; backgroundView = new ImageView(context); backgroundView.setScaleType(ImageView.ScaleType.CENTER_CROP); @@ -71,7 +73,7 @@ public class PhotoAttachCameraCell extends FrameLayout { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogCameraIcon), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogCameraIcon), PorterDuff.Mode.MULTIPLY)); } public void updateBitmap() { @@ -88,4 +90,9 @@ public class PhotoAttachCameraCell extends FrameLayout { backgroundView.setImageResource(R.drawable.icplaceholder); } } + + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPermissionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPermissionCell.java index 3940e4025..65f2369f6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPermissionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPermissionCell.java @@ -25,26 +25,28 @@ import org.telegram.ui.Components.LayoutHelper; public class PhotoAttachPermissionCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private ImageView imageView; private ImageView imageView2; private TextView textView; private int itemSize; - public PhotoAttachPermissionCell(Context context) { + public PhotoAttachPermissionCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_attachPermissionImage), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_attachPermissionImage), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(44, 44, Gravity.CENTER, 5, 0, 0, 27)); imageView2 = new ImageView(context); imageView2.setScaleType(ImageView.ScaleType.CENTER); - imageView2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_attachPermissionMark), PorterDuff.Mode.MULTIPLY)); + imageView2.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_attachPermissionMark), PorterDuff.Mode.MULTIPLY)); addView(imageView2, LayoutHelper.createFrame(44, 44, Gravity.CENTER, 5, 0, 0, 27)); textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_chat_attachPermissionText)); + textView.setTextColor(getThemedColor(Theme.key_chat_attachPermissionText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); textView.setGravity(Gravity.CENTER); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 5, 13, 5, 0)); @@ -78,4 +80,9 @@ public class PhotoAttachPermissionCell extends FrameLayout { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(MeasureSpec.makeMeasureSpec(itemSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemSize + AndroidUtilities.dp(5), MeasureSpec.EXACTLY)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java index 75ae75ce8..e2e079774 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java @@ -72,13 +72,15 @@ public class PhotoAttachPhotoCell extends FrameLayout { private Paint backgroundPaint = new Paint(); private AnimatorSet animator; + private final Theme.ResourcesProvider resourcesProvider; public interface PhotoAttachPhotoCellDelegate { void onCheckClick(PhotoAttachPhotoCell v); } - public PhotoAttachPhotoCell(Context context) { + public PhotoAttachPhotoCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setWillNotDraw(false); @@ -113,7 +115,7 @@ public class PhotoAttachPhotoCell extends FrameLayout { videoTextView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); videoInfoContainer.addView(videoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 13, -0.7f, 0, 0)); - checkBox = new CheckBox2(context, 24); + checkBox = new CheckBox2(context, 24, resourcesProvider); checkBox.setDrawBackgroundAsArc(7); checkBox.setColor(Theme.key_chat_attachCheckBoxBackground, Theme.key_chat_attachPhotoBackground, Theme.key_chat_attachCheckBoxCheck); addView(checkBox, LayoutHelper.createFrame(26, 26, Gravity.LEFT | Gravity.TOP, 52, 4, 0, 0)); @@ -393,7 +395,7 @@ public class PhotoAttachPhotoCell extends FrameLayout { @Override protected void onDraw(Canvas canvas) { if (checkBox.isChecked() || container.getScaleX() != 1.0f || !imageView.getImageReceiver().hasNotThumb() || imageView.getImageReceiver().getCurrentAlpha() != 1.0f || photoEntry != null && PhotoViewer.isShowingImage(photoEntry.path) || searchEntry != null && PhotoViewer.isShowingImage(searchEntry.getPathToAttach())) { - backgroundPaint.setColor(Theme.getColor(Theme.key_chat_attachPhotoBackground)); + backgroundPaint.setColor(getThemedColor(Theme.key_chat_attachPhotoBackground)); canvas.drawRect(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight(), backgroundPaint); } } @@ -424,4 +426,9 @@ public class PhotoAttachPhotoCell extends FrameLayout { } return super.performAccessibilityAction(action, arguments); } + + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoEditToolCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoEditToolCell.java index 8b8354b97..23a3640d7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoEditToolCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoEditToolCell.java @@ -22,11 +22,13 @@ import android.widget.FrameLayout; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; +import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.PhotoEditorSeekBar; public class PhotoEditToolCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private TextView nameTextView; private TextView valueTextView; private PhotoEditorSeekBar seekBar; @@ -53,8 +55,9 @@ public class PhotoEditToolCell extends FrameLayout { } }; - public PhotoEditToolCell(Context context) { + public PhotoEditToolCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; nameTextView = new TextView(context); nameTextView.setGravity(Gravity.RIGHT); @@ -66,7 +69,7 @@ public class PhotoEditToolCell extends FrameLayout { addView(nameTextView, LayoutHelper.createFrame(80, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0)); valueTextView = new TextView(context); - valueTextView.setTextColor(0xff6cc3ff); + valueTextView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); valueTextView.setGravity(Gravity.RIGHT); valueTextView.setSingleLine(true); @@ -138,4 +141,9 @@ public class PhotoEditToolCell extends FrameLayout { seekBar.setMinMax(min, max); seekBar.setProgress((int) value, false); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PollEditTextCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PollEditTextCell.java index b3a7337f0..c53edccd6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PollEditTextCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PollEditTextCell.java @@ -59,7 +59,7 @@ public class PollEditTextCell extends FrameLayout { super(context); if (caption) { - textView = new EditTextCaption(context) { + textView = new EditTextCaption(context, null) { @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { InputConnection conn = super.onCreateInputConnection(outAttrs); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java index e8d526ed9..e2c9d7611 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ProfileSearchCell.java @@ -20,6 +20,7 @@ import android.view.accessibility.AccessibilityNodeInfo; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; @@ -162,28 +163,24 @@ public class ProfileSearchCell extends BaseCell { text = LocaleController.getString("NotificationsOff", R.string.NotificationsOff); } - int lower_id = (int) exception.did; - int high_id = (int) (exception.did >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); - if (user != null) { - setData(user, null, name, text, false, false); - } - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (chat != null) { - setData(chat, null, name, text, false, false); - } - } - } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(exception.did)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(exception.did)); if (encryptedChat != null) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); if (user != null) { setData(user, encryptedChat, name, text, false, false); } } + } else if (DialogObject.isUserDialog(exception.did)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(exception.did); + if (user != null) { + setData(user, null, name, text, false, false); + } + } else { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-exception.did); + if (chat != null) { + setData(chat, null, name, text, false, false); + } } } @@ -247,7 +244,7 @@ public class ProfileSearchCell extends BaseCell { if (encryptedChat != null) { drawNameLock = true; - dialog_id = ((long) encryptedChat.id) << 32; + dialog_id = DialogObject.makeEncryptedDialogId(encryptedChat.id); if (!LocaleController.isRTL) { nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); @@ -534,7 +531,7 @@ public class ProfileSearchCell extends BaseCell { if (mask != 0) { boolean continueUpdate = false; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 && user != null || (mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 && chat != null) { - if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { + if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { continueUpdate = true; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/RadioColorCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/RadioColorCell.java index 737a879d8..9ac5c1c05 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/RadioColorCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/RadioColorCell.java @@ -25,17 +25,23 @@ public class RadioColorCell extends FrameLayout { private TextView textView; private RadioButton radioButton; + private final Theme.ResourcesProvider resourcesProvider; public RadioColorCell(Context context) { + this(context, null); + } + + public RadioColorCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; radioButton = new RadioButton(context); radioButton.setSize(AndroidUtilities.dp(20)); - radioButton.setColor(Theme.getColor(Theme.key_dialogRadioBackground), Theme.getColor(Theme.key_dialogRadioBackgroundChecked)); + radioButton.setColor(getThemedColor(Theme.key_dialogRadioBackground), getThemedColor(Theme.key_dialogRadioBackgroundChecked)); addView(radioButton, LayoutHelper.createFrame(22, 22, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, (LocaleController.isRTL ? 0 : 18), 14, (LocaleController.isRTL ? 18 : 0), 0)); textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setLines(1); textView.setMaxLines(1); @@ -69,4 +75,9 @@ public class RadioColorCell extends FrameLayout { info.setCheckable(true); info.setChecked(radioButton.isChecked()); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SendLocationCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SendLocationCell.java index 329da7e7d..b52a575d3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SendLocationCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SendLocationCell.java @@ -38,6 +38,7 @@ public class SendLocationCell extends FrameLayout { private ImageView imageView; private long dialogId; private RectF rect; + private final Theme.ResourcesProvider resourcesProvider; private Runnable invalidateRunnable = new Runnable() { @Override @@ -48,17 +49,18 @@ public class SendLocationCell extends FrameLayout { } }; - public SendLocationCell(Context context, boolean live) { + public SendLocationCell(Context context, boolean live, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; imageView = new ImageView(context); imageView.setTag(live ? Theme.key_location_sendLiveLocationBackground + Theme.key_location_sendLiveLocationIcon : Theme.key_location_sendLocationBackground + Theme.key_location_sendLocationIcon); - Drawable circle = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground), Theme.getColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground)); + Drawable circle = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground), getThemedColor(live ? Theme.key_location_sendLiveLocationBackground : Theme.key_location_sendLocationBackground)); if (live) { rect = new RectF(); Drawable drawable = new ShareLocationDrawable(context, 4); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_sendLiveLocationIcon), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLiveLocationIcon), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable); combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42)); imageView.setBackgroundDrawable(combinedDrawable); @@ -66,7 +68,7 @@ public class SendLocationCell extends FrameLayout { setWillNotDraw(false); } else { Drawable drawable = getResources().getDrawable(R.drawable.pin); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable); combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42)); combinedDrawable.setIconSize(AndroidUtilities.dp(24), AndroidUtilities.dp(24)); @@ -77,14 +79,14 @@ public class SendLocationCell extends FrameLayout { titleTextView = new SimpleTextView(context); titleTextView.setTextSize(16); titleTextView.setTag(live ? Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText); - titleTextView.setTextColor(Theme.getColor(live ? Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText)); + titleTextView.setTextColor(getThemedColor(live ? Theme.key_location_sendLiveLocationText : Theme.key_location_sendLocationText)); titleTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 12, LocaleController.isRTL ? 73 : 16, 0)); accurateTextView = new SimpleTextView(context); accurateTextView.setTextSize(14); - accurateTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + accurateTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); accurateTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); addView(accurateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 16 : 73, 37, LocaleController.isRTL ? 73 : 16, 0)); } @@ -159,7 +161,7 @@ public class SendLocationCell extends FrameLayout { rect.set(getMeasuredWidth() - AndroidUtilities.dp(43), AndroidUtilities.dp(18), getMeasuredWidth() - AndroidUtilities.dp(13), AndroidUtilities.dp(48)); } - int color = Theme.getColor(Theme.key_location_liveLocationProgress); + int color = getThemedColor(Theme.key_location_liveLocationProgress); Theme.chat_radialProgress2Paint.setColor(color); Theme.chat_livePaint.setColor(color); @@ -171,4 +173,9 @@ public class SendLocationCell extends FrameLayout { canvas.drawText(text, rect.centerX() - size / 2, AndroidUtilities.dp(37), Theme.chat_livePaint); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ShareDialogCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ShareDialogCell.java index b9a65850c..c8adae174 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ShareDialogCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ShareDialogCell.java @@ -20,6 +20,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; @@ -48,13 +49,15 @@ public class ShareDialogCell extends FrameLayout { private long currentDialog; private int currentAccount = UserConfig.selectedAccount; + private final Theme.ResourcesProvider resourcesProvider; public static final int TYPE_SHARE = 0; public static final int TYPE_CALL = 1; public static final int TYPE_CREATE = 2; - public ShareDialogCell(Context context, int type) { + public ShareDialogCell(Context context, int type, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setWillNotDraw(false); currentType = type; @@ -68,7 +71,7 @@ public class ShareDialogCell extends FrameLayout { } nameTextView = new TextView(context); - nameTextView.setTextColor(Theme.getColor(type == TYPE_CALL ? Theme.key_voipgroup_nameText : Theme.key_dialogTextBlack)); + nameTextView.setTextColor(getThemedColor(type == TYPE_CALL ? Theme.key_voipgroup_nameText : Theme.key_dialogTextBlack)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); nameTextView.setMaxLines(2); nameTextView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); @@ -76,7 +79,7 @@ public class ShareDialogCell extends FrameLayout { nameTextView.setEllipsize(TextUtils.TruncateAt.END); addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 6, currentType == TYPE_CREATE ? 58 : 66, 6, 0)); - checkBox = new CheckBox2(context, 21); + checkBox = new CheckBox2(context, 21, resourcesProvider); checkBox.setColor(Theme.key_dialogRoundCheckBox, type == TYPE_CALL ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground, Theme.key_dialogRoundCheckBoxCheck); checkBox.setDrawUnchecked(false); checkBox.setDrawBackgroundAsArc(4); @@ -94,8 +97,8 @@ public class ShareDialogCell extends FrameLayout { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentType == TYPE_CREATE ? 95 : 103), MeasureSpec.EXACTLY)); } - public void setDialog(int uid, boolean checked, CharSequence name) { - if (uid > 0) { + public void setDialog(long uid, boolean checked, CharSequence name) { + if (DialogObject.isUserDialog(uid)) { user = MessagesController.getInstance(currentAccount).getUser(uid); avatarDrawable.setInfo(user); if (currentType != TYPE_CREATE && UserObject.isReplyUser(user)) { @@ -157,9 +160,9 @@ public class ShareDialogCell extends FrameLayout { if (isOnline || onlineProgress != 0) { int top = imageView.getBottom() - AndroidUtilities.dp(6); int left = imageView.getRight() - AndroidUtilities.dp(10); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(currentType == TYPE_CALL ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_windowBackgroundWhite)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(currentType == TYPE_CALL ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_windowBackgroundWhite)); canvas.drawCircle(left, top, AndroidUtilities.dp(7) * onlineProgress, Theme.dialogs_onlineCirclePaint); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chats_onlineCircle)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(Theme.key_chats_onlineCircle)); canvas.drawCircle(left, top, AndroidUtilities.dp(5) * onlineProgress, Theme.dialogs_onlineCirclePaint); if (isOnline) { if (onlineProgress < 1.0f) { @@ -190,8 +193,13 @@ public class ShareDialogCell extends FrameLayout { protected void onDraw(Canvas canvas) { int cx = imageView.getLeft() + imageView.getMeasuredWidth() / 2; int cy = imageView.getTop() + imageView.getMeasuredHeight() / 2; - Theme.checkboxSquare_checkPaint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBox)); + Theme.checkboxSquare_checkPaint.setColor(getThemedColor(Theme.key_dialogRoundCheckBox)); Theme.checkboxSquare_checkPaint.setAlpha((int) (checkBox.getProgress() * 255)); canvas.drawCircle(cx, cy, AndroidUtilities.dp(currentType == TYPE_CREATE ? 24 : 28), Theme.checkboxSquare_checkPaint); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedAudioCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedAudioCell.java index 398622afc..479c77c9e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedAudioCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedAudioCell.java @@ -78,23 +78,29 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F private TextPaint description2TextPaint; private TextPaint captionTextPaint; + private final Theme.ResourcesProvider resourcesProvider; public SharedAudioCell(Context context) { - this(context, VIEW_TYPE_DEFAULT); + this(context, VIEW_TYPE_DEFAULT, null); } - public SharedAudioCell(Context context, int viewType) { + public SharedAudioCell(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, VIEW_TYPE_DEFAULT, resourcesProvider); + } + + public SharedAudioCell(Context context, int viewType, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; this.viewType = viewType; setFocusable(true); - radialProgress = new RadialProgress2(this); + radialProgress = new RadialProgress2(this, resourcesProvider); radialProgress.setColors(Theme.key_chat_inLoader, Theme.key_chat_inLoaderSelected, Theme.key_chat_inMediaIcon, Theme.key_chat_inMediaIconSelected); TAG = DownloadController.getInstance(currentAccount).generateObserverTag(); setWillNotDraw(false); - checkBox = new CheckBox2(context, 22); + checkBox = new CheckBox2(context, 22, resourcesProvider); checkBox.setVisibility(INVISIBLE); checkBox.setColor(null, Theme.key_windowBackgroundWhite, Theme.key_checkboxCheck); checkBox.setDrawUnchecked(false); @@ -140,7 +146,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F } else { title = currentMessageObject.getMusicTitle().replace('\n', ' '); } - CharSequence titleH = AndroidUtilities.highlightText(title, currentMessageObject.highlightedWords); + CharSequence titleH = AndroidUtilities.highlightText(title, currentMessageObject.highlightedWords, resourcesProvider); if (titleH != null) { title = titleH; } @@ -152,7 +158,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F if (currentMessageObject.hasHighlightedWords()) { CharSequence caption = Emoji.replaceEmoji(currentMessageObject.messageOwner.message.replace("\n", " ").replaceAll(" +", " ").trim(), Theme.chat_msgTextPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); - CharSequence sequence = AndroidUtilities.highlightText(caption, currentMessageObject.highlightedWords); + CharSequence sequence = AndroidUtilities.highlightText(caption, currentMessageObject.highlightedWords, resourcesProvider); if (sequence != null) { sequence = TextUtils.ellipsize(AndroidUtilities.ellipsizeCenterEnd(sequence, currentMessageObject.highlightedWords.get(0), maxWidth, captionTextPaint, 130), captionTextPaint, maxWidth, TextUtils.TruncateAt.END); captionLayout = new StaticLayout(sequence, captionTextPaint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); @@ -166,7 +172,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F descriptionLayout = new StaticLayout(duration, paint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } else { CharSequence author = currentMessageObject.getMusicAuthor().replace('\n', ' '); - CharSequence authorH = AndroidUtilities.highlightText(author, currentMessageObject.highlightedWords); + CharSequence authorH = AndroidUtilities.highlightText(author, currentMessageObject.highlightedWords, resourcesProvider); if (authorH != null) { author = authorH; } @@ -378,7 +384,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F @Override protected void onDraw(Canvas canvas) { if (viewType == VIEW_TYPE_GLOBAL_SEARCH) { - description2TextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + description2TextPaint.setColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); } if (dateLayout != null) { canvas.save(); @@ -395,7 +401,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F } if (captionLayout != null) { - captionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + captionTextPaint.setColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), captionY); captionLayout.draw(canvas); @@ -403,14 +409,14 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F } if (descriptionLayout != null) { - Theme.chat_contextResult_descriptionTextPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); + Theme.chat_contextResult_descriptionTextPaint.setColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText2)); canvas.save(); canvas.translate(AndroidUtilities.dp(LocaleController.isRTL ? 8 : AndroidUtilities.leftBaseline), descriptionY); descriptionLayout.draw(canvas); canvas.restore(); } - radialProgress.setProgressColor(Theme.getColor(buttonPressed ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); + radialProgress.setProgressColor(getThemedColor(buttonPressed ? Theme.key_chat_inAudioSelectedProgress : Theme.key_chat_inAudioProgress)); radialProgress.draw(canvas); if (needDivider) { @@ -454,7 +460,7 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F miniButtonState = -1; } if (hasMiniProgress != 0) { - radialProgress.setMiniProgressBackgroundColor(Theme.getColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); + radialProgress.setMiniProgressBackgroundColor(getThemedColor(currentMessageObject.isOutOwner() ? Theme.key_chat_outLoader : Theme.key_chat_inLoader)); boolean playing = MediaController.getInstance().isPlayingMessage(currentMessageObject); if (!playing || playing && MediaController.getInstance().isMessagePaused()) { buttonState = 0; @@ -571,5 +577,10 @@ public class SharedAudioCell extends FrameLayout implements DownloadController.F public void didReceivedNotification(int id, int account, Object... args) { updateButtonState(false, true); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java index b45fbaa7d..9e034a3f9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java @@ -88,13 +88,19 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle private SpannableStringBuilder dotSpan; private CharSequence caption; private RLottieDrawable statusDrawable; + private final Theme.ResourcesProvider resourcesProvider; public SharedDocumentCell(Context context) { this(context, VIEW_TYPE_DEFAULT); } public SharedDocumentCell(Context context, int viewType) { + this(context, viewType, null); + } + + public SharedDocumentCell(Context context, int viewType, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; this.viewType = viewType; TAG = DownloadController.getInstance(currentAccount).generateObserverTag(); @@ -107,7 +113,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle } extTextView = new TextView(context); - extTextView.setTextColor(Theme.getColor(Theme.key_files_iconText)); + extTextView.setTextColor(getThemedColor(Theme.key_files_iconText)); extTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); extTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); extTextView.setLines(1); @@ -144,7 +150,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle } nameTextView = new TextView(context); - nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + nameTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setEllipsize(TextUtils.TruncateAt.END); @@ -162,7 +168,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 16 : 72, 5, LocaleController.isRTL ? 72 : 16, 0)); rightDateTextView = new TextView(context); - rightDateTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + rightDateTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); rightDateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); if (!LocaleController.isRTL) { linearLayout.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 1f)); @@ -174,7 +180,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle nameTextView.setMaxLines(2); captionTextView = new TextView(context); - captionTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + captionTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); captionTextView.setLines(1); captionTextView.setMaxLines(1); captionTextView.setSingleLine(true); @@ -192,7 +198,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle statusImageView = new RLottieImageView(context); statusImageView.setAnimation(statusDrawable); statusImageView.setVisibility(INVISIBLE); - statusImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_sharedMedia_startStopLoadIcon), PorterDuff.Mode.MULTIPLY)); + statusImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_sharedMedia_startStopLoadIcon), PorterDuff.Mode.MULTIPLY)); if (viewType == VIEW_TYPE_PICKER) { addView(statusImageView, LayoutHelper.createFrame(14, 14, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 8 : 70, 37, LocaleController.isRTL ? 72 : 8, 0)); } else { @@ -200,7 +206,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle } dateTextView = new TextView(context); - dateTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + dateTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); dateTextView.setLines(1); dateTextView.setMaxLines(1); dateTextView.setSingleLine(true); @@ -215,7 +221,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle } progressView = new LineProgressView(context); - progressView.setProgressColor(Theme.getColor(Theme.key_sharedMedia_startStopLoadIcon)); + progressView.setProgressColor(getThemedColor(Theme.key_sharedMedia_startStopLoadIcon)); addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 72, 54, LocaleController.isRTL ? 72 : 0, 0)); checkBox = new CheckBox2(context, 21); @@ -278,8 +284,8 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle backKey = Theme.key_files_folderIconBackground; iconKey = Theme.key_files_folderIcon; } - Theme.setCombinedDrawableColor(drawable, Theme.getColor(backKey), false); - Theme.setCombinedDrawableColor(drawable, Theme.getColor(iconKey), true); + Theme.setCombinedDrawableColor(drawable, getThemedColor(backKey), false); + Theme.setCombinedDrawableColor(drawable, getThemedColor(iconKey), true); thumbImageView.setImageDrawable(drawable); } thumbImageView.setVisibility(VISIBLE); @@ -390,7 +396,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle if (name == null) { name = fileName; } - CharSequence nameH = AndroidUtilities.highlightText(name, messageObject.highlightedWords); + CharSequence nameH = AndroidUtilities.highlightText(name, messageObject.highlightedWords, resourcesProvider); if (nameH != null) { nameTextView.setText(nameH); } else { @@ -436,7 +442,7 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle if (messageObject.hasHighlightedWords() && !TextUtils.isEmpty(message.messageOwner.message)) { String str = message.messageOwner.message.replace("\n", " ").replaceAll(" +", " ").trim(); - caption = AndroidUtilities.highlightText(str, message.highlightedWords); + caption = AndroidUtilities.highlightText(str, message.highlightedWords, resourcesProvider); if (captionTextView != null) { captionTextView.setVisibility(caption == null ? View.GONE : View.VISIBLE); } @@ -639,4 +645,9 @@ public class SharedDocumentCell extends FrameLayout implements DownloadControlle info.setChecked(true); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedLinkCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedLinkCell.java index 4514ebb9e..1d19d756a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedLinkCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedLinkCell.java @@ -304,7 +304,7 @@ public class SharedLinkCell extends FrameLayout { if (title != null) { try { CharSequence titleFinal = title; - CharSequence titleH = AndroidUtilities.highlightText(titleFinal, message.highlightedWords); + CharSequence titleH = AndroidUtilities.highlightText(titleFinal, message.highlightedWords, null); if (titleH != null) { titleFinal = titleH; } @@ -350,7 +350,7 @@ public class SharedLinkCell extends FrameLayout { if (message != null && !TextUtils.isEmpty(message.messageOwner.message)) { CharSequence caption = Emoji.replaceEmoji(message.messageOwner.message.replace("\n", " ").replaceAll(" +", " ").trim(), Theme.chat_msgTextPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false); - CharSequence sequence = AndroidUtilities.highlightText(caption, message.highlightedWords); + CharSequence sequence = AndroidUtilities.highlightText(caption, message.highlightedWords, null); if (sequence != null) { sequence = TextUtils.ellipsize(AndroidUtilities.ellipsizeCenterEnd(sequence, message.highlightedWords.get(0), maxWidth, captionTextPaint, 130), captionTextPaint, maxWidth, TextUtils.TruncateAt.END); captionLayout = new StaticLayout(sequence, captionTextPaint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharingLiveLocationCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharingLiveLocationCell.java index 340de8625..80f4abd32 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharingLiveLocationCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharingLiveLocationCell.java @@ -23,6 +23,7 @@ import com.google.android.gms.maps.model.LatLng; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocationController; @@ -53,6 +54,7 @@ public class SharingLiveLocationCell extends FrameLayout { private LocationController.SharingLocationInfo currentInfo; private LocationActivity.LiveLocation liveLocation; private Location location = new Location("network"); + private final Theme.ResourcesProvider resourcesProvider; private int currentAccount = UserConfig.selectedAccount; @@ -64,8 +66,9 @@ public class SharingLiveLocationCell extends FrameLayout { } }; - public SharingLiveLocationCell(Context context, boolean distance, int padding) { + public SharingLiveLocationCell(Context context, boolean distance, int padding, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(21)); @@ -74,7 +77,7 @@ public class SharingLiveLocationCell extends FrameLayout { nameTextView = new SimpleTextView(context); nameTextView.setTextSize(16); - nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + nameTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); @@ -84,7 +87,7 @@ public class SharingLiveLocationCell extends FrameLayout { distanceTextView = new SimpleTextView(context); distanceTextView.setTextSize(14); - distanceTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + distanceTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); distanceTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); addView(distanceTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? padding : 73, 37, LocaleController.isRTL ? 73 : padding, 0)); @@ -118,16 +121,15 @@ public class SharingLiveLocationCell extends FrameLayout { String address = chatLocation.address; String name = ""; avatarDrawable = null; - int lowerId = (int) dialogId; - if (lowerId > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null) { avatarDrawable = new AvatarDrawable(user); name = UserObject.getUserName(user); avatarImageView.setForUserOrChat(user, avatarDrawable); } } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (chat != null) { avatarDrawable = new AvatarDrawable(chat); name = chat.title; @@ -142,15 +144,9 @@ public class SharingLiveLocationCell extends FrameLayout { } public void setDialog(MessageObject messageObject, Location userLocation) { - int fromId = messageObject.getFromChatId(); + long fromId = messageObject.getFromChatId(); if (messageObject.isForwarded()) { - if (messageObject.messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerChannel) { - fromId = -messageObject.messageOwner.fwd_from.from_id.channel_id; - } else if (messageObject.messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerChat) { - fromId = -messageObject.messageOwner.fwd_from.from_id.chat_id; - } else if (messageObject.messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerUser) { - fromId = messageObject.messageOwner.fwd_from.from_id.user_id; - } + fromId = MessageObject.getPeerId(messageObject.messageOwner.fwd_from.from_id); } currentAccount = messageObject.currentAccount; String address = null; @@ -162,8 +158,8 @@ public class SharingLiveLocationCell extends FrameLayout { name = messageObject.messageOwner.media.title; Drawable drawable = getResources().getDrawable(R.drawable.pin); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY)); - int color = Theme.getColor(Theme.key_location_placeLocationBackground); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_sendLocationIcon), PorterDuff.Mode.MULTIPLY)); + int color = getThemedColor(Theme.key_location_placeLocationBackground); Drawable circle = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), color, color); CombinedDrawable combinedDrawable = new CombinedDrawable(circle, drawable); combinedDrawable.setCustomSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42)); @@ -210,16 +206,15 @@ public class SharingLiveLocationCell extends FrameLayout { public void setDialog(LocationActivity.LiveLocation info, Location userLocation) { liveLocation = info; - int lower_id = info.id; - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); + if (DialogObject.isUserDialog(info.id)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(info.id); if (user != null) { avatarDrawable.setInfo(user); nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name)); avatarImageView.setForUserOrChat(user, avatarDrawable); } } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-info.id); if (chat != null) { avatarDrawable.setInfo(chat); nameTextView.setText(chat.title); @@ -243,16 +238,15 @@ public class SharingLiveLocationCell extends FrameLayout { currentInfo = info; currentAccount = info.account; avatarImageView.getImageReceiver().setCurrentAccount(currentAccount); - int lower_id = (int) info.did; - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); + if (DialogObject.isUserDialog(info.did)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(info.did); if (user != null) { avatarDrawable.setInfo(user); nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name)); avatarImageView.setForUserOrChat(user, avatarDrawable); } } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-info.did); if (chat != null) { avatarDrawable.setInfo(chat); nameTextView.setText(chat.title); @@ -288,9 +282,9 @@ public class SharingLiveLocationCell extends FrameLayout { int color; if (distanceTextView == null) { - color = Theme.getColor(Theme.key_dialog_liveLocationProgress); + color = getThemedColor(Theme.key_dialog_liveLocationProgress); } else { - color = Theme.getColor(Theme.key_location_liveLocationProgress); + color = getThemedColor(Theme.key_location_liveLocationProgress); } Theme.chat_radialProgress2Paint.setColor(color); Theme.chat_livePaint.setColor(color); @@ -303,4 +297,9 @@ public class SharingLiveLocationCell extends FrameLayout { canvas.drawText(text, rect.centerX() - size / 2, AndroidUtilities.dp(distanceTextView != null ? 37 : 31), Theme.chat_livePaint); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerSetNameCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerSetNameCell.java index 5e87bb187..8cb3455f9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerSetNameCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StickerSetNameCell.java @@ -46,20 +46,22 @@ public class StickerSetNameCell extends FrameLayout { private CharSequence url; private int urlSearchLength; + private final Theme.ResourcesProvider resourcesProvider; - public StickerSetNameCell(Context context, boolean emoji) { - this(context, emoji, false); + public StickerSetNameCell(Context context, boolean emoji, Theme.ResourcesProvider resourcesProvider) { + this(context, emoji, false, resourcesProvider); } - public StickerSetNameCell(Context context, boolean emoji, boolean supportRtl) { + public StickerSetNameCell(Context context, boolean emoji, boolean supportRtl, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; isEmoji = emoji; FrameLayout.LayoutParams lp; textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName)); + textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelStickerSetName)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setEllipsize(TextUtils.TruncateAt.END); @@ -72,7 +74,7 @@ public class StickerSetNameCell extends FrameLayout { addView(textView, lp); urlTextView = new TextView(context); - urlTextView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName)); + urlTextView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelStickerSetName)); urlTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); urlTextView.setEllipsize(TextUtils.TruncateAt.END); urlTextView.setSingleLine(true); @@ -86,7 +88,7 @@ public class StickerSetNameCell extends FrameLayout { buttonView = new ImageView(context); buttonView.setScaleType(ImageView.ScaleType.CENTER); - buttonView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameIcon), PorterDuff.Mode.MULTIPLY)); + buttonView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelStickerSetNameIcon), PorterDuff.Mode.MULTIPLY)); if (supportRtl) { lp = LayoutHelper.createFrameRelatively(24, 24, Gravity.TOP | Gravity.END, 0, 0, 16, 0); } else { @@ -106,8 +108,8 @@ public class StickerSetNameCell extends FrameLayout { if (url != null) { SpannableStringBuilder builder = new SpannableStringBuilder(url); try { - builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - builder.setSpan(new ColorSpanUnderline(Theme.getColor(Theme.key_chat_emojiPanelStickerSetName)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ColorSpanUnderline(getThemedColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), 0, urlSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ColorSpanUnderline(getThemedColor(Theme.key_chat_emojiPanelStickerSetName)), urlSearchLength, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { } urlTextView.setText(builder); @@ -149,7 +151,7 @@ public class StickerSetNameCell extends FrameLayout { if (stickerSetName != null && stickerSetNameSearchLength != 0) { SpannableStringBuilder builder = new SpannableStringBuilder(stickerSetName); try { - builder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), stickerSetNameSearchIndex, stickerSetNameSearchIndex + stickerSetNameSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + builder.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_chat_emojiPanelStickerSetNameHighlight)), stickerSetNameSearchIndex, stickerSetNameSearchIndex + stickerSetNameSearchLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (Exception ignore) { } textView.setText(Emoji.replaceEmoji(builder, textView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false)); @@ -195,4 +197,9 @@ public class StickerSetNameCell extends FrameLayout { descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_chat_emojiPanelStickerSetNameHighlight)); descriptions.add(new ThemeDescription(null, 0, null, null, null, delegate, Theme.key_chat_emojiPanelStickerSetName)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java index a3c8f436b..583d7c54c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextInfoPrivacyCell.java @@ -38,13 +38,23 @@ public class TextInfoPrivacyCell extends FrameLayout { private int fixedSize; private CharSequence text; + private final Theme.ResourcesProvider resourcesProvider; public TextInfoPrivacyCell(Context context) { - this(context, 21); + this(context, 21, null); + } + + public TextInfoPrivacyCell(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, 21, resourcesProvider); } public TextInfoPrivacyCell(Context context, int padding) { + this(context, padding, null); + } + + public TextInfoPrivacyCell(Context context, int padding, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; textView = new TextView(context) { @Override @@ -58,8 +68,8 @@ public class TextInfoPrivacyCell extends FrameLayout { textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); textView.setPadding(0, AndroidUtilities.dp(10), 0, AndroidUtilities.dp(17)); textView.setMovementMethod(LinkMovementMethod.getInstance()); - textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4)); - textView.setLinkTextColor(Theme.getColor(linkTextColorKey)); + textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText4)); + textView.setLinkTextColor(getThemedColor(linkTextColorKey)); textView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, padding, 0, padding, 0)); } @@ -125,7 +135,7 @@ public class TextInfoPrivacyCell extends FrameLayout { } public void setTextColor(String key) { - textView.setTextColor(Theme.getColor(key)); + textView.setTextColor(getThemedColor(key)); textView.setTag(key); } @@ -151,4 +161,9 @@ public class TextInfoPrivacyCell extends FrameLayout { info.setClassName(TextView.class.getName()); info.setText(text); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSelectionHelper.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSelectionHelper.java index a26f6eb9d..a5914def3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSelectionHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/TextSelectionHelper.java @@ -424,7 +424,7 @@ public abstract class TextSelectionHelper { copyText(); }); @@ -476,7 +476,7 @@ public abstract class TextSelectionHelper> 32); - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); - if (user != null) { - setData(user, null, name, text, 0, divider); - } - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (chat != null) { - setData(chat, null, name, text, 0, divider); - } - } - } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(exception.did)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(exception.did)); if (encryptedChat != null) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); if (user != null) { setData(user, encryptedChat, name, text, 0, false); } } + } else if (DialogObject.isUserDialog(exception.did)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(exception.did); + if (user != null) { + setData(user, null, name, text, 0, divider); + } + } else { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-exception.did); + if (chat != null) { + setData(chat, null, name, text, 0, divider); + } } } @@ -344,18 +341,6 @@ public class UserCell extends FrameLayout { if (currentUser.photo != null) { photo = currentUser.photo.photo_small; } - /*if (encryptedChat != null) { - drawNameLock = true; - dialog_id = ((long) encryptedChat.id) << 32; - if (!LocaleController.isRTL) { - nameLockLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline); - nameLeft = AndroidUtilities.dp(AndroidUtilities.leftBaseline + 4) + Theme.dialogs_lockDrawable.getIntrinsicWidth(); - } else { - nameLockLeft = getMeasuredWidth() - AndroidUtilities.dp(AndroidUtilities.leftBaseline + 2) - Theme.dialogs_lockDrawable.getIntrinsicWidth(); - nameLeft = AndroidUtilities.dp(11); - } - nameLockTop = AndroidUtilities.dp(16.5f); - }*/ } else if (currentObject instanceof TLRPC.Chat) { currentChat = (TLRPC.Chat) currentObject; if (currentChat.photo != null) { @@ -366,7 +351,7 @@ public class UserCell extends FrameLayout { if (mask != 0) { boolean continueUpdate = false; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) { - if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { + if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) { continueUpdate = true; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/WallpaperCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/WallpaperCell.java index 6f715a742..7d9a3419a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/WallpaperCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/WallpaperCell.java @@ -15,6 +15,7 @@ import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.BlendMode; import android.graphics.Canvas; +import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; @@ -176,7 +177,7 @@ public class WallpaperCell extends FrameLayout { } if (Theme.DEFAULT_BACKGROUND_SLUG.equals(wallPaper.slug)) { if (wallPaper.defaultCache == null) { - wallPaper.defaultCache = SvgHelper.getBitmap(R.raw.default_pattern, 100, 180, patternColor); + wallPaper.defaultCache = SvgHelper.getBitmap(R.raw.default_pattern, 100, 180, Color.BLACK); } imageView.setImageBitmap(wallPaper.defaultCache); imageView.getImageReceiver().setAlpha(Math.abs(wallPaper.intensity)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java index dfa7543b9..b3ac23512 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChangePhoneActivity.java @@ -379,8 +379,8 @@ public class ChangePhoneActivity extends BaseFragment { addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 0, 0, 14)); countryButton.setOnClickListener(view -> { CountrySelectActivity fragment = new CountrySelectActivity(true); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - selectCountry(name); + fragment.setCountrySelectActivityDelegate((country) -> { + selectCountry(country.name); AndroidUtilities.runOnUIThread(() -> AndroidUtilities.showKeyboard(phoneField), 300); phoneField.requestFocus(); phoneField.setSelection(phoneField.length()); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java index d0e8cbcaa..8624b3f78 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java @@ -29,6 +29,8 @@ import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; + +import androidx.collection.LongSparseArray; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.ChatListItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; @@ -38,8 +40,6 @@ import androidx.recyclerview.widget.RecyclerView; import android.text.TextUtils; import android.text.style.CharacterStyle; import android.text.style.URLSpan; -import android.util.LongSparseArray; -import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -184,14 +184,14 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio private ArrayList admins; private TLRPC.TL_channelAdminLogEventsFilter currentFilter = null; private String searchQuery = ""; - private SparseArray selectedAdmins; + private LongSparseArray selectedAdmins; private MessageObject scrollToMessage; private int allowAnimationIndex; private HashMap invitesCache = new HashMap<>(); - private HashMap usersMap; + private HashMap usersMap; private boolean linviteLoading; private PhotoViewer.PhotoViewerProvider provider = new PhotoViewer.EmptyPhotoViewerProvider() { @@ -848,7 +848,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context)); chatListView.setClipToPadding(false); chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3)); - chatListView.setItemAnimator(chatListItemAnimator = new ChatListItemAnimator(null, chatListView) { + chatListView.setItemAnimator(chatListItemAnimator = new ChatListItemAnimator(null, chatListView, null) { int scrollAnimationIndex = -1; Runnable finishRunnable; @@ -1078,7 +1078,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio return; } AndroidUtilities.hideKeyboard(searchItem.getSearchField()); - showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, param -> loadMessages(true)).create()); + showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, param -> loadMessages(true), null).create()); }); searchCountText = new SimpleTextView(context); @@ -1143,7 +1143,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } } else if (selectedObject.currentEvent != null && selectedObject.currentEvent.action instanceof TLRPC.TL_channelAdminLogEventActionChangeHistoryTTL) { if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) { - ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), null, currentChat, false); + ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), null, currentChat, false, null); alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() { @Override public void onAutoDeleteHistory(int ttl, int action) { @@ -1246,7 +1246,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio private String getMessageContent(MessageObject messageObject, int previousUid, boolean name) { String str = ""; if (name) { - int fromId = messageObject.getFromChatId(); + long fromId = messageObject.getFromChatId(); if (previousUid != fromId) { if (fromId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(fromId); @@ -1532,7 +1532,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } case 15: { Bundle args = new Bundle(); - args.putInt("user_id", selectedObject.messageOwner.media.user_id); + args.putLong("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); @@ -1947,7 +1947,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio return currentChat; } - private void addCanBanUser(Bundle bundle, int uid) { + private void addCanBanUser(Bundle bundle, long uid) { if (!currentChat.megagroup || admins == null || !ChatObject.canBlockUsers(currentChat)) { return; } @@ -1960,7 +1960,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio break; } } - bundle.putInt("ban_chat_id", currentChat.id); + bundle.putLong("ban_chat_id", currentChat.id); } public void showOpenUrlAlert(final String url, boolean ask) { @@ -2063,7 +2063,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { if (chat != null && chat != currentChat) { Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); if (postId != 0) { args.putInt("message_id", postId); } @@ -2115,7 +2115,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio private void openProfile(TLRPC.User user) { Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); addCanBanUser(args, user.id); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); @@ -2125,7 +2125,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio private void openDialog(ChatMessageCell cell, TLRPC.User user) { if (user != null) { Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); if (getMessagesController().checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args)); } @@ -2157,7 +2157,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio ((URLSpanMono) url).copyToClipboard(); Toast.makeText(getParentActivity(), LocaleController.getString("TextCopied", R.string.TextCopied), Toast.LENGTH_SHORT).show(); } else if (url instanceof URLSpanUserMention) { - int peerId = Utilities.parseInt(((URLSpanUserMention) url).getURL()); + long peerId = Utilities.parseInt(((URLSpanUserMention) url).getURL()); if (peerId > 0) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(peerId); if (user != null) { @@ -2304,7 +2304,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } } try { - AndroidUtilities.openForView(message, getParentActivity()); + AndroidUtilities.openForView(message, getParentActivity(), null); } catch (Exception e) { alertUserOpenError(message); } @@ -2359,16 +2359,16 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } @Override - public void needOpenUserProfile(int uid) { + public void needOpenUserProfile(long uid) { if (uid < 0) { Bundle args = new Bundle(); - args.putInt("chat_id", -uid); + args.putLong("chat_id", -uid); if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ChannelAdminLogActivity.this)) { presentFragment(new ChatActivity(args), true); } } else if (uid != UserConfig.getInstance(currentAccount).getClientUserId()) { Bundle args = new Bundle(); - args.putInt("user_id", uid); + args.putLong("user_id", uid); addCanBanUser(args, uid); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(0); @@ -2444,9 +2444,9 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } }); } else if (viewType == 2) { - view = new ChatUnreadCell(mContext); + view = new ChatUnreadCell(mContext, null); } else { - view = new ChatLoadingCell(mContext, contentView); + view = new ChatLoadingCell(mContext, contentView, null); } view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new RecyclerListView.Holder(view); @@ -2629,7 +2629,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio } } - private void showInviteLinkBottomSheet(TLRPC.TL_messages_exportedChatInvite invite, HashMap usersMap) { + private void showInviteLinkBottomSheet(TLRPC.TL_messages_exportedChatInvite invite, HashMap usersMap) { TLRPC.ChatFull chatInfo = getMessagesController().getChatFull(currentChat.id); InviteLinkBottomSheet inviteLinkBottomSheet = new InviteLinkBottomSheet(contentView.getContext(), (TLRPC.TL_chatInviteExported) invite.invite, chatInfo, usersMap, ChannelAdminLogActivity.this, chatInfo.id, false, ChatObject.isChannel(currentChat)); inviteLinkBottomSheet.setInviteDelegate(new InviteLinkBottomSheet.InviteDelegate() { @@ -2769,13 +2769,7 @@ public class ChannelAdminLogActivity extends BaseFragment implements Notificatio themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadDrawable, Theme.chat_msgOutHalfCheckDrawable}, null, Theme.key_chat_outSentCheckRead)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadSelectedDrawable, Theme.chat_msgOutHalfCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckReadSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutClockDrawable}, null, Theme.key_chat_outSentClock)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedClockDrawable}, null, Theme.key_chat_outSentClockSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInClockDrawable}, null, Theme.key_chat_inSentClock)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedClockDrawable}, null, Theme.key_chat_inSentClockSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaCheckDrawable, Theme.chat_msgMediaHalfCheckDrawable}, null, Theme.key_chat_mediaSentCheck)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgStickerHalfCheckDrawable, Theme.chat_msgStickerCheckDrawable, Theme.chat_msgStickerClockDrawable, Theme.chat_msgStickerViewsDrawable, Theme.chat_msgStickerRepliesDrawable, Theme.chat_msgStickerPinnedDrawable}, null, Theme.key_chat_serviceText)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaClockDrawable}, null, Theme.key_chat_mediaSentClock)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsDrawable, Theme.chat_msgOutRepliesDrawable, Theme.chat_msgOutPinnedDrawable}, null, Theme.key_chat_outViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsSelectedDrawable, Theme.chat_msgOutRepliesSelectedDrawable, Theme.chat_msgOutPinnedSelectedDrawable}, null, Theme.key_chat_outViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsDrawable, Theme.chat_msgInRepliesDrawable, Theme.chat_msgInPinnedDrawable}, null, Theme.key_chat_inViews)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java index 023f5ab34..2840c6cba 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChannelCreateActivity.java @@ -121,7 +121,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC private LoadingCell loadingAdminedCell; private int currentStep; - private int chatId; + private long chatId; private boolean canCreatePublic = true; private TLRPC.InputFile inputPhoto; private TLRPC.InputFile inputVideo; @@ -152,7 +152,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC loadAdminedChannels(); } } - chatId = args.getInt("chat_id", 0); + chatId = args.getLong("chat_id", 0); } } @@ -306,7 +306,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC } Bundle args = new Bundle(); args.putInt("step", 2); - args.putInt("chatId", chatId); + args.putLong("chatId", chatId); args.putInt("chatType", ChatObject.CHAT_TYPE_CHANNEL); presentFragment(new GroupCreateActivity(args), true); } @@ -883,6 +883,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC return; } if (avatarAnimation != null) { + avatarAnimation.removeAllListeners(); avatarAnimation.cancel(); avatarAnimation = null; } @@ -894,6 +895,9 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC avatarAnimation.playTogether(ObjectAnimator.ofFloat(avatarEditor, View.ALPHA, 0.0f), ObjectAnimator.ofFloat(avatarProgressView, View.ALPHA, 1.0f)); } else { + if (avatarEditor.getVisibility() != View.VISIBLE) { + avatarEditor.setAlpha(0f); + } avatarEditor.setVisibility(View.VISIBLE); avatarAnimation.playTogether(ObjectAnimator.ofFloat(avatarEditor, View.ALPHA, 1.0f), @@ -1001,10 +1005,10 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC FileLog.e(e); } } - int chat_id = (Integer) args[0]; + long chat_id = (Long) args[0]; Bundle bundle = new Bundle(); bundle.putInt("step", 1); - bundle.putInt("chat_id", chat_id); + bundle.putLong("chat_id", chat_id); bundle.putBoolean("canCreatePublic", canCreatePublic); if (inputPhoto != null || inputVideo != null) { MessagesController.getInstance(currentAccount).changeChatAvatar(chat_id, null, inputPhoto, inputVideo, videoTimestamp, inputVideoPath, avatar, avatarBig, null); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index caa336601..8c3ae610e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -26,8 +26,12 @@ import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Bitmap; +import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; +import android.graphics.ColorMatrix; +import android.graphics.ColorMatrixColorFilter; +import android.graphics.Matrix; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.Path; @@ -36,6 +40,7 @@ import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; +import android.graphics.Shader; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; @@ -55,7 +60,6 @@ import android.text.TextUtils; import android.text.style.CharacterStyle; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; -import android.util.LongSparseArray; import android.util.Property; import android.util.SparseArray; import android.util.SparseIntArray; @@ -82,6 +86,8 @@ import android.widget.Space; import android.widget.TextView; import android.widget.Toast; +import androidx.collection.LongSparseArray; +import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.ChatListItemAnimator; @@ -92,6 +98,7 @@ import androidx.recyclerview.widget.LinearSmoothScrollerCustom; import androidx.recyclerview.widget.RecyclerView; import com.google.android.exoplayer2.ui.AspectRatioFrameLayout; +import com.google.android.exoplayer2.util.Log; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.AccountInstance; @@ -100,7 +107,9 @@ import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildConfig; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.ChatThemeController; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.EmojiData; import org.telegram.messenger.FileLoader; @@ -124,7 +133,7 @@ import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; import org.telegram.messenger.VideoEditedInfo; import org.telegram.messenger.browser.Browser; -import org.telegram.messenger.support.SparseLongArray; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; @@ -140,6 +149,7 @@ import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BackDrawable; import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BottomSheet; +import org.telegram.ui.ActionBar.ChatTheme; import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; @@ -174,6 +184,7 @@ import org.telegram.ui.Components.ChatAttachAlertDocumentLayout; import org.telegram.ui.Components.ChatAvatarContainer; import org.telegram.ui.Components.ChatBigEmptyView; import org.telegram.ui.Components.ChatGreetingsView; +import org.telegram.ui.Components.ChatThemeBottomSheet; import org.telegram.ui.Components.ChecksHintView; import org.telegram.ui.Components.ClearHistoryAlert; import org.telegram.ui.Components.ClippingImageView; @@ -212,6 +223,7 @@ import org.telegram.ui.Components.ShareAlert; import org.telegram.ui.Components.Size; import org.telegram.ui.Components.SizeNotifierFrameLayout; import org.telegram.ui.Components.StickersAlert; +import org.telegram.ui.Components.TextSelectionHint; import org.telegram.ui.Components.TextStyleSpan; import org.telegram.ui.Components.TrendingStickersAlert; import org.telegram.ui.Components.TypefaceSpan; @@ -234,6 +246,8 @@ import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -246,7 +260,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not protected TLRPC.EncryptedChat currentEncryptedChat; private boolean userBlocked; - private int chatInviterId; + private long chatInviterId; private ArrayList chatMessageCellsCache = new ArrayList<>(); @@ -267,6 +281,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private ActionBarMenuItem editTextItem; private ActionBarMenuItem searchItem; private ActionBarMenuItem searchIconItem; + private ActionBarMenuItem audioCallIconItem; private boolean searchItemVisible; private RadialProgressView progressBar; private ActionBarMenuSubItem addContactItem; @@ -523,7 +538,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public boolean openAnimationEnded; private boolean fragmentOpened; - private boolean fragmentBeginToShow; private long openAnimationStartTime; private boolean scrollToTopOnResume; @@ -606,7 +620,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not protected TLRPC.ChatFull chatInfo; protected TLRPC.UserFull userInfo; - private SparseArray botInfo = new SparseArray<>(); + private LongSparseArray botInfo = new LongSparseArray<>(); private String botUser; private long inlineReturn; private String voiceChatHash; @@ -635,6 +649,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private int popupAnimationIndex = -1; private AnimatorSet scrimAnimatorSet; private ActionBarPopupWindow scrimPopupWindow; + private ActionBarPopupWindow mesageSeenUsersPopupWindow; + private int scrimPopupX, scrimPopupY; private ActionBarMenuSubItem[] scrimPopupWindowItems; private ActionBarMenuSubItem menuDeleteItem; private Runnable updateDeleteItemRunnable = new Runnable() { @@ -710,15 +726,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private int scrollCallbackAnimationIndex; private boolean showSearchAsIcon; + private boolean showAudioCallAsIcon; public MessageEnterTransitionContainer messageEnterTransitionContainer; private float pullingDownOffset; private ChatPullingDownDrawable pullingDownDrawable; - private ValueAnimator pullingDownBackAnimator; + private Animator pullingDownBackAnimator; private boolean fromPullingDownTransition; private boolean toPullingDownTransition; private ChatActivity pullingDownAnimateToActivity; private float pullingDownAnimateProgress; private AnimatorSet fragmentTransition; + private ChatActivity backToPreviousFragment; private Runnable fragmentTransitionRunnable = new Runnable() { @Override public void run() { @@ -728,6 +746,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }; + private boolean isPauseOnThemePreview; + private ChatThemeBottomSheet chatThemeBottomSheet; + private ThemeDelegate themeDelegate; + private final static int[] allowedNotificationsDuringChatListAnimations = new int[]{ NotificationCenter.messagesRead, NotificationCenter.threadMessagesRead, @@ -778,14 +800,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int dialogFilterId; private PinchToZoomHelper pinchToZoomHelper; - - public float getChatListViewPadding() { - return chatListViewPaddingTop; - } - - public FragmentContextView getFragmentContextView() { - return fragmentContextView; - } + private EmojiAnimationsOverlay emojiAnimationsOverlay; private interface ChatActivityDelegate { default void openReplyMessage(int mid) { @@ -962,15 +977,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override protected void onDraw(Canvas canvas) { Layout layout = textLayout; - int color = Theme.getColor(Theme.key_chat_fieldOverlayText); + int color = getThemedColor(Theme.key_chat_fieldOverlayText); if (textColor != color) { layoutPaint.setColor(textColor = color); } - color = Theme.getColor(Theme.key_chat_messagePanelBackground); + color = getThemedColor(Theme.key_chat_messagePanelBackground); if (panelBackgroundColor != color) { textPaint.setColor(panelBackgroundColor = color); } - color = Theme.getColor(Theme.key_chat_goDownButtonCounterBackground); + color = getThemedColor(Theme.key_chat_goDownButtonCounterBackground); if (counterColor != color) { paint.setColor(counterColor = color); } @@ -978,8 +993,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParent() != null) { int contentWidth = getMeasuredWidth(); int x = (getMeasuredWidth() - contentWidth) / 2; - if (rippleColor != Theme.getColor(Theme.key_chat_fieldOverlayText) || selectableBackground == null) { - selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(rippleColor = Theme.getColor(Theme.key_chat_fieldOverlayText), 26)); + if (rippleColor != getThemedColor(Theme.key_chat_fieldOverlayText) || selectableBackground == null) { + selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(rippleColor = getThemedColor(Theme.key_chat_fieldOverlayText), 26)); selectableBackground.setCallback(this); } int start = (getLeft() + x) <= 0 ? x - AndroidUtilities.dp(20) : x; @@ -1108,6 +1123,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private final static int add_shortcut = 24; private final static int save_to = 25; private final static int auto_delete_timer = 26; + private final static int change_colors = 27; private final static int bot_help = 30; private final static int bot_settings = 31; @@ -1293,7 +1309,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } SharedConfig.increaseScheduledOrNoSuoundHintShowed(); if (scheduledOrNoSoundHint == null) { - scheduledOrNoSoundHint = new HintView(getParentActivity(), 4); + scheduledOrNoSoundHint = new HintView(getParentActivity(), 4, themeDelegate); scheduledOrNoSoundHint.setShowingDuration(5000); scheduledOrNoSoundHint.setAlpha(0); scheduledOrNoSoundHint.setVisibility(View.INVISIBLE); @@ -1309,8 +1325,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public boolean onFragmentCreate() { - final int chatId = arguments.getInt("chat_id", 0); - final int userId = arguments.getInt("user_id", 0); + final long chatId = arguments.getLong("chat_id", 0); + final long userId = arguments.getLong("user_id", 0); final int encId = arguments.getInt("enc_id", 0); dialogFolderId = arguments.getInt("dialog_folder_id", 0); dialogFilterId = arguments.getInt("dialog_filter_id", 0); @@ -1419,13 +1435,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return false; } } - dialog_id = ((long) encId) << 32; + dialog_id = DialogObject.makeEncryptedDialogId(encId); maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE; minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE; } else { return false; } + themeDelegate = new ThemeDelegate(); + if (themeDelegate.isThemeChangeAvailable()) { + NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.needSetDayNightTheme); + } + if (currentUser != null && Build.VERSION.SDK_INT < 23) { MediaController.getInstance().startMediaObserver(); } @@ -1593,21 +1614,21 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not startLoadFromMessageIdSaved = startLoadFromMessageId; if (migrated_to != 0) { mergeDialogId = migrated_to; - getMessagesController().loadMessages(mergeDialogId, 0, loadInfo, loadingFromOldPosition ? 50 : (AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20), startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(mergeDialogId, 0, loadInfo, loadingFromOldPosition ? 50 : (AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20), startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } else { - getMessagesController().loadMessages(dialog_id, mergeDialogId, loadInfo, loadingFromOldPosition ? 50 : (AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20), startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, loadInfo, loadingFromOldPosition ? 50 : (AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20), startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } } else { if (historyPreloaded) { lastLoadIndex++; } else { - getMessagesController().loadMessages(dialog_id, mergeDialogId, loadInfo, AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20, startLoadFromMessageId, 0, true, 0, classGuid, 2, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, loadInfo, AndroidUtilities.isTablet() || isThreadChat() ? 30 : 20, startLoadFromMessageId, 0, true, 0, classGuid, 2, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } } } if (chatMode == 0 && !isThreadChat()) { waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 1, 0, 0, true, 0, classGuid, 2, 0, ChatObject.isChannel(currentChat), MODE_SCHEDULED, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 1, 0, 0, true, 0, classGuid, 2, 0, MODE_SCHEDULED, threadMessageId, replyMaxReadId, lastLoadIndex++); } if (chatMode == 0) { @@ -1648,7 +1669,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } AndroidUtilities.runOnUIThread(chatInviteRunnable = () -> { chatInviteRunnable = null; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) { builder.setMessage(LocaleController.getString("JoinByPeekChannelText", R.string.JoinByPeekChannelText)); builder.setTitle(LocaleController.getString("JoinByPeekChannelTitle", R.string.JoinByPeekChannelTitle)); @@ -1681,7 +1702,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatInviterId = chatInfo.participants.self_participant.inviter_id; return; } - int selfId = getUserConfig().getClientUserId(); + long selfId = getUserConfig().getClientUserId(); for (int a = 0, N = chatInfo.participants.participants.size(); a < N; a++) { TLRPC.ChatParticipant participant = chatInfo.participants.participants.get(a); if (participant.user_id == selfId) { @@ -1799,6 +1820,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null) { getNotificationCenter().removeObserver(this, NotificationCenter.didVerifyMessagesStickers); } + NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.needSetDayNightTheme); if (chatMode == 0 && AndroidUtilities.isTablet()) { getNotificationCenter().postNotificationName(NotificationCenter.openedChatChanged, dialog_id, true); @@ -1842,6 +1864,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (pinchToZoomHelper != null) { pinchToZoomHelper.clear(); } + chatThemeBottomSheet = null; } @Override @@ -1851,19 +1874,30 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public int getParentTopPadding() { return (int) chatListViewPaddingTop; } + + @Override + protected int getThemedColor(String key) { + Integer color = themeDelegate.getColor(key); + return color != null ? color : super.getThemedColor(key); + } + + @Override + protected Theme.ResourcesProvider getResourcesProvider() { + return themeDelegate; + } }; if (reportType >= 0) { - actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefault)); - actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), false); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), false); - actionBar.setTitleColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon)); - actionBar.setSubtitleColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon)); + actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefault)); + actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), false); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false); + actionBar.setTitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon)); + actionBar.setSubtitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon)); } if (chatMessageCellsCache.isEmpty()) { for (int a = 0; a < 15; a++) { - chatMessageCellsCache.add(new ChatMessageCell(context)); + chatMessageCellsCache.add(new ChatMessageCell(context, themeDelegate)); } } for (int a = 1; a >= 0; a--) { @@ -1936,7 +1970,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } else if (id == copy) { String str = ""; - int previousUid = 0; + long previousUid = 0; for (int a = 1; a >= 0; a--) { ArrayList ids = new ArrayList<>(); for (int b = 0; b < selectedMessagesCanCopyIds[a].size(); b++) { @@ -1988,27 +2022,27 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParentActivity() == null) { return; } - BulletinFactory.of(ChatActivity.this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count).show(); + BulletinFactory.of(ChatActivity.this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count, themeDelegate).show(); } }); } else if (id == chat_enc_timer) { if (getParentActivity() == null) { return; } - showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat).create()); + showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat, themeDelegate).create()); } else if (id == clear_history || id == delete_chat || id == auto_delete_timer) { if (getParentActivity() == null) { return; } if (id == auto_delete_timer || id == clear_history && currentEncryptedChat == null && (currentUser != null && !UserObject.isUserSelf(currentUser) && !UserObject.isDeleted(currentUser) || ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES) && (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)))) { - ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), currentUser, currentChat, id != auto_delete_timer); + ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), currentUser, currentChat, id != auto_delete_timer, themeDelegate); alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() { @Override public void onClearHistory(boolean revoke) { if (revoke && currentUser != null) { getMessagesStorage().getMessagesCount(currentUser.id, (count) -> { if (count >= 50) { - AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, true, false, true, null, currentUser, false, false, (param) -> performHistoryClear(true)); + AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, true, false, true, null, currentUser, false, false, (param) -> performHistoryClear(true), themeDelegate); } else { performHistoryClear(true); } @@ -2029,7 +2063,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not showDialog(alert); return; } - final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1; + final boolean isChat = DialogObject.isChatDialog(dialog_id); AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, id == clear_history, currentChat, currentUser, currentEncryptedChat != null, true, (param) -> { if (id == clear_history && ChatObject.isChannel(currentChat) && (!currentChat.megagroup || !TextUtils.isEmpty(currentChat.username))) { @@ -2044,7 +2078,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not performHistoryClear(param); } } - }); + }, themeDelegate); } else if (id == share_contact) { if (currentUser == null || getParentActivity() == null) { return; @@ -2053,7 +2087,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not shareMyContact((Integer) addToContactsButton.getTag(), null); } else { Bundle args = new Bundle(); - args.putInt("user_id", currentUser.id); + args.putLong("user_id", currentUser.id); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); } @@ -2066,7 +2100,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FileLog.e(e); } } else if (id == report) { - AlertsCreator.createReportAlert(getParentActivity(), dialog_id, 0, ChatActivity.this); + AlertsCreator.createReportAlert(getParentActivity(), dialog_id, 0, ChatActivity.this, themeDelegate); } else if (id == star) { for (int a = 0; a < 2; a++) { for (int b = 0; b < selectedMessagesCanStarIds[a].size(); b++) { @@ -2143,14 +2177,23 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd); chatActivityEnterView.getEditField().makeSelectedRegular(); } + } else if (id == change_colors) { + showChatThemeBottomSheet(); } } }); + actionBar.setInterceptTouchEventListener((view, motionEvent) -> { + if (chatThemeBottomSheet != null) { + chatThemeBottomSheet.close(); + return true; + } + return false; + }); if (avatarContainer != null) { avatarContainer.onDestroy(); } - avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null); + avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null, themeDelegate); AndroidUtilities.updateViewVisibilityAnimated(avatarContainer, true, 1f, false); if (inPreviewMode || inBubbleMode) { avatarContainer.setOccupyStatusBar(false); @@ -2174,7 +2217,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat == null && chatMode == 0 && reportType < 0) { searchIconItem = menu.addItem(search, R.drawable.ic_ab_search); - searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { + searchItem = menu.addItem(0, R.drawable.ic_ab_search, themeDelegate).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() { boolean searchWas; @@ -2217,6 +2260,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (searchIconItem != null && showSearchAsIcon) { searchIconItem.setVisibility(View.GONE); } + if (audioCallIconItem != null && showAudioCallAsIcon) { + audioCallIconItem.setVisibility(View.GONE); + } } else if (chatActivityEnterView.hasText() && TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer()) && (currentChat == null || ChatObject.canSendMessages(currentChat))) { if (headerItem != null) { headerItem.setVisibility(View.GONE); @@ -2230,10 +2276,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (searchIconItem != null && showSearchAsIcon) { searchIconItem.setVisibility(View.GONE); } + if (audioCallIconItem != null && showAudioCallAsIcon) { + audioCallIconItem.setVisibility(View.GONE); + } } else { if (headerItem != null) { headerItem.setVisibility(View.VISIBLE); } + if (audioCallIconItem != null && showAudioCallAsIcon) { + audioCallIconItem.setVisibility(View.VISIBLE); + } if (searchIconItem != null && showSearchAsIcon) { searchIconItem.setVisibility(View.VISIBLE); } @@ -2324,14 +2376,25 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (chatMode == 0 && threadMessageId == 0 && !UserObject.isReplyUser(currentUser) && reportType < 0) { - headerItem = menu.addItem(0, R.drawable.ic_ab_other); + TLRPC.UserFull userFull = null; + if (currentUser != null) { + audioCallIconItem = menu.addItem(call, R.drawable.ic_call, themeDelegate); + userFull = getMessagesController().getUserFull(currentUser.id); + if (userFull != null && userFull.phone_calls_available) { + showAudioCallAsIcon = !inPreviewMode; + audioCallIconItem.setVisibility(View.VISIBLE); + } else { + showAudioCallAsIcon = false; + audioCallIconItem.setVisibility(View.GONE); + } + } + headerItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate); headerItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); if (currentUser != null) { - headerItem.addSubItem(call, R.drawable.msg_callback, LocaleController.getString("Call", R.string.Call)); + headerItem.addSubItem(call, R.drawable.msg_callback, LocaleController.getString("Call", R.string.Call), themeDelegate); if (Build.VERSION.SDK_INT >= 18) { - headerItem.addSubItem(video_call, R.drawable.msg_videocall, LocaleController.getString("VideoCall", R.string.VideoCall)); + headerItem.addSubItem(video_call, R.drawable.msg_videocall, LocaleController.getString("VideoCall", R.string.VideoCall), themeDelegate); } - TLRPC.UserFull userFull = getMessagesController().getUserFull(currentUser.id); if (userFull != null && userFull.phone_calls_available) { headerItem.showSubItem(call); if (userFull.video_calls_available) { @@ -2345,7 +2408,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - editTextItem = menu.addItem(0, R.drawable.ic_ab_other); + editTextItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate); editTextItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); editTextItem.setTag(null); editTextItem.setVisibility(View.GONE); @@ -2375,46 +2438,49 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not editTextItem.addSubItem(text_regular, LocaleController.getString("Regular", R.string.Regular)); if (searchItem != null) { - headerItem.addSubItem(search, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search)); + headerItem.addSubItem(search, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search), themeDelegate); } if (currentChat != null && !currentChat.creator && !ChatObject.hasAdminRights(currentChat)) { - headerItem.addSubItem(report, R.drawable.msg_report, LocaleController.getString("ReportChat", R.string.ReportChat)); + headerItem.addSubItem(report, R.drawable.msg_report, LocaleController.getString("ReportChat", R.string.ReportChat), themeDelegate); } if (currentUser != null) { - addContactItem = headerItem.addSubItem(share_contact, R.drawable.msg_addcontact, ""); + addContactItem = headerItem.addSubItem(share_contact, R.drawable.msg_addcontact, "", themeDelegate); } if (currentEncryptedChat != null) { - timeItem2 = headerItem.addSubItem(chat_enc_timer, R.drawable.msg_timer, LocaleController.getString("SetTimer", R.string.SetTimer)); + timeItem2 = headerItem.addSubItem(chat_enc_timer, R.drawable.msg_timer, LocaleController.getString("SetTimer", R.string.SetTimer), themeDelegate); } if (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)) { - headerItem.addSubItem(clear_history, R.drawable.msg_clear, LocaleController.getString("ClearHistory", R.string.ClearHistory)); + headerItem.addSubItem(clear_history, R.drawable.msg_clear, LocaleController.getString("ClearHistory", R.string.ClearHistory), themeDelegate); } else if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) { - headerItem.addSubItem(auto_delete_timer, R.drawable.msg_timer, LocaleController.getString("AutoDeleteSetTimer", R.string.AutoDeleteSetTimer)); + headerItem.addSubItem(auto_delete_timer, R.drawable.msg_timer, LocaleController.getString("AutoDeleteSetTimer", R.string.AutoDeleteSetTimer), themeDelegate); + } + if (themeDelegate.isThemeChangeAvailable()) { + headerItem.addSubItem(change_colors, R.drawable.msg_colors, LocaleController.getString("ChangeColors", R.string.ChangeColors), themeDelegate); } if (currentUser == null || !currentUser.self) { - muteItem = headerItem.addSubItem(mute, R.drawable.msg_mute, null); + muteItem = headerItem.addSubItem(mute, R.drawable.msg_mute, null, themeDelegate); } if (ChatObject.isChannel(currentChat) && !currentChat.creator) { if (!ChatObject.isNotInChat(currentChat)) { if (currentChat.megagroup) { - headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveMegaMenu", R.string.LeaveMegaMenu)); + headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveMegaMenu", R.string.LeaveMegaMenu), themeDelegate); } else { - headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveChannelMenu", R.string.LeaveChannelMenu)); + headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveChannelMenu", R.string.LeaveChannelMenu), themeDelegate); } } } else if (!ChatObject.isChannel(currentChat)) { if (currentChat != null) { - headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit)); + headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), themeDelegate); } else { - headerItem.addSubItem(delete_chat, R.drawable.msg_delete, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser)); + headerItem.addSubItem(delete_chat, R.drawable.msg_delete, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), themeDelegate); } } if (currentUser != null && currentUser.self) { - headerItem.addSubItem(add_shortcut, R.drawable.msg_home, LocaleController.getString("AddShortcut", R.string.AddShortcut)); + headerItem.addSubItem(add_shortcut, R.drawable.msg_home, LocaleController.getString("AddShortcut", R.string.AddShortcut), themeDelegate); } if (currentUser != null && currentEncryptedChat == null && currentUser.bot) { - headerItem.addSubItem(bot_settings, R.drawable.menu_settings, LocaleController.getString("BotSettings", R.string.BotSettings)); - headerItem.addSubItem(bot_help, R.drawable.menu_help, LocaleController.getString("BotHelp", R.string.BotHelp)); + headerItem.addSubItem(bot_settings, R.drawable.menu_settings, LocaleController.getString("BotSettings", R.string.BotSettings), themeDelegate); + headerItem.addSubItem(bot_help, R.drawable.menu_help, LocaleController.getString("BotHelp", R.string.BotHelp), themeDelegate); updateBotButtons(); } } @@ -2425,7 +2491,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateTitleIcons(); if (chatMode == 0 && !isThreadChat() && reportType < 0) { - attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other).setOverrideMenuClick(true).setAllowCloseAnimation(false); + attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other, themeDelegate).setOverrideMenuClick(true).setAllowCloseAnimation(false); attachItem.setContentDescription(LocaleController.getString("AccDescrAttachButton", R.string.AccDescrAttachButton)); attachItem.setVisibility(View.GONE); } @@ -2446,7 +2512,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selectedMessagesCountTextView = new NumberTextView(actionMode.getContext()); selectedMessagesCountTextView.setTextSize(18); selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - selectedMessagesCountTextView.setTextColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon)); + selectedMessagesCountTextView.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon)); actionMode.addView(selectedMessagesCountTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0)); selectedMessagesCountTextView.setOnTouchListener((v, event) -> true); @@ -2568,6 +2634,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (pullingDownDrawable != null) { pullingDownDrawable.onAttach(); } + emojiAnimationsOverlay.onAttachedToWindow(); } @Override @@ -2578,6 +2645,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pullingDownDrawable.onDetach(); pullingDownDrawable = null; } + emojiAnimationsOverlay.onDetachedFromWindow(); } @Override @@ -2654,9 +2722,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) != null) { boolean needBlur; if (((int) getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND)) == BlurBehindDrawable.STATIC_CONTENT) { - needBlur = child == actionBar; + needBlur = child == actionBar || child == fragmentContextView || child == pinnedMessageView; } else { - needBlur = child == chatListView || child == pinnedMessageView || child == fragmentContextView || child == chatActivityEnterView || chatActivityEnterView.isPopupView(child); + needBlur = child == chatListView || child == chatActivityEnterView || chatActivityEnterView.isPopupView(child); } if (!needBlur) { return false; @@ -2786,7 +2854,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (chatActivityEnterView != null) { if (chatActivityEnterView.pannelAniamationInProgress() && chatActivityEnterView.getEmojiPadding() < bottomPanelTranslationY) { - int color = Theme.getColor(Theme.key_chat_emojiPanelBackground); + int color = getThemedColor(Theme.key_chat_emojiPanelBackground); if (backgroundPaint == null) { backgroundPaint = new Paint(); } @@ -2965,7 +3033,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } if (fixedKeyboardHeight > 0 && keyboardHeight < AndroidUtilities.dp(20)) { - int color = Theme.getColor(Theme.key_windowBackgroundWhite); + int color = getThemedColor(Theme.key_windowBackgroundWhite); if (backgroundPaint == null) { backgroundPaint = new Paint(); } @@ -2990,6 +3058,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pullingDownAnimateToActivity.fragmentView.draw(canvas); canvas.restore(); } + + emojiAnimationsOverlay.draw(canvas); } @Override @@ -3007,17 +3077,23 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not SimpleTextView textView = avatarContainer.getTitleTextView(); int textWidth = (int) textView.getPaint().measureText(textView.getText(), 0, textView.getText().length()); if (widthSize - AndroidUtilities.dp(96 + 56) > textWidth + AndroidUtilities.dp(10)) { - showSearchAsIcon = true; + showSearchAsIcon = !showAudioCallAsIcon; } else { showSearchAsIcon = false; } } else { showSearchAsIcon = false; } - if (showSearchAsIcon) { + if (showSearchAsIcon || showAudioCallAsIcon) { if (avatarContainer != null && avatarContainer.getLayoutParams() != null) { ((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(96); } + } else { + if (avatarContainer != null && avatarContainer.getLayoutParams() != null) { + ((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(40); + } + } + if (showSearchAsIcon) { if (!actionBar.isSearchFieldVisible() && searchIconItem != null) { searchIconItem.setVisibility(View.VISIBLE); } @@ -3028,13 +3104,21 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (headerItem != null) { headerItem.showSubItem(search); } - if (avatarContainer != null && avatarContainer.getLayoutParams() != null) { - ((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(40); - } if (searchIconItem != null) { searchIconItem.setVisibility(View.GONE); } } + if (!actionBar.isSearchFieldVisible() && audioCallIconItem != null) { + audioCallIconItem.setVisibility((showAudioCallAsIcon && !showSearchAsIcon) ? View.VISIBLE : View.GONE); + } + if (headerItem != null) { + TLRPC.UserFull userInfo = getCurrentUserInfo(); + if (showAudioCallAsIcon) { + headerItem.hideSubItem(call); + } else if (userInfo != null && userInfo.phone_calls_available) { + headerItem.showSubItem(call); + } + } globalIgnoreLayout = false; } @@ -3419,6 +3503,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } return super.dispatchKeyEvent(event); } + + protected Drawable getNewDrawable() { + Drawable drawable = themeDelegate.getWallpaperDrawable(); + return drawable != null ? drawable : super.getNewDrawable(); + } }; contentView = (SizeNotifierFrameLayout) fragmentView; @@ -3435,16 +3524,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int distance = getArguments().getInt("nearby_distance", -1); if ((distance >= 0 || preloadedGreetingsSticker != null) && currentUser != null && !userBlocked) { - greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker); + greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate); greetingsViewContainer.setListener((sticker) -> { animatingDocuments.put(sticker, 0); SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0); }); - greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView)); + greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground))); emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0)); } else if (currentEncryptedChat == null) { if (!isThreadChat() && chatMode == 0 && (currentUser != null && currentUser.self || currentChat != null && currentChat.creator)) { - bigEmptyView = new ChatBigEmptyView(context, contentView, currentChat != null ? ChatBigEmptyView.EMPTY_VIEW_TYPE_GROUP : ChatBigEmptyView.EMPTY_VIEW_TYPE_SAVED); + bigEmptyView = new ChatBigEmptyView(context, contentView, currentChat != null ? ChatBigEmptyView.EMPTY_VIEW_TYPE_GROUP : ChatBigEmptyView.EMPTY_VIEW_TYPE_SAVED, themeDelegate); emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); if (currentChat != null) { bigEmptyView.setStatusText(AndroidUtilities.replaceTags(LocaleController.getString("GroupEmptyTitle1", R.string.GroupEmptyTitle1))); @@ -3465,27 +3554,27 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not emptyMessage = LocaleController.getString("NoMessages", R.string.NoMessages); } if (emptyMessage == null) { - greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker); + greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate); greetingsViewContainer.setListener((sticker) -> { animatingDocuments.put(sticker, 0); SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0); }); - greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView)); + greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground))); emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0)); } else { emptyView = new TextView(context); emptyView.setText(emptyMessage); emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); emptyView.setGravity(Gravity.CENTER); - emptyView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); - emptyView.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(6), emptyView, contentView)); + emptyView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); + emptyView.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(6), emptyView, contentView, getThemedPaint(Theme.key_paint_chatActionBackground))); emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10), AndroidUtilities.dp(3)); emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); } } } else { - bigEmptyView = new ChatBigEmptyView(context, contentView, ChatBigEmptyView.EMPTY_VIEW_TYPE_SECRET); + bigEmptyView = new ChatBigEmptyView(context, contentView, ChatBigEmptyView.EMPTY_VIEW_TYPE_SECRET, themeDelegate); if (currentEncryptedChat.admin_id == getUserConfig().getClientUserId()) { bigEmptyView.setStatusText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, UserObject.getFirstName(currentUser))); } else { @@ -3509,7 +3598,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not mentionsAdapter.onDestroy(); } - chatListView = new RecyclerListView(context) { + chatListView = new RecyclerListView(context, themeDelegate) { private int lastWidth; @@ -3665,7 +3754,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } int alpha; int alpha2; - int oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); + Paint chatActionBackgroundPaint = getThemedPaint(Theme.key_paint_chatActionBackground); + int oldAlpha = chatActionBackgroundPaint.getAlpha(); float scale; if (showing) { if (replyButtonProgress <= 0.8f) { @@ -3681,22 +3771,23 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not alpha2 = (int) Math.min(oldAlpha, oldAlpha * replyButtonProgress); } - Theme.chat_actionBackgroundPaint.setAlpha(alpha2); - Theme.chat_replyIconDrawable.setAlpha(alpha); + chatActionBackgroundPaint.setAlpha(alpha2); float x = getMeasuredWidth() + slidingView.getNonAnimationTranslationX(false) / 2; float y = slidingView.getTop() + slidingView.getMeasuredHeight() / 2; AndroidUtilities.rectTmp.set((int) (x - AndroidUtilities.dp(16) * scale), (int) (y - AndroidUtilities.dp(16) * scale), (int) (x + AndroidUtilities.dp(16) * scale), (int) (y + AndroidUtilities.dp(16) * scale)); Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() + AndroidUtilities.rectTmp.top); - canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), chatActionBackgroundPaint); + if (themeDelegate.hasGradientService()) { canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundGradientDarkenPaint); } + chatActionBackgroundPaint.setAlpha(oldAlpha); - Theme.chat_replyIconDrawable.setBounds((int) (x - AndroidUtilities.dp(7) * scale), (int) (y - AndroidUtilities.dp(6) * scale), (int) (x + AndroidUtilities.dp(7) * scale), (int) (y + AndroidUtilities.dp(5) * scale)); - Theme.chat_replyIconDrawable.draw(canvas); - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); - Theme.chat_replyIconDrawable.setAlpha(255); + Drawable replyIconDrawable = getThemedDrawable(Theme.key_drawable_replyIcon); + replyIconDrawable.setAlpha(alpha); + replyIconDrawable.setBounds((int) (x - AndroidUtilities.dp(7) * scale), (int) (y - AndroidUtilities.dp(6) * scale), (int) (x + AndroidUtilities.dp(7) * scale), (int) (y + AndroidUtilities.dp(5) * scale)); + replyIconDrawable.draw(canvas); + replyIconDrawable.setAlpha(255); } private void processTouchEvent(MotionEvent e) { @@ -3789,14 +3880,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not float progress = Math.min(1f, pullingDownOffset / AndroidUtilities.dp(110)); if (e.getAction() == MotionEvent.ACTION_UP && progress == 1 && pullingDownDrawable != null && !pullingDownDrawable.emptyStub) { if (pullingDownDrawable.animationIsRunning()) { - pullingDownBackAnimator = ValueAnimator.ofFloat(pullingDownOffset, pullingDownOffset + AndroidUtilities.dp(8)); - pullingDownBackAnimator.addUpdateListener(valueAnimator -> { + ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, pullingDownOffset + AndroidUtilities.dp(8)); + pullingDownBackAnimator = animator; + animator.addUpdateListener(valueAnimator -> { pullingDownOffset = (float) valueAnimator.getAnimatedValue(); chatListView.invalidate(); }); - pullingDownBackAnimator.setDuration(200); - pullingDownBackAnimator.setInterpolator(CubicBezierInterpolator.DEFAULT); - pullingDownBackAnimator.start(); + animator.setDuration(200); + animator.setInterpolator(CubicBezierInterpolator.DEFAULT); + animator.start(); pullingDownDrawable.runOnAnimationFinish(() -> { animateToNextChat(); }); @@ -3804,15 +3896,41 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not animateToNextChat(); } } else { - pullingDownBackAnimator = ValueAnimator.ofFloat(pullingDownOffset, 0); - pullingDownDrawable.showBottomPanel(false); - pullingDownBackAnimator.addUpdateListener(valueAnimator -> { - pullingDownOffset = (float) valueAnimator.getAnimatedValue(); - chatListView.invalidate(); - }); - pullingDownBackAnimator.setDuration(ChatListItemAnimator.DEFAULT_DURATION); - pullingDownBackAnimator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR); - pullingDownBackAnimator.start(); + if (pullingDownDrawable != null && pullingDownDrawable.emptyStub && (System.currentTimeMillis() - pullingDownDrawable.lastShowingReleaseTime) < 500 && pullingDownDrawable.animateSwipeToRelease) { + AnimatorSet animatorSet = new AnimatorSet(); + pullingDownBackAnimator = animatorSet; + pullingDownDrawable.showBottomPanel(false); + ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, AndroidUtilities.dp(111)); + animator.addUpdateListener(valueAnimator -> { + pullingDownOffset = (float) valueAnimator.getAnimatedValue(); + chatListView.invalidate(); + }); + animator.setDuration(400); + animator.setInterpolator(CubicBezierInterpolator.DEFAULT); + + ValueAnimator animator2 = ValueAnimator.ofFloat(AndroidUtilities.dp(111), 0); + animator2.addUpdateListener(valueAnimator -> { + pullingDownOffset = (float) valueAnimator.getAnimatedValue(); + chatListView.invalidate(); + }); + animator2.setStartDelay(600); + animator2.setDuration(ChatListItemAnimator.DEFAULT_DURATION); + animator2.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR); + + animatorSet.playSequentially(animator, animator2); + animatorSet.start(); + } else { + ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, 0); + pullingDownBackAnimator = animator; + pullingDownDrawable.showBottomPanel(false); + animator.addUpdateListener(valueAnimator -> { + pullingDownOffset = (float) valueAnimator.getAnimatedValue(); + chatListView.invalidate(); + }); + animator.setDuration(ChatListItemAnimator.DEFAULT_DURATION); + animator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR); + animator.start(); + } } } if (isFastScrollAnimationRunning()) { @@ -3901,7 +4019,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } c.translate(0, getMeasuredHeight() - transitionOffset); if (pullingDownDrawable == null) { - pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId); + pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId, themeDelegate); pullingDownDrawable.showBottomPanel(true); pullingDownDrawable.onAttach(); } @@ -3932,6 +4050,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not canvas.clipRect(0, chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4), getMeasuredWidth(), getMeasuredHeight()); } + selectorRect.setEmpty(); if (pullingDownOffset != 0) { canvas.save(); float transitionOffset = 0; @@ -3978,17 +4097,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if ((backgroundDrawable.isAnimationInProgress() || cell.isDrawingSelectionBackground()) && (position == null || (position.flags & MessageObject.POSITION_FLAG_RIGHT) != 0)) { if (cell.isHighlighted() || cell.isHighlightedAnimated()) { if (position == null) { - int color = Theme.getColor(Theme.key_chat_selectedBackground); + int color = getThemedColor(Theme.key_chat_selectedBackground); int alpha = Color.alpha(color); canvas.save(); canvas.translate(0, cell.getTranslationY()); - Theme.chat_replyLinePaint.setColor(Theme.getColor(Theme.key_chat_selectedBackground)); + Theme.chat_replyLinePaint.setColor(getThemedColor(Theme.key_chat_selectedBackground)); Theme.chat_replyLinePaint.setAlpha((int) (alpha * cell.getHightlightAlpha() * cell.getAlpha())); canvas.drawRect(0, cell.getTop(), getMeasuredWidth(), cell.getBottom(), Theme.chat_replyLinePaint); canvas.restore(); } } else { - backgroundDrawable.setColor(Theme.getColor(Theme.key_chat_selectedBackground)); + backgroundDrawable.setColor(getThemedColor(Theme.key_chat_selectedBackground)); int y = (int) cell.getY(); int height; canvas.save(); @@ -4662,7 +4781,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatListViewPaddingTop = 0; invalidateChatListViewTopPadding(); if (MessagesController.getGlobalMainSettings().getBoolean("view_animations", true)) { - chatListItemAnimator = new ChatListItemAnimator(this, chatListView) { + chatListItemAnimator = new ChatListItemAnimator(this, chatListView, themeDelegate) { Runnable finishRunnable; @@ -5100,6 +5219,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } invalidateMessagesVisiblePart(); textSelectionHelper.onParentScrolled(); + emojiAnimationsOverlay.onScrolled(dy); } }); @@ -5112,15 +5232,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); progressView2 = new View(context); - progressView2.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), progressView2, contentView)); + progressView2.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), progressView2, contentView, getThemedPaint(Theme.key_paint_chatActionBackground))); progressView.addView(progressView2, LayoutHelper.createFrame(36, 36, Gravity.CENTER)); - progressBar = new RadialProgressView(context); + progressBar = new RadialProgressView(context, themeDelegate); progressBar.setSize(AndroidUtilities.dp(28)); - progressBar.setProgressColor(Theme.getColor(Theme.key_chat_serviceText)); + progressBar.setProgressColor(getThemedColor(Theme.key_chat_serviceText)); progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER)); - floatingDateView = new ChatActionCell(context) { + floatingDateView = new ChatActionCell(context, themeDelegate) { @Override public void setTranslationY(float translationY) { @@ -5128,7 +5248,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not invalidate(); } super.setTranslationY(translationY); - } @Override @@ -5166,6 +5285,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not floatingDateView.setCustomDate((int) (System.currentTimeMillis() / 1000), false, false); floatingDateView.setAlpha(0.0f); floatingDateView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); + floatingDateView.setInvalidateColors(true); contentView.addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 4, 0, 0)); floatingDateView.setOnClickListener(view -> { if (floatingDateView.getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) { @@ -5253,7 +5373,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedMessageEnterOffset = -AndroidUtilities.dp(50); pinnedMessageView.setVisibility(View.GONE); pinnedMessageView.setBackgroundResource(R.drawable.blockpanel); - pinnedMessageView.getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); + pinnedMessageView.getBackground().mutate().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); contentView.addView(pinnedMessageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT)); pinnedMessageView.setOnClickListener(v -> { wasManualScroll = true; @@ -5285,13 +5405,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selector.setBackground(Theme.getSelectorDrawable(false)); pinnedMessageView.addView(selector, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 2)); - pinnedLineView = new PinnedLineView(context); + pinnedLineView = new PinnedLineView(context, themeDelegate); pinnedMessageView.addView(pinnedLineView, LayoutHelper.createFrame(2, 48, Gravity.LEFT | Gravity.TOP, 8, 0, 0, 0)); pinnedCounterTextView = new NumberTextView(context); pinnedCounterTextView.setAddNumber(); pinnedCounterTextView.setTextSize(14); - pinnedCounterTextView.setTextColor(Theme.getColor(Theme.key_chat_topPanelTitle)); + pinnedCounterTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle)); pinnedCounterTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); pinnedMessageView.addView(pinnedCounterTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7, 44, 0)); @@ -5310,7 +5430,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }; pinnedNameTextView[a].setTextSize(14); - pinnedNameTextView[a].setTextColor(Theme.getColor(Theme.key_chat_topPanelTitle)); + pinnedNameTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelTitle)); pinnedNameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); pinnedMessageView.addView(pinnedNameTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7.3f, 44, 0)); @@ -5328,7 +5448,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }; pinnedMessageTextView[a].setTextSize(14); - pinnedMessageTextView[a].setTextColor(Theme.getColor(Theme.key_chat_topPanelMessage)); + pinnedMessageTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelMessage)); pinnedMessageView.addView(pinnedMessageTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 25.3f, 44, 0)); pinnedMessageImageView[a] = new BackupImageView(context); @@ -5343,7 +5463,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedListButton = new ImageView(context); pinnedListButton.setImageResource(R.drawable.menu_pinnedlist); - pinnedListButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); + pinnedListButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); pinnedListButton.setScaleType(ImageView.ScaleType.CENTER); pinnedListButton.setContentDescription(LocaleController.getString("AccPinnedMessagesList", R.string.AccPinnedMessagesList)); pinnedListButton.setVisibility(View.INVISIBLE); @@ -5351,29 +5471,29 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedListButton.setScaleX(0.4f); pinnedListButton.setScaleY(0.4f); if (Build.VERSION.SDK_INT >= 21) { - pinnedListButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerClose) & 0x19ffffff)); + pinnedListButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff)); } pinnedMessageView.addView(pinnedListButton, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 7, 0)); pinnedListButton.setOnClickListener(v -> openPinnedMessagesList(false)); closePinned = new ImageView(context); closePinned.setImageResource(R.drawable.miniplayer_close); - closePinned.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); + closePinned.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); closePinned.setScaleType(ImageView.ScaleType.CENTER); closePinned.setContentDescription(LocaleController.getString("Close", R.string.Close)); - pinnedProgress = new RadialProgressView(context); + pinnedProgress = new RadialProgressView(context, themeDelegate); pinnedProgress.setVisibility(View.GONE); pinnedProgress.setSize(AndroidUtilities.dp(16)); pinnedProgress.setStrokeWidth(2f); - pinnedProgress.setProgressColor(Theme.getColor(Theme.key_chat_topPanelLine)); + pinnedProgress.setProgressColor(getThemedColor(Theme.key_chat_topPanelLine)); pinnedMessageView.addView(pinnedProgress, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0)); if (threadMessageId != 0) { closePinned.setVisibility(View.GONE); } if (Build.VERSION.SDK_INT >= 21) { - closePinned.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + closePinned.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); } pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0)); closePinned.setOnClickListener(v -> { @@ -5393,7 +5513,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not allowPin = false; } if (allowPin) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("UnpinMessageAlertTitle", R.string.UnpinMessageAlertTitle)); builder.setMessage(LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert)); builder.setPositiveButton(LocaleController.getString("UnpinMessage", R.string.UnpinMessage), (dialogInterface, i) -> { @@ -5464,13 +5584,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not invalidateChatListViewTopPadding(); topChatPanelView.setVisibility(View.GONE); topChatPanelView.setBackgroundResource(R.drawable.blockpanel); - topChatPanelView.getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); + topChatPanelView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); contentView.addView(topChatPanelView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT)); reportSpamButton = new TextView(context); - reportSpamButton.setTextColor(Theme.getColor(Theme.key_chat_reportSpam)); + reportSpamButton.setTextColor(getThemedColor(Theme.key_chat_reportSpam)); if (Build.VERSION.SDK_INT >= 21) { - reportSpamButton.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_chat_reportSpam) & 0x19ffffff, 2)); + reportSpamButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_reportSpam) & 0x19ffffff, 2)); } reportSpamButton.setTag(Theme.key_chat_reportSpam); reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); @@ -5485,10 +5605,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { finishFragment(); } - })); + }, themeDelegate)); addToContactsButton = new TextView(context); - addToContactsButton.setTextColor(Theme.getColor(Theme.key_chat_addContact)); + addToContactsButton.setTextColor(getThemedColor(Theme.key_chat_addContact)); addToContactsButton.setVisibility(View.GONE); addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -5497,7 +5617,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); addToContactsButton.setGravity(Gravity.CENTER); if (Build.VERSION.SDK_INT >= 21) { - addToContactsButton.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_chat_addContact) & 0x19ffffff, 2)); + addToContactsButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_addContact) & 0x19ffffff, 2)); } topChatPanelView.addView(addToContactsButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 1)); addToContactsButton.setOnClickListener(v -> { @@ -5514,12 +5634,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getNotificationsController().clearDialogNotificationsSettings(dialog_id); } else if (addToContactsButton.getTag() != null && (Integer) addToContactsButton.getTag() == 4) { if (chatInfo != null && chatInfo.participants != null) { - SparseArray users = new SparseArray<>(); + LongSparseArray users = new LongSparseArray<>(); for (int a = 0; a < chatInfo.participants.participants.size(); a++) { users.put(chatInfo.participants.participants.get(a).user_id, null); } - int chatId = chatInfo.id; - InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, users, chatInfo.id, ChatActivity.this); + long chatId = chatInfo.id; + InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, users, chatInfo.id, ChatActivity.this, themeDelegate); bottomSheet.setDelegate((users1, fwdCount) -> { for (int a = 0, N = users1.size(); a < N; a++) { TLRPC.User user = users1.get(a); @@ -5535,7 +5655,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not shareMyContact(1, null); } else { Bundle args = new Bundle(); - args.putInt("user_id", currentUser.id); + args.putLong("user_id", currentUser.id); args.putBoolean("addContact", true); ContactAddActivity activity = new ContactAddActivity(args); activity.setDelegate(() -> undoView.showWithAction(dialog_id, UndoView.ACTION_CONTACT_ADDED, currentUser)); @@ -5547,9 +5667,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not closeReportSpam.setImageResource(R.drawable.miniplayer_close); closeReportSpam.setContentDescription(LocaleController.getString("Close", R.string.Close)); if (Build.VERSION.SDK_INT >= 21) { - closeReportSpam.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_chat_topPanelClose) & 0x19ffffff)); + closeReportSpam.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_topPanelClose) & 0x19ffffff)); } - closeReportSpam.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); + closeReportSpam.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY)); closeReportSpam.setScaleType(ImageView.ScaleType.CENTER); topChatPanelView.addView(closeReportSpam, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0)); closeReportSpam.setOnClickListener(v -> { @@ -5566,12 +5686,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not alertView.setTag(1); alertView.setVisibility(View.GONE); alertView.setBackgroundResource(R.drawable.blockpanel); - alertView.getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); + alertView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY)); contentView.addView(alertView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT)); alertNameTextView = new TextView(context); alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - alertNameTextView.setTextColor(Theme.getColor(Theme.key_chat_topPanelTitle)); + alertNameTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle)); alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); alertNameTextView.setSingleLine(true); alertNameTextView.setEllipsize(TextUtils.TruncateAt.END); @@ -5580,7 +5700,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not alertTextView = new TextView(context); alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - alertTextView.setTextColor(Theme.getColor(Theme.key_chat_topPanelMessage)); + alertTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelMessage)); + alertTextView.setSingleLine(true); alertTextView.setEllipsize(TextUtils.TruncateAt.END); alertTextView.setMaxLines(1); @@ -5624,7 +5745,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { final MessagesStorage messagesStorage = getMessagesStorage(); TLRPC.TL_messages_getUnreadMentions req = new TLRPC.TL_messages_getUnreadMentions(); - req.peer = getMessagesController().getInputPeer((int) dialog_id); + req.peer = getMessagesController().getInputPeer(dialog_id); req.limit = 1; req.add_offset = newMentionsCount - 1; getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { @@ -5645,12 +5766,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } else { int id = res.messages.get(0).id; - long mid = id; - if (ChatObject.isChannel(currentChat)) { - mid = mid | (((long) currentChat.id) << 32); - } MessageObject object = messagesDict[0].get(id); - messagesStorage.markMessageAsMention(mid); + messagesStorage.markMessageAsMention(dialog_id, id); if (object != null) { object.messageOwner.media_unread = true; object.messageOwner.mentioned = true; @@ -5695,7 +5812,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not float bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, (int) bottom, getMeasuredWidth(), (int) top); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, 0, getMeasuredWidth(), top, Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, 0, getMeasuredWidth(), top, getThemedPaint(Theme.key_paint_chatComposeBackground)); } else { int top = (int) mentionListView.getY(); if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout() && mentionsAdapter.getBotContextSwitch() == null) { @@ -5715,7 +5832,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, top, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, bottom, getMeasuredWidth(), bottomPanelTranslationYReverse + getMeasuredHeight(), Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, bottom, getMeasuredWidth(), bottomPanelTranslationYReverse + getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground)); } } } @@ -5762,7 +5879,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID(); inputStickerSet.access_hash = set.access_hash; inputStickerSet.id = set.id; - StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView); + StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate); alert.setCalcMandatoryInsets(isKeyboardVisible()); alert.setClearsInputField(clearsInputField); showDialog(alert); @@ -5774,7 +5891,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }; - mentionListView = new RecyclerListView(context) { + mentionListView = new RecyclerListView(context, themeDelegate) { private int lastWidth; private int lastHeight; @@ -5790,7 +5907,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return false; } } - boolean result = !mentionListViewIsScrolling && ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, mentionListView, 0, null); + boolean result = !mentionListViewIsScrolling && ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, mentionListView, 0, null, themeDelegate); + if (mentionsAdapter.isStickers() && event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) { + mentionsAdapter.doSomeStickersAction(); + } return super.onInterceptTouchEvent(event) || result; } @@ -5853,7 +5973,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not mentionContainer.invalidate(); } }; - mentionListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, mentionListView, 0, mentionsOnItemClickListener, mentionsAdapter.isStickers() ? contentPreviewViewerDelegate : null)); + mentionListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, mentionListView, 0, mentionsOnItemClickListener, mentionsAdapter.isStickers() ? contentPreviewViewerDelegate : null, themeDelegate)); mentionListView.setTag(2); mentionLayoutManager = new LinearLayoutManager(context) { @Override @@ -5980,7 +6100,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not mentionListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); mentionContainer.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id, new MentionsAdapter.MentionsAdapterDelegate() { + mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id, threadMessageId, new MentionsAdapter.MentionsAdapterDelegate() { @Override public void needChangePanelVisibility(boolean show) { if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) { @@ -6010,7 +6130,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); if (!preferences.getBoolean("secretbot", false)) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("SecretChatContextBotAlert", R.string.SecretChatContextBotAlert)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); @@ -6109,7 +6229,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not processExternalUrl(0, result.content.url, false); } } - })); + }, themeDelegate)); if (!ChatObject.isChannel(currentChat) || currentChat.megagroup) { mentionsAdapter.setBotInfo(botInfo); } @@ -6137,7 +6257,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Object parent = mentionsAdapter.getItemParent(position); if (chatMode == MODE_SCHEDULED) { String query = stickersAdapter.getQuery(); - AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> SendMessagesHelper.getInstance(currentAccount).sendSticker(document, query, dialog_id, replyingMessageObject, getThreadMessage(), parent, null, notify, scheduleDate)); + AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> SendMessagesHelper.getInstance(currentAccount).sendSticker(document, query, dialog_id, replyingMessageObject, getThreadMessage(), parent, null, notify, scheduleDate), themeDelegate); } else { getSendMessagesHelper().sendSticker(document, stickersAdapter.getQuery(), dialog_id, replyingMessageObject, getThreadMessage(), parent, sendAnimationData, true, 0); } @@ -6174,7 +6294,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getSendMessagesHelper().sendMessage((String) object, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, notify, scheduleDate, null); chatActivityEnterView.setFieldText(""); hideFieldPanel(false); - }); + }, themeDelegate); } else { if (checkSlowMode(view)) { return; @@ -6199,7 +6319,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not error = 2; } if (error != 0) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle)); if (error == 1) { builder.setMessage(LocaleController.getString("GameCantSendSecretChat", R.string.GameCantSendSecretChat)); @@ -6215,11 +6335,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not result.type.equals("gif") && (result.document != null || result.content != null) || result.type.equals("video") && (result.document != null/* || result.content_url != null*/))) { ArrayList arrayList = botContextResults = new ArrayList<>(mentionsAdapter.getSearchResultBotContext()); - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); PhotoViewer.getInstance().openPhotoForSelect(arrayList, mentionsAdapter.getItemPosition(position), 3, false, botContextProvider, ChatActivity.this); } else { if (chatMode == MODE_SCHEDULED) { - AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> sendBotInlineResult(result, notify, scheduleDate)); + AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> sendBotInlineResult(result, notify, scheduleDate), themeDelegate); } else { sendBotInlineResult(result, true, 0); } @@ -6247,7 +6367,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } return false; } else { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> mentionsAdapter.clearRecentHashtags()); @@ -6286,7 +6406,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pagedownButtonImage = new ImageView(context); pagedownButtonImage.setImageResource(R.drawable.pagedown); pagedownButtonImage.setScaleType(ImageView.ScaleType.CENTER); - pagedownButtonImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY)); + pagedownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY)); pagedownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0); Drawable drawable; if (Build.VERSION.SDK_INT >= 21) { @@ -6296,12 +6416,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42)); } }); - drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_chat_goDownButton), Theme.getColor(Theme.key_listSelector)); + drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector)); } else { - drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_chat_goDownButton)); + drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton)); } Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42)); drawable = combinedDrawable; @@ -6310,14 +6430,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pagedownButton.addView(pagedownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)); pagedownButton.setContentDescription(LocaleController.getString("AccDescrPageDown", R.string.AccDescrPageDown)); - pagedownButtonCounter = new CounterView(context); + pagedownButtonCounter = new CounterView(context, themeDelegate); pagedownButtonCounter.setReverse(true); pagedownButton.addView(pagedownButtonCounter, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP | Gravity.LEFT)); mentiondownButtonImage = new ImageView(context); mentiondownButtonImage.setImageResource(R.drawable.mentionbutton); mentiondownButtonImage.setScaleType(ImageView.ScaleType.CENTER); - mentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY)); + mentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY)); mentiondownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0); if (Build.VERSION.SDK_INT >= 21) { pagedownButtonImage.setOutlineProvider(new ViewOutlineProvider() { @@ -6326,12 +6446,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42)); } }); - drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_chat_goDownButton), Theme.getColor(Theme.key_listSelector)); + drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector)); } else { - drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), Theme.getColor(Theme.key_chat_goDownButton)); + drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton)); } shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY)); combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0); combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42)); drawable = combinedDrawable; @@ -6343,16 +6463,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not mentiondownButtonCounter.setVisibility(View.INVISIBLE); mentiondownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); mentiondownButtonCounter.setTextSize(13); - mentiondownButtonCounter.setTextColor(Theme.getColor(Theme.key_chat_goDownButtonCounter)); + mentiondownButtonCounter.setTextColor(getThemedColor(Theme.key_chat_goDownButtonCounter)); mentiondownButtonCounter.setGravity(Gravity.CENTER); - mentiondownButtonCounter.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(11.5f), Theme.getColor(Theme.key_chat_goDownButtonCounterBackground))); + mentiondownButtonCounter.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(11.5f), getThemedColor(Theme.key_chat_goDownButtonCounterBackground))); mentiondownButtonCounter.setMinWidth(AndroidUtilities.dp(23)); mentiondownButtonCounter.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(1), AndroidUtilities.dp(8), 0); mentiondownButton.addView(mentiondownButtonCounter, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); mentiondownButton.setContentDescription(LocaleController.getString("AccDescrMentionDown", R.string.AccDescrMentionDown)); - contentView.addView(fragmentLocationContextView = new FragmentContextView(context, this, true), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0)); - contentView.addView(fragmentContextView = new FragmentContextView(context, this, false) { + contentView.addView(fragmentLocationContextView = new FragmentContextView(context, this, true, themeDelegate), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0)); + contentView.addView(fragmentContextView = new FragmentContextView(context, this, false, themeDelegate) { @Override protected void playbackSpeedChanged(float value) { if (Math.abs(value - 1.0f) < 0.001f || Math.abs(value - 1.8f) < 0.001f) { @@ -6367,14 +6487,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not fragmentContextView.setSupportsCalls(false); } - messagesSearchListView = new RecyclerListView(context); - messagesSearchListView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + messagesSearchListView = new RecyclerListView(context, themeDelegate); + messagesSearchListView.setBackgroundColor(getThemedColor(Theme.key_windowBackgroundWhite)); LinearLayoutManager messagesSearchLayoutManager = new LinearLayoutManager(context); messagesSearchLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); messagesSearchListView.setLayoutManager(messagesSearchLayoutManager); messagesSearchListView.setVisibility(View.GONE); messagesSearchListView.setAlpha(0.0f); - messagesSearchListView.setAdapter(messagesSearchAdapter = new MessagesSearchAdapter(context)); + messagesSearchListView.setAdapter(messagesSearchAdapter = new MessagesSearchAdapter(context, themeDelegate)); contentView.addView(messagesSearchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48)); messagesSearchListView.setOnItemClickListener((view, position) -> { getMediaDataController().jumpToSearchedMessage(classGuid, position); @@ -6391,7 +6511,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); - topUndoView = new UndoView(context, this, true) { + topUndoView = new UndoView(context, this, true, themeDelegate) { @Override public void didPressUrl(CharacterStyle span) { didPressMessageUrl(span, false, null, null); @@ -6419,7 +6539,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not overlayView.setVisibility(View.GONE); contentView.setClipChildren(false); - instantCameraView = new InstantCameraView(context, this); + instantCameraView = new InstantCameraView(context, this, themeDelegate); contentView.addView(instantCameraView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); bottomMessagesActionContainer = new FrameLayout(context) { @@ -6428,7 +6548,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground)); } }; bottomMessagesActionContainer.setVisibility(View.INVISIBLE); @@ -6437,7 +6557,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not contentView.addView(bottomMessagesActionContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); bottomMessagesActionContainer.setOnTouchListener((v, event) -> true); - chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true) { + chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true, themeDelegate) { int lastContentViewHeight; int messageEditTextPredrawHeigth; @@ -7029,7 +7149,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not }; replyLineView = new View(context); - replyLineView.setBackgroundColor(Theme.getColor(Theme.key_chat_replyPanelLine)); + replyLineView.setBackgroundColor(getThemedColor(Theme.key_chat_replyPanelLine)); chatActivityEnterView.addTopView(chatActivityEnterTopView, replyLineView, 48); final FrameLayout replyLayout = new FrameLayout(context); @@ -7055,16 +7175,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not }); replyIconImageView = new ImageView(context); - replyIconImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_replyPanelIcons), PorterDuff.Mode.MULTIPLY)); + replyIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelIcons), PorterDuff.Mode.MULTIPLY)); replyIconImageView.setScaleType(ImageView.ScaleType.CENTER); replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT)); replyCloseImageView = new ImageView(context); - replyCloseImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_replyPanelClose), PorterDuff.Mode.MULTIPLY)); + replyCloseImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelClose), PorterDuff.Mode.MULTIPLY)); replyCloseImageView.setImageResource(R.drawable.input_clear); replyCloseImageView.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { - replyCloseImageView.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(18))); + replyCloseImageView.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(18))); } chatActivityEnterTopView.addView(replyCloseImageView, LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0)); replyCloseImageView.setOnClickListener(v -> { @@ -7077,18 +7197,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyNameTextView = new SimpleTextView(context); replyNameTextView.setTextSize(14); - replyNameTextView.setTextColor(Theme.getColor(Theme.key_chat_replyPanelName)); + replyNameTextView.setTextColor(getThemedColor(Theme.key_chat_replyPanelName)); replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); replyLayout.addView(replyNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0)); replyObjectTextView = new SimpleTextView(context); replyObjectTextView.setTextSize(14); - replyObjectTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + replyObjectTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); replyLayout.addView(replyObjectTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0)); replyObjectHintTextView = new SimpleTextView(context); replyObjectHintTextView.setTextSize(14); - replyObjectHintTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + replyObjectHintTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); replyObjectHintTextView.setText(LocaleController.getString("TapForForwardingOptions", R.string.TapForForwardingOptions)); replyObjectHintTextView.setAlpha(0f); replyLayout.addView(replyObjectHintTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0)); @@ -7127,9 +7247,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public void updateColors() { final int leftInset = firstButton ? AndroidUtilities.dp(14) : 0; - setBackground(Theme.createCircleSelectorDrawable(Theme.getColor(Theme.key_chat_replyPanelName) & 0x19ffffff, leftInset, 0)); - getImageView().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_replyPanelName), PorterDuff.Mode.MULTIPLY)); - getTextView().setTextColor(Theme.getColor(Theme.key_chat_replyPanelName)); + setBackground(Theme.createCircleSelectorDrawable(getThemedColor(Theme.key_chat_replyPanelName) & 0x19ffffff, leftInset, 0)); + getImageView().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelName), PorterDuff.Mode.MULTIPLY)); + getTextView().setTextColor(getThemedColor(Theme.key_chat_replyPanelName)); } }; button.setOrientation(LinearLayout.HORIZONTAL); @@ -7165,15 +7285,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not }); } - stickersListView = new RecyclerListView(context) { + stickersListView = new RecyclerListView(context, themeDelegate) { @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView, 0, contentPreviewViewerDelegate); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView, 0, contentPreviewViewerDelegate, themeDelegate); return super.onInterceptTouchEvent(event) || result; } }; stickersListView.setTag(3); - stickersListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersListView, 0, stickersOnItemClickListener, contentPreviewViewerDelegate)); + stickersListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersListView, 0, stickersOnItemClickListener, contentPreviewViewerDelegate, themeDelegate)); stickersListView.setDisallowInterceptTouchEvents(true); LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); @@ -7185,7 +7305,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not stickersPanelArrow = new ImageView(context); stickersPanelArrow.setImageResource(R.drawable.stickers_back_arrow); - stickersPanelArrow.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY)); + stickersPanelArrow.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY)); stickersPanel.addView(stickersPanelArrow, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 53, 0)); searchContainer = new FrameLayout(context) { @@ -7196,7 +7316,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); } - canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground)); } @Override @@ -7222,7 +7342,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchAsListTogglerView = new View(context); searchAsListTogglerView.setOnTouchListener((v, event) -> getMediaDataController().getFoundMessageObjects().size() <= 1); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - searchAsListTogglerView.setBackground(Theme.getSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), false)); + searchAsListTogglerView.setBackground(Theme.getSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false)); } searchAsListTogglerView.setOnClickListener(v -> { if (getMediaDataController().getFoundMessageObjects().size() > 1) { @@ -7241,8 +7361,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchUpButton = new ImageView(context); searchUpButton.setScaleType(ImageView.ScaleType.CENTER); searchUpButton.setImageResource(R.drawable.msg_go_up); - searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); - searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1)); + searchUpButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); + searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1)); searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0)); searchUpButton.setOnClickListener(view -> { getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1, threadMessageId, searchingUserMessages, searchingChatMessages); @@ -7258,8 +7378,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchDownButton = new ImageView(context); searchDownButton.setScaleType(ImageView.ScaleType.CENTER); searchDownButton.setImageResource(R.drawable.msg_go_down); - searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); - searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1)); + searchDownButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); + searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1)); searchContainer.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0)); searchDownButton.setOnClickListener(view -> { getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2, threadMessageId, searchingUserMessages, searchingChatMessages); @@ -7271,8 +7391,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchUserButton = new ImageView(context); searchUserButton.setScaleType(ImageView.ScaleType.CENTER); searchUserButton.setImageResource(R.drawable.msg_usersearch); - searchUserButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); - searchUserButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1)); + searchUserButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); + searchUserButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1)); searchContainer.addView(searchUserButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0)); searchUserButton.setOnClickListener(view -> { mentionLayoutManager.setReverseLayout(true); @@ -7293,19 +7413,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchCalendarButton = new ImageView(context); searchCalendarButton.setScaleType(ImageView.ScaleType.CENTER); searchCalendarButton.setImageResource(R.drawable.msg_calendar); - searchCalendarButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); - searchCalendarButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1)); + searchCalendarButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY)); + searchCalendarButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1)); searchContainer.addView(searchCalendarButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); searchCalendarButton.setOnClickListener(view -> { if (getParentActivity() == null) { return; } AndroidUtilities.hideKeyboard(searchItem.getSearchField()); - showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, this::jumpToDate).create()); + showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, this::jumpToDate, themeDelegate).create()); }); searchCalendarButton.setContentDescription(LocaleController.getString("JumpToDate", R.string.JumpToDate)); - searchCountText = new SearchCounterView(context); + searchCountText = new SearchCounterView(context, themeDelegate); searchCountText.setGravity(Gravity.LEFT); searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 0, 108, 0)); @@ -7315,7 +7435,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground)); } }; bottomOverlay.setWillNotDraw(false); @@ -7332,7 +7452,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not bottomOverlayText.setMaxLines(2); bottomOverlayText.setEllipsize(TextUtils.TruncateAt.END); bottomOverlayText.setLineSpacing(AndroidUtilities.dp(2), 1); - bottomOverlayText.setTextColor(Theme.getColor(Theme.key_chat_secretChatStatusText)); + bottomOverlayText.setTextColor(getThemedColor(Theme.key_chat_secretChatStatusText)); bottomOverlay.addView(bottomOverlayText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 14, 0, 14, 0)); bottomOverlayChat = new FrameLayout(context) { @@ -7349,7 +7469,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight(); Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint); + canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground)); } }; bottomOverlayChat.setWillNotDraw(false); @@ -7392,7 +7512,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getSendMessagesHelper().sendMessage("/start", dialog_id, null, null, null, false, null, null, null, true, 0, null); } } else { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> getMessagesController().unblockPeer(currentUser.id)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); @@ -7434,14 +7554,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getNotificationCenter().postNotificationName(NotificationCenter.closeChats); finishFragment(); getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, dialog_id, currentUser, currentChat, param); - }); + }, themeDelegate); } } }); - bottomOverlayProgress = new RadialProgressView(context); + bottomOverlayProgress = new RadialProgressView(context, themeDelegate); bottomOverlayProgress.setSize(AndroidUtilities.dp(22)); - bottomOverlayProgress.setProgressColor(Theme.getColor(Theme.key_chat_fieldOverlayText)); + bottomOverlayProgress.setProgressColor(getThemedColor(Theme.key_chat_fieldOverlayText)); bottomOverlayProgress.setVisibility(View.INVISIBLE); bottomOverlayProgress.setScaleX(0.1f); bottomOverlayProgress.setScaleY(0.1f); @@ -7449,7 +7569,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not bottomOverlayChat.addView(bottomOverlayProgress, LayoutHelper.createFrame(30, 30, Gravity.CENTER)); bottomOverlayImage = new ImageView(context); - int color = Theme.getColor(Theme.key_chat_fieldOverlayText); + int color = getThemedColor(Theme.key_chat_fieldOverlayText); bottomOverlayImage.setImageResource(R.drawable.log_info); bottomOverlayImage.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); bottomOverlayImage.setScaleType(ImageView.ScaleType.CENTER); @@ -7465,12 +7585,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyButton.setGravity(Gravity.CENTER_VERTICAL); replyButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); replyButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(21), 0); - replyButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 3)); - replyButton.setTextColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon)); + replyButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3)); + replyButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon)); replyButton.setCompoundDrawablePadding(AndroidUtilities.dp(7)); replyButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); Drawable image = context.getResources().getDrawable(R.drawable.input_reply).mutate(); - image.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY)); + image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY)); replyButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null); replyButton.setOnClickListener(v -> { MessageObject messageObject = null; @@ -7497,23 +7617,23 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not forwardButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); forwardButton.setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0); forwardButton.setCompoundDrawablePadding(AndroidUtilities.dp(6)); - forwardButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 3)); - forwardButton.setTextColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon)); + forwardButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3)); + forwardButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon)); forwardButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); image = context.getResources().getDrawable(R.drawable.input_forward).mutate(); - image.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY)); + image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY)); forwardButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null); forwardButton.setOnClickListener(v -> openForward()); bottomMessagesActionContainer.addView(forwardButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP)); contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM)); contentView.addView(messageEnterTransitionContainer = new MessageEnterTransitionContainer(context, currentAccount)); - undoView = new UndoView(context, this); + undoView = new UndoView(context, this, false, themeDelegate); undoView.setAdditionalTranslationY(AndroidUtilities.dp(51)); contentView.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); if (currentChat != null) { - slowModeHint = new HintView(getParentActivity(), 2); + slowModeHint = new HintView(getParentActivity(), 2, themeDelegate); slowModeHint.setAlpha(0.0f); slowModeHint.setVisibility(View.INVISIBLE); contentView.addView(slowModeHint, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 19, 0, 19, 0)); @@ -7583,17 +7703,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not contentView.addView(fireworksOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); textSelectionHelper.setParentView(chatListView); - int searchFromUserId = getArguments().getInt("search_from_user_id", 0); - int searchFromChatId = getArguments().getInt("search_from_chat_id", 0); + long searchFromUserId = getArguments().getInt("search_from_user_id", 0); + long searchFromChatId = getArguments().getInt("search_from_chat_id", 0); if (searchFromUserId != 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(searchFromUserId); + TLRPC.User user = getMessagesController().getUser(searchFromUserId); if (user != null) { openSearchWithText(""); searchUserButton.callOnClick(); searchUserMessages(user, null); } } else if (searchFromChatId != 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(searchFromChatId); + TLRPC.Chat chat = getMessagesController().getChat(searchFromChatId); if (chat != null) { openSearchWithText(""); searchUserButton.callOnClick(); @@ -7703,21 +7823,29 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not topBottom[1] = chatListView.getBottom(); topBottom[0] = chatListView.getTop() + chatListViewPaddingTop - AndroidUtilities.dp(4); }); + + emojiAnimationsOverlay = new EmojiAnimationsOverlay(ChatActivity.this, contentView, chatListView, currentAccount, dialog_id, threadMessageId); return fragmentView; } private void openForwardingPreview() { boolean keyboardVisible = chatActivityEnterView.isKeyboardVisible(); - forwardingPreviewView = new ForwardingPreviewView(contentView.getContext(), forwardingMessages, currentUser, currentChat, currentAccount) { + forwardingPreviewView = new ForwardingPreviewView(contentView.getContext(), forwardingMessages, currentUser, currentChat, currentAccount, themeDelegate) { @Override protected void onDismiss(boolean canShowKeyboard) { checkShowBlur(true); - ArrayList selectedMessage = new ArrayList<>(); - forwardingMessages.getSelectedMessages(selectedMessage); - showFieldPanelForForward(true, selectedMessage); + if (forwardingMessages != null) { + ArrayList selectedMessage = new ArrayList<>(); + forwardingMessages.getSelectedMessages(selectedMessage); + showFieldPanelForForward(true, selectedMessage); + } if (keyboardVisible && canShowKeyboard) { - AndroidUtilities.runOnUIThread(() -> chatActivityEnterView.openKeyboard(), 50); + AndroidUtilities.runOnUIThread(() -> { + if (chatActivityEnterView != null) { + chatActivityEnterView.openKeyboard(); + } + }, 50); } AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); @@ -7782,7 +7910,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } Bundle bundle = new Bundle(); - bundle.putInt("chat_id", pullingDownDrawable.getChatId()); + bundle.putLong("chat_id", pullingDownDrawable.getChatId()); bundle.putInt("dialog_folder_id", pullingDownDrawable.dialogFolderId); bundle.putInt("dialog_filter_id", pullingDownDrawable.dialogFilterId); SharedPreferences sharedPreferences = MessagesController.getNotificationsSettings(currentAccount); @@ -7827,7 +7955,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not searchingForUser = false; String from = LocaleController.getString("SearchFrom", R.string.SearchFrom); Spannable spannable = new SpannableString(from + " " + name); - spannable.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_actionBarDefaultSubtitle)), from.length() + 1, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + spannable.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_actionBarDefaultSubtitle)), from.length() + 1, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); searchItem.setSearchFieldCaption(spannable); mentionsAdapter.searchUsernameOrHashtag(null, 0, null, false, true); searchItem.setSearchFieldHint(null); @@ -7860,7 +7988,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not text = MessageObject.replaceWithLink(text, "un1", user); onClickListener = (v) -> { Bundle args = new Bundle(); - args.putInt("user_id", chatInviterId); + args.putLong("user_id", chatInviterId); presentFragment(new ProfileActivity(args)); }; } @@ -7873,8 +8001,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not infoTopViewAnimator.cancel(); } if (infoTopView == null) { - infoTopView = new ChatActionCell(contentView.getContext()); + infoTopView = new ChatActionCell(contentView.getContext(), themeDelegate); infoTopView.setCustomText(text); + infoTopView.setInvalidateColors(true); infoTopView.setOnClickListener(onClickListener); contentView.addView(infoTopView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0, 0, 0)); } @@ -7910,6 +8039,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } private void openAnotherForward() { + if (forwardingMessages == null) { + return; + } boolean fewSenders = false; long lastPeerId = 0; long dialogId = 0; @@ -7923,14 +8055,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not break; } } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setButtonsVertical(true); String message; if (dialogId > 0) { - TLRPC.User user = getMessagesController().getUser((int) dialogId); + TLRPC.User user = getMessagesController().getUser(dialogId); message = LocaleController.formatString("CancelForwardPrivate", R.string.CancelForwardPrivate, LocaleController.formatPluralString("MessagesBold", forwardingMessages.messages.size()), ContactsController.formatName(user.first_name, user.last_name)); } else { - TLRPC.Chat chat = getMessagesController().getChat(-(int) dialogId); + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); message = LocaleController.formatString("CancelForwardChat", R.string.CancelForwardChat, LocaleController.formatPluralString("MessagesBold", forwardingMessages.messages.size()), chat.title); } builder.setMessage(AndroidUtilities.replaceTags(message)); @@ -8002,7 +8134,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not showDialog(dialog); TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { - button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2)); + button.setTextColor(getThemedColor(Theme.key_dialogTextRed2)); } } @@ -8012,9 +8144,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } Bundle bundle = new Bundle(); if (currentChat != null) { - bundle.putInt("chat_id", currentChat.id); + bundle.putLong("chat_id", currentChat.id); } else { - bundle.putInt("user_id", currentUser.id); + bundle.putLong("user_id", currentUser.id); } bundle.putInt("chatMode", MODE_PINNED); ChatActivity fragment = new ChatActivity(bundle); @@ -8088,7 +8220,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (tag == pinBullerinTag) { pinBulletin = null; } - }); + }, themeDelegate); } else { MessageObject messageObject = pinnedMessageObjects.get(currentPinnedMessageId); if (messageObject == null) { @@ -8112,7 +8244,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (show && (blurredView == null || blurredView.getTag() == null)) { if (blurredView == null) { - blurredView = new BluredView(fragmentView.getContext(), fragmentView) { + blurredView = new BluredView(fragmentView.getContext(), fragmentView, themeDelegate) { @Override public void setAlpha(float alpha) { super.setAlpha(alpha); @@ -8616,7 +8748,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } private void sendBotInlineResult(TLRPC.BotInlineResult result, boolean notify, int scheduleDate) { - int uid = mentionsAdapter.getContextBotId(); + long uid = mentionsAdapter.getContextBotId(); HashMap params = new HashMap<>(); params.put("id", result.id); params.put("query_id", "" + result.query_id); @@ -8716,7 +8848,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not break; } } - } else if ((int) dialog_id != 0) { + } else if (!DialogObject.isEncryptedDialog(dialog_id)) { int scrollDirection = RecyclerAnimationScrollHelper.SCROLL_DIRECTION_UNSET; int end = chatLayoutManager.findLastVisibleItemPosition(); for (int i = chatLayoutManager.findFirstVisibleItemPosition(); i <= end; i++) { @@ -8738,7 +8870,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not progressDialog.dismiss(); } updatePinnedListButton(false); - progressDialog = new AlertDialog(getParentActivity(), 3); + progressDialog = new AlertDialog(getParentActivity(), 3, themeDelegate); progressDialog.setOnCancelListener(postponedScrollCancelListener); progressDialog.showDelayed(1000); @@ -8746,7 +8878,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not waitingForLoad.add(lastLoadIndex); postponedScrollMessageId = 0; postponedScrollIsCanceled = false; - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, date, true, 0, classGuid, 4, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, date, true, 0, classGuid, 4, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); floatingDateView.setAlpha(0.0f); floatingDateView.setTag(null); } @@ -8766,7 +8898,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getMessagesController().sendBotStart(currentUser, object.start_param); } else { Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); args.putString("inline_query", object.start_param); args.putLong("inline_return", dialog_id); if (!getMessagesController().checkCanOpenChat(args, ChatActivity.this)) { @@ -8781,7 +8913,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (chatAttachAlert == null) { - chatAttachAlert = new ChatAttachAlert(getParentActivity(), this, false, false) { + chatAttachAlert = new ChatAttachAlert(getParentActivity(), this, false, false, themeDelegate) { @Override public void dismissInternal() { if (chatAttachAlert.isShowing()) { @@ -9033,9 +9165,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null) { bundle.putInt("enc_id", currentEncryptedChat.id); } else if (currentChat != null) { - bundle.putInt("chat_id", currentChat.id); + bundle.putLong("chat_id", currentChat.id); } else { - bundle.putInt("user_id", currentUser.id); + bundle.putLong("user_id", currentUser.id); } bundle.putInt("chatMode", MODE_SCHEDULED); ChatActivity fragment = new ChatActivity(bundle); @@ -9117,7 +9249,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else if (!show) { stickersPanel.setVisibility(View.GONE); } - })); + }, themeDelegate)); stickersListView.setOnItemClickListener(stickersOnItemClickListener = (view, position) -> { Object item = stickersAdapter.getItem(position); if (item instanceof String) { @@ -9130,7 +9262,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } public void shareMyContact(int type, MessageObject messageObject) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("ShareYouPhoneNumberTitle", R.string.ShareYouPhoneNumberTitle)); if (currentUser != null) { if (currentUser.bot) { @@ -9173,7 +9305,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (index == -1) { return; } - voiceHintTextView = new HintView(getParentActivity(), 9); + voiceHintTextView = new HintView(getParentActivity(), 9, themeDelegate); frameLayout.addView(voiceHintTextView, index + 1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); } if (hide) { @@ -9243,7 +9375,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (timerHintView == null) { - timerHintView = new HintView(getParentActivity(), 7, true); + timerHintView = new HintView(getParentActivity(), 7, true, themeDelegate); timerHintView.setAlpha(0.0f); timerHintView.setVisibility(View.INVISIBLE); timerHintView.setShowingDuration(4000); @@ -9268,7 +9400,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (searchAsListHint == null) { - searchAsListHint = new HintView(getParentActivity(), HintView.TYPE_SEARCH_AS_LIST); + searchAsListHint = new HintView(getParentActivity(), HintView.TYPE_SEARCH_AS_LIST, themeDelegate); searchAsListHint.setAlpha(0.0f); searchAsListHint.setVisibility(View.INVISIBLE); searchAsListHint.setText(LocaleController.getString("TapToViewAsList", R.string.TapToViewAsList)); @@ -9297,7 +9429,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (mediaBanTooltip == null) { - mediaBanTooltip = new HintView(getParentActivity(), 9); + mediaBanTooltip = new HintView(getParentActivity(), 9, themeDelegate); mediaBanTooltip.setVisibility(View.GONE); frameLayout.addView(mediaBanTooltip, index + 1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); } @@ -9329,7 +9461,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (index == -1) { return; } - noSoundHintView = new HintView(getParentActivity(), 0); + noSoundHintView = new HintView(getParentActivity(), 0, themeDelegate); noSoundHintView.setShowingDuration(10000); frameLayout.addView(noSoundHintView, index + 1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 19, 0, 19, 0)); noSoundHintView.setAlpha(0.0f); @@ -9376,7 +9508,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (index == -1) { return; } - checksHintView = new ChecksHintView(getParentActivity()); + checksHintView = new ChecksHintView(getParentActivity(), themeDelegate); frameLayout.addView(checksHintView, index + 1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); checksHintView.setAlpha(0.0f); checksHintView.setVisibility(View.INVISIBLE); @@ -9411,7 +9543,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (index == -1) { return; } - forwardHintView = new HintView(getParentActivity(), 1); + forwardHintView = new HintView(getParentActivity(), 1, themeDelegate); frameLayout.addView(forwardHintView, index + 1, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 19, 0, 19, 0)); forwardHintView.setAlpha(0.0f); forwardHintView.setVisibility(View.INVISIBLE); @@ -9443,7 +9575,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not textSelectionHintWasShowed = true; SharedConfig.increaseTextSelectionHintShowed(); if (textSelectionHint == null) { - textSelectionHint = new TextSelectionHint(getParentActivity()) { + textSelectionHint = new TextSelectionHint(getParentActivity(), themeDelegate) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { @@ -9498,8 +9630,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not frameLayout.addView(emojiButtonRed, index + 1, LayoutHelper.createFrame(10, 10, Gravity.BOTTOM | Gravity.LEFT, 30, 0, 0, 27)); gifHintTextView = new TextView(getParentActivity()); - gifHintTextView.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(3), Theme.getColor(Theme.key_chat_gifSaveHintBackground))); - gifHintTextView.setTextColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); + gifHintTextView.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(3), getThemedColor(Theme.key_chat_gifSaveHintBackground))); + gifHintTextView.setTextColor(getThemedColor(Theme.key_chat_gifSaveHintText)); gifHintTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); gifHintTextView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(7), AndroidUtilities.dp(8), AndroidUtilities.dp(7)); gifHintTextView.setText(LocaleController.getString("TapHereGifs", R.string.TapHereGifs)); @@ -9828,24 +9960,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not loading = true; waitingForLoad.add(lastLoadIndex); if (messagesByDays.size() != 0) { - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, maxMessageId[0], 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, maxMessageId[0], 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } else { - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } } else if (mergeDialogId != 0 && !endReached[1]) { loading = true; waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(mergeDialogId, 0, false, 50, maxMessageId[1], 0, !cacheEndReached[1], minDate[1], classGuid, 0, 0, false, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(mergeDialogId, 0, false, 50, maxMessageId[1], 0, !cacheEndReached[1], minDate[1], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } } if (visibleItemCount > 0 && !loadingForward && firstVisibleItem <= 10) { if (mergeDialogId != 0 && !forwardEndReached[1]) { waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(mergeDialogId, 0, false, 50, minMessageId[1], 0, true, maxDate[1], classGuid, 1, 0, false, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(mergeDialogId, 0, false, 50, minMessageId[1], 0, true, maxDate[1], classGuid, 1, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); loadingForward = true; } else if (!forwardEndReached[0]) { waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, minMessageId[0], 0, true, maxDate[0], classGuid, 1, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 50, minMessageId[0], 0, true, maxDate[0], classGuid, 1, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); loadingForward = true; } } @@ -10149,7 +10281,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null && messagesController.secretWebpagePreview == 2) { AndroidUtilities.runOnUIThread(() -> { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> { messagesController.secretWebpagePreview = 1; @@ -10212,7 +10344,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if ((scheduleDate != 0) == (chatMode == MODE_SCHEDULED)) { waitingForSendingMessageLoad = true; } - AlertsCreator.showSendMediaAlert(getSendMessagesHelper().sendMessage(arrayList, dialog_id, fromMyName, hideCaption, notify, scheduleDate), this); + AlertsCreator.showSendMediaAlert(getSendMessagesHelper().sendMessage(arrayList, dialog_id, fromMyName, hideCaption, notify, scheduleDate), this, themeDelegate); } public boolean shouldShowImport() { @@ -10425,7 +10557,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } chatActivityEnterView.setForceShowSendButton(true, false); - ArrayList uids = new ArrayList<>(); + ArrayList uids = new ArrayList<>(); replyIconImageView.setImageResource(R.drawable.msg_panel_forward); replyIconImageView.setContentDescription(LocaleController.getString("AccDescrForwarding", R.string.AccDescrForwarding)); replyCloseImageView.setContentDescription(LocaleController.getString("AccDescrCancelForward", R.string.AccDescrCancelForward)); @@ -10444,7 +10576,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int type = object.isAnimatedEmoji() || object.isDice() ? 0 : object.type; for (int a = 1; a < messageObjectsToForward.size(); a++) { object = messageObjectsToForward.get(a); - int uid; + long uid; if (object.isFromUser()) { uid = object.messageOwner.from_id.user_id; } else { @@ -10464,7 +10596,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } StringBuilder userNames = new StringBuilder(); for (int a = 0; a < uids.size(); a++) { - Integer uid = uids.get(a); + Long uid = uids.get(a); TLRPC.Chat chat = null; TLRPC.User user = null; if (uid > 0) { @@ -10599,6 +10731,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) replyNameTextView.getLayoutParams(); FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) replyObjectTextView.getLayoutParams(); + FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) replyObjectHintTextView.getLayoutParams(); int cacheType = 1; int size = 0; @@ -10631,9 +10764,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyImageLocation = null; replyImageLocationObject = null; replyImageView.setVisibility(View.INVISIBLE); - layoutParams1.leftMargin = layoutParams2.leftMargin = AndroidUtilities.dp(52); + layoutParams1.leftMargin = layoutParams2.leftMargin = layoutParams3.leftMargin = AndroidUtilities.dp(52); } else { - if (thumbMediaMessageObject != null && thumbMediaMessageObject.isRoundVideo()) { + if (thumbMediaMessageObject.isRoundVideo()) { replyImageView.setRoundRadius(AndroidUtilities.dp(17)); } else { replyImageView.setRoundRadius(AndroidUtilities.dp(2)); @@ -10645,10 +10778,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not replyImageLocationObject = photoSizeObject; replyImageView.setImage(ImageLocation.getForObject(replyImageLocation, photoSizeObject), "50_50", ImageLocation.getForObject(thumbPhotoSize, photoSizeObject), "50_50_b", null, size, cacheType, thumbMediaMessageObject); replyImageView.setVisibility(View.VISIBLE); - layoutParams1.leftMargin = layoutParams2.leftMargin = AndroidUtilities.dp(96); + layoutParams1.leftMargin = layoutParams2.leftMargin = layoutParams3.leftMargin = AndroidUtilities.dp(96); } replyNameTextView.setLayoutParams(layoutParams1); replyObjectTextView.setLayoutParams(layoutParams2); + replyObjectTextView.setLayoutParams(layoutParams3); chatActivityEnterView.showTopView(true, openKeyboard); } else { if (replyingMessageObject == null && forwardingMessages == null && foundWebPage == null && editingMessageObject == null && !chatActivityEnterView.isTopViewVisible()) { @@ -10727,7 +10861,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null) { getMessagesController().markMessageAsRead(dialog_id, messageObject.messageOwner.random_id, messageObject.messageOwner.ttl); } else { - getMessagesController().markMessageAsRead(messageObject.getId(), ChatObject.isChannel(currentChat) ? currentChat.id : 0, null, messageObject.messageOwner.ttl, 0); + getMessagesController().markMessageAsRead2(dialog_id, messageObject.getId(), null, messageObject.messageOwner.ttl, 0); } return null; } else { @@ -10735,7 +10869,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null) { getMessagesController().markMessageAsRead(dialog_id, messageObject.messageOwner.random_id, messageObject.messageOwner.ttl); } else { - getMessagesController().markMessageAsRead(messageObject.getId(), ChatObject.isChannel(currentChat) ? currentChat.id : 0, null, messageObject.messageOwner.ttl, 0); + getMessagesController().markMessageAsRead2(dialog_id, messageObject.getId(), null, messageObject.messageOwner.ttl, 0); } }; } @@ -10810,7 +10944,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not progressDialog.dismiss(); } updatePinnedListButton(false); - progressDialog = new AlertDialog(getParentActivity(), 3); + progressDialog = new AlertDialog(getParentActivity(), 3, themeDelegate); progressDialog.setOnCancelListener(postponedScrollCancelListener); progressDialog.showDelayed(1000); @@ -10820,7 +10954,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not waitingForLoad.clear(); waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, true, 0, classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, true, 0, classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } } @@ -10982,9 +11116,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not threadMessageVisible = firstLoading; Integer currentReadMaxId; - long threadId = threadMessageId; + int threadId = threadMessageId; if (threadId != 0 && currentChat != null) { - threadId |= ((long) currentChat.id) << 32; currentReadMaxId = replyMaxReadId; } else { currentReadMaxId = getMessagesController().dialogs_read_inbox_max.get(dialog_id); @@ -11368,7 +11501,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getNotificationsController().updateServerNotificationsSettings(dialog_id); getNotificationsController().removeNotificationsForDialog(dialog_id); } else { - BottomSheet alert = AlertsCreator.createMuteAlert(this, dialog_id); + BottomSheet alert = AlertsCreator.createMuteAlert(this, dialog_id, themeDelegate); alert.setCalcMandatoryInsets(isKeyboardVisible()); showDialog(alert); } @@ -11384,7 +11517,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } getNotificationsController().updateServerNotificationsSettings(dialog_id); if (!instant) { - BulletinFactory.createMuteBulletin(this, false).show(); + BulletinFactory.createMuteBulletin(this, false, themeDelegate).show(); } } } @@ -11396,7 +11529,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private int getHeightForMessage(MessageObject object) { if (dummyMessageCell == null) { - dummyMessageCell = new ChatMessageCell(getParentActivity()); + dummyMessageCell = new ChatMessageCell(getParentActivity(), themeDelegate); } dummyMessageCell.isChat = currentChat != null || UserObject.isUserSelf(currentUser); dummyMessageCell.isBot = currentUser != null && currentUser.bot; @@ -11580,7 +11713,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not showPinnedProgress(forceNextPinnedMessageId != 0); - progressDialog = new AlertDialog(getParentActivity(), 3); + progressDialog = new AlertDialog(getParentActivity(), 3, themeDelegate); progressDialog.setOnShowListener(dialogInterface -> showPinnedProgress(false)); progressDialog.setOnCancelListener(postponedScrollCancelListener); progressDialog.showDelayed(400); @@ -11598,7 +11731,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not postponedScrollToLastMessageQueryIndex = lastLoadIndex; postponedScrollMinMessageId = minMessageId[0]; postponedScrollMessageId = id; - getMessagesController().loadMessages(loadIndex == 0 ? dialog_id : mergeDialogId, 0, false, isThreadChat() || AndroidUtilities.isTablet() ? 30 : 20, startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(loadIndex == 0 ? dialog_id : mergeDialogId, 0, false, isThreadChat() || AndroidUtilities.isTablet() ? 30 : 20, startLoadFromMessageId, 0, true, 0, classGuid, 3, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } else { View child = chatListView.getChildAt(0); if (child != null && child.getTop() <= 0) { @@ -11840,7 +11973,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (grantResults != null && grantResults.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("PermissionNoAudioVideo", R.string.PermissionNoAudioVideo)); builder.setNegativeButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialog, which) -> { @@ -12496,8 +12629,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (avatarContainer == null || chatMode != 0) { return; } - Drawable rightIcon = getMessagesController().isDialogMuted(dialog_id) ? Theme.chat_muteIconDrawable : null; - avatarContainer.setTitleIcons(currentEncryptedChat != null ? Theme.chat_lockIconDrawable : null, !UserObject.isReplyUser(currentUser) && !isThreadChat() ? rightIcon : null); + Drawable rightIcon = getMessagesController().isDialogMuted(dialog_id) ? getThemedDrawable(Theme.key_drawable_muteIconDrawable) : null; + avatarContainer.setTitleIcons(currentEncryptedChat != null ? getThemedDrawable(Theme.key_drawable_lockIconDrawable) : null, !UserObject.isReplyUser(currentUser) && !isThreadChat() ? rightIcon : null); if (muteItem != null) { if (rightIcon != null) { muteItem.setTextAndIcon(LocaleController.getString("UnmuteNotifications", R.string.UnmuteNotifications), R.drawable.msg_unmute); @@ -12529,7 +12662,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public void openVideoEditor(String videoPath, String caption) { if (getParentActivity() != null) { final Bitmap thumb = SendMessagesHelper.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND); - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); final ArrayList cameraPhoto = new ArrayList<>(); MediaController.PhotoEntry entry = new MediaController.PhotoEntry(0, 0, 0, videoPath, 0, true, 0, 0, 0); entry.caption = caption; @@ -12578,7 +12711,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (!file.exists()) { return; } - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); final ArrayList photos = new ArrayList<>(); final MediaController.PhotoEntry entry = new MediaController.PhotoEntry(0, 0, 0, file.getAbsolutePath(), 0, object.isVideo(), 0, 0, 0); entry.caption = chatActivityEnterView.getFieldText(); @@ -12698,7 +12831,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParentActivity() == null) { return; } - BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("UnsupportedAttachment", R.string.UnsupportedAttachment)).show(); + BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("UnsupportedAttachment", R.string.UnsupportedAttachment), themeDelegate).show(); } private void fillEditingMediaWithCaption(CharSequence caption, ArrayList entities) { @@ -12784,7 +12917,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> { fillEditingMediaWithCaption(null, null); SendMessagesHelper.prepareSendingPhoto(getAccountInstance(), null, uri, dialog_id, replyingMessageObject, getThreadMessage(), null, null, null, null, 0, editingMessageObject, notify, scheduleDate); - }); + }, themeDelegate); } else { fillEditingMediaWithCaption(null, null); SendMessagesHelper.prepareSendingPhoto(getAccountInstance(), null, uri, dialog_id, replyingMessageObject, getThreadMessage(), null, null, null, null, 0, editingMessageObject, true, 0); @@ -12863,7 +12996,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } int index = waitingForLoad.indexOf(queryLoadIndex); - int currentUserId = getUserConfig().getClientUserId(); + long currentUserId = getUserConfig().getClientUserId(); int mode = (Integer) args[14]; boolean isCache = (Boolean) args[3]; boolean postponedScroll = postponedScrollToLastMessageQueryIndex > 0 && queryLoadIndex == postponedScrollToLastMessageQueryIndex; @@ -12875,7 +13008,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatMode == MODE_SCHEDULED && mode == MODE_SCHEDULED && !isCache) { waitingForReplyMessageLoad = true; waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, AndroidUtilities.isTablet() ? 30 : 20, 0, 0, true, 0, classGuid, 2, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, AndroidUtilities.isTablet() ? 30 : 20, 0, 0, true, 0, classGuid, 2, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); } return; } else if (!doNotRemoveLoadIndex) { @@ -12981,7 +13114,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (load_type == 0 && isCache && messArr.size() < count) { postponedScrollToLastMessageQueryIndex = lastLoadIndex; waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, count, 0, 0, false, 0, classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, count, 0, 0, false, 0, classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); return; } @@ -13013,14 +13146,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (currentEncryptedChat != null) { bundle.putInt("enc_id", currentEncryptedChat.id); } else if (currentChat != null) { - bundle.putInt("chat_id", currentChat.id); + bundle.putLong("chat_id", currentChat.id); } else { - bundle.putInt("user_id", currentUser.id); + bundle.putLong("user_id", currentUser.id); } bundle.putInt("message_id", postponedScrollMessageId); presentFragment(new ChatActivity(bundle), true); } else { - BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound)).show(); + BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show(); } return; } @@ -13464,7 +13597,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not highlightMessageId = messageId; } if (showScrollToMessageError && messageId != startLoadFromMessageId) { - BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound)).show(); + BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("MessageNotFound", R.string.MessageNotFound), themeDelegate).show(); } scrollToMessage = obj; if (postponedScroll) { @@ -13851,7 +13984,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not checkAutoDownloadMessages(false); } } else if (id == NotificationCenter.chatOnlineCountDidLoad) { - Integer chatId = (Integer) args[0]; + Long chatId = (Long) args[0]; if (chatInfo == null || currentChat == null || currentChat.id != chatId) { return; } @@ -13947,7 +14080,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.commentsRead) { - int channelId = (Integer) args[0]; + long channelId = (Long) args[0]; if (currentChat != null && currentChat.id == channelId) { int mid = (Integer) args[1]; MessageObject obj = messagesDict[0].get(mid); @@ -13968,7 +14101,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.changeRepliesCounter) { - int channelId = (Integer) args[0]; + long channelId = (Long) args[0]; if (currentChat != null && currentChat.id == channelId) { int mid = (Integer) args[1]; MessageObject obj = messagesDict[0].get(mid); @@ -14044,12 +14177,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatMode == MODE_SCHEDULED) { return; } - SparseLongArray inbox = (SparseLongArray) args[0]; - SparseLongArray outbox = (SparseLongArray) args[1]; + LongSparseIntArray inbox = (LongSparseIntArray) args[0]; + LongSparseIntArray outbox = (LongSparseIntArray) args[1]; boolean updated = false; if (inbox != null) { for (int b = 0, size = inbox.size(); b < size; b++) { - int key = inbox.keyAt(b); + long key = inbox.keyAt(b); long messageId = inbox.get(key); if (key != dialog_id) { continue; @@ -14085,7 +14218,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (outbox != null) { for (int b = 0, size = outbox.size(); b < size; b++) { - int key = outbox.keyAt(b); + long key = outbox.keyAt(b); int messageId = (int) outbox.get(key); if (key != dialog_id) { continue; @@ -14157,7 +14290,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not maxDate[0] = maxDate[1] = Integer.MIN_VALUE; minDate[0] = minDate[1] = 0; waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); loading = true; } else { if (botButtons != null) { @@ -14185,7 +14318,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } ArrayList markAsDeletedMessages = (ArrayList) args[0]; - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; processDeletedMessages(markAsDeletedMessages, channelId); } else if (id == NotificationCenter.messageReceivedByServer) { Boolean scheduled = (Boolean) args[6]; @@ -14311,7 +14444,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateVisibleRows(); } } else if (id == NotificationCenter.groupCallUpdated) { - Integer chatId = (Integer) args[0]; + Long chatId = (Long) args[0]; if (dialog_id == -chatId) { groupCall = getMessagesController().getGroupCall(currentChat.id, false); if (fragmentContextView != null) { @@ -14320,9 +14453,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not checkGroupCallJoin(false); } } else if (id == NotificationCenter.didLoadChatInviter) { - int chatId = (Integer) args[0]; + long chatId = (Long) args[0]; if (dialog_id == -chatId && chatInviterId == 0) { - chatInviterId = (Integer) args[1]; + chatInviterId = (Long) args[1]; if (chatInfo != null) { chatInfo.inviterId = chatInviterId; } @@ -14348,7 +14481,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } showGigagroupConvertAlert(); - int prevLinkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; + long prevLinkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; chatInfo = chatFull; groupCall = getMessagesController().getGroupCall(currentChat.id, true); if (ChatObject.isChannel(currentChat) && currentChat.megagroup && fragmentContextView != null) { @@ -14450,15 +14583,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } checkGroupCallJoin((Boolean) args[3]); + checkThemeEmoticon(); } } else if (id == NotificationCenter.chatInfoCantLoad) { - int chatId = (Integer) args[0]; + long chatId = (Long) args[0]; if (currentChat != null && currentChat.id == chatId) { int reason = (Integer) args[1]; if (getParentActivity() == null || closeChatDialog != null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (reason == 0) { if (currentChat.has_link) { @@ -14530,7 +14664,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not forwardEndReached[0] = false; chatAdapter.notifyItemInserted(0); } - MessagesController.getInstance(currentAccount).addToViewsQueue(threadMessageObject); + getMessagesController().addToViewsQueue(threadMessageObject); } else { clearHistory((Boolean) args[1], (TLRPC.TL_updates_channelDifferenceTooLong) args[2]); } @@ -14556,23 +14690,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.didCreatedNewDeleteTask) { - SparseArray> mids = (SparseArray>) args[0]; + long dialogId = (Long) args[0]; + if (dialogId != dialog_id) { + return; + } + SparseArray> mids = (SparseArray>) args[1]; boolean changed = false; for (int i = 0; i < mids.size(); i++) { int key = mids.keyAt(i); - ArrayList arr = mids.get(key); + ArrayList arr = mids.get(key); for (int a = 0; a < arr.size(); a++) { - long mid = arr.get(a); - if (a == 0) { - int channelId = (int) (mid >> 32); - if (channelId < 0) { - channelId = 0; - } - if (channelId != (ChatObject.isChannel(currentChat) ? currentChat.id : 0)) { - return; - } - } - MessageObject messageObject = messagesDict[0].get((int) mid); + Integer mid = arr.get(a); + MessageObject messageObject = messagesDict[0].get(mid); if (messageObject != null) { messageObject.messageOwner.destroyTime = key; changed = true; @@ -14907,16 +15036,19 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not long did = (Long) args[0]; if (did == dialog_id) { ArrayList loadedMessages = (ArrayList) args[1]; - LongSparseArray> replyMessageOwners = (LongSparseArray>) args[2]; + LongSparseArray>> replyMessageOwners = (LongSparseArray>>) args[2]; for (int a = 0, N = loadedMessages.size(); a < N; a++) { MessageObject obj = loadedMessages.get(a); repliesMessagesDict.put(obj.getId(), obj); } if (replyMessageOwners != null) { for (int a = 0, N = replyMessageOwners.size(); a < N; a++) { - ArrayList arrayList = replyMessageOwners.valueAt(a); - for (int b = 0, N2 = arrayList.size(); b < N2; b++) { - addReplyMessageOwner(arrayList.get(b), 0); + SparseArray> sparseArray = replyMessageOwners.valueAt(a); + for (int c = 0, N3 = sparseArray.size(); c < N3; c++) { + ArrayList arrayList = sparseArray.valueAt(c); + for (int b = 0, N2 = arrayList.size(); b < N2; b++) { + addReplyMessageOwner(arrayList.get(b), 0); + } } } } @@ -15027,7 +15159,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not processNewMessages(arrayList); } } else { - processDeletedMessages(ids, ChatObject.isChannel(currentChat) ? currentChat.id : 0); + processDeletedMessages(ids, ChatObject.isChannel(currentChat) ? dialog_id : 0); } } } else { @@ -15083,18 +15215,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.messagesReadContent) { - ArrayList arrayList = (ArrayList) args[0]; - int currentChannelId = ChatObject.isChannel(currentChat) ? currentChat.id : 0; - for (int a = 0; a < arrayList.size(); a++) { - long mid = arrayList.get(a); - int channelId = (int) (mid >> 32); - if (channelId < 0) { - channelId = 0; - } - if (channelId != currentChannelId) { - continue; - } - MessageObject currentMessage = messagesDict[0].get((int) mid); + long did = (Long) args[0]; + if (did != dialog_id && (ChatObject.isChannel(currentChat) || did != 0)) { + return; + } + ArrayList arrayList = (ArrayList) args[1]; + for (int a = 0, N = arrayList.size(); a < N; a++) { + int mid = arrayList.get(a); + MessageObject currentMessage = messagesDict[0].get(mid); if (currentMessage != null) { currentMessage.setContentIsRead(); if (currentMessage.messageOwner.mentioned) { @@ -15196,20 +15324,20 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.didUpdateMessagesViews) { - SparseArray channelViews = (SparseArray) args[0]; - SparseArray channelForwards = (SparseArray) args[1]; - SparseArray> channelReplies = (SparseArray>) args[2]; + LongSparseArray channelViews = (LongSparseArray) args[0]; + LongSparseArray channelForwards = (LongSparseArray) args[1]; + LongSparseArray> channelReplies = (LongSparseArray>) args[2]; boolean addingReplies = (Boolean) args[3]; boolean updated = false; LongSparseArray newGroups = null; ArrayList updatedRows = null; for (int b = 0; b < 2; b++) { - SparseArray sparseArray = b == 0 ? channelViews : channelForwards; + LongSparseArray sparseArray = b == 0 ? channelViews : channelForwards; if (sparseArray == null) { continue; } - SparseIntArray array = sparseArray.get((int) dialog_id); + SparseIntArray array = sparseArray.get(dialog_id); if (array != null) { for (int a = 0; a < array.size(); a++) { int messageId = array.keyAt(a); @@ -15244,7 +15372,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } if (channelReplies != null) { - SparseArray array = channelReplies.get((int) dialog_id); + SparseArray array = channelReplies.get(dialog_id); boolean hasChatInBack = false; if (threadMessageObject != null && parentLayout != null) { @@ -15265,7 +15393,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not int messageId = array.keyAt(a); MessageObject messageObject = messagesDict[0].get(messageId); if (messageObject != null && messageObject != threadMessageObject) { - TLRPC.TL_messageReplies newValue = array.get(messageId); + TLRPC.MessageReplies newValue = array.get(messageId); if (newValue == null || !addingReplies && messageObject.messageOwner.replies != null && newValue.replies_pts <= messageObject.messageOwner.replies.replies_pts && newValue.read_max_id <= messageObject.messageOwner.replies.read_max_id && newValue.max_id <= messageObject.messageOwner.replies.max_id) { continue; } @@ -15371,12 +15499,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } else if (id == NotificationCenter.userInfoDidLoad) { - Integer uid = (Integer) args[0]; + Long uid = (Long) args[0]; if (currentUser != null && currentUser.id == uid) { userInfo = (TLRPC.UserFull) args[1]; + checkThemeEmoticon(); if (headerItem != null) { + showAudioCallAsIcon = userInfo.phone_calls_available && !inPreviewMode; if (userInfo.phone_calls_available) { - headerItem.showSubItem(call); + if (showAudioCallAsIcon) { + if (audioCallIconItem != null) { + if (openAnimationStartTime != 0 && audioCallIconItem.getVisibility() != View.VISIBLE) { + audioCallIconItem.setAlpha(0f); + audioCallIconItem.animate().alpha(1f).setDuration(150).start(); + } + audioCallIconItem.setVisibility(View.VISIBLE); + } + } else { + headerItem.showSubItem(call); + } if (userInfo.video_calls_available) { headerItem.showSubItem(video_call); } else { @@ -15385,6 +15525,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { headerItem.hideSubItem(call); headerItem.hideSubItem(video_call); + if (audioCallIconItem != null) { + audioCallIconItem.setVisibility(View.GONE); + } } } checkActionBarMenu(false); @@ -15435,6 +15578,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); } else if (id == NotificationCenter.goingToPreviewTheme) { + isPauseOnThemePreview = true; if (chatLayoutManager != null) { scrollToPositionOnRecreate = chatLayoutManager.findFirstVisibleItemPosition(); RecyclerListView.Holder holder = (RecyclerListView.Holder) chatListView.findViewHolderForAdapterPosition(scrollToPositionOnRecreate); @@ -15527,6 +15671,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not removeSelfFromStack(); } } + } else if (id == NotificationCenter.needSetDayNightTheme) { + Theme.ThemeInfo theme = (Theme.ThemeInfo) args[0]; + if (theme != null) { + if (chatThemeBottomSheet != null) { + chatThemeBottomSheet.setupLightDarkTheme(theme.isDark()); + } else { + themeDelegate.setCurrentTheme(themeDelegate.chatTheme, true, theme.isDark()); + } + } } } @@ -15547,7 +15700,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } } - }, true); + }, true, themeDelegate); } private boolean sponsoredMessagesAdded; @@ -15760,16 +15913,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not finishFragment(); } else { Bundle bundle = new Bundle(); - int lower_part = (int) inlineReturn; - int high_part = (int) (inlineReturn >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - bundle.putInt("user_id", lower_part); - } else { - bundle.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(inlineReturn)) { + bundle.putInt("enc_id", DialogObject.getEncryptedChatId(inlineReturn)); + } else if (DialogObject.isUserDialog(inlineReturn)) { + bundle.putLong("user_id", inlineReturn); } else { - bundle.putInt("enc_id", high_part); + bundle.putLong("chat_id", -inlineReturn); } presentFragment(new ChatActivity(bundle), true); } @@ -15854,18 +16003,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } private void rotateMotionBackgroundDrawable() { - Drawable wallpaper = Theme.getCachedWallpaperNonBlocking(); + Drawable wallpaper = themeDelegate.getWallpaperDrawable(); + if (fragmentView != null) { + wallpaper = ((SizeNotifierFrameLayout) fragmentView).getBackgroundImage(); + } if (wallpaper instanceof MotionBackgroundDrawable) { ((MotionBackgroundDrawable) wallpaper).switchToNextPosition(); } - MotionBackgroundDrawable drawable = Theme.chat_msgOutDrawable != null ? Theme.chat_msgOutDrawable.getMotionBackgroundDrawable() : null; - if (drawable instanceof MotionBackgroundDrawable) { - drawable.switchToNextPosition(); + Drawable drawable = getThemedDrawable(Theme.key_drawable_msgOut); + if (drawable instanceof Theme.MessageDrawable) { + MotionBackgroundDrawable motionDrawable = ((Theme.MessageDrawable) drawable).getMotionBackgroundDrawable(); + if (motionDrawable != null) { + motionDrawable.switchToNextPosition(); + } } } private void processNewMessages(ArrayList arr) { - int currentUserId = getUserConfig().getClientUserId(); + long currentUserId = getUserConfig().getClientUserId(); boolean updateChat = false; boolean hasFromMe = false; boolean isAd = false; @@ -16085,6 +16240,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (BuildVars.LOGS_ENABLED) { FileLog.d("received new messages " + arr.size() + " in dialog " + dialog_id); } + + MessageObject lastActionSetChatThemeMessageObject = null; for (int a = 0; a < arr.size(); a++) { MessageObject obj = arr.get(a); if (obj.scheduled != (chatMode == MODE_SCHEDULED) || threadMessageId != 0 && threadMessageId != obj.getReplyTopMsgId() && threadMessageId != obj.getReplyMsgId()) { @@ -16354,6 +16511,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (obj.type == 10 || obj.type == 11) { updateChat = true; } + if (obj.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + lastActionSetChatThemeMessageObject = obj; + } + } + if (lastActionSetChatThemeMessageObject != null && lastActionSetChatThemeMessageObject.messageOwner != null && lastActionSetChatThemeMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + TLRPC.TL_messageActionSetChatTheme action = (TLRPC.TL_messageActionSetChatTheme) lastActionSetChatThemeMessageObject.messageOwner.action; + setChatThemeEmoticon(action.emoticon); } if (webpagesToReload != null) { getMessagesController().reloadWebPages(dialog_id, webpagesToReload, chatMode == MODE_SCHEDULED); @@ -16455,13 +16619,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not updateReplyMessageHeader(true); } - private void processDeletedMessages(ArrayList markAsDeletedMessages, int channelId) { + private void processDeletedMessages(ArrayList markAsDeletedMessages, long channelId) { ArrayList removedIndexes = new ArrayList<>(); int loadIndex = 0; if (ChatObject.isChannel(currentChat)) { if (channelId == 0 && mergeDialogId != 0) { loadIndex = 1; - } else if (channelId == currentChat.id) { + } else if (channelId == -dialog_id) { loadIndex = 0; } else { return; @@ -16638,7 +16802,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not maxDate[0] = maxDate[1] = Integer.MIN_VALUE; minDate[0] = minDate[1] = 0; waitingForLoad.add(lastLoadIndex); - getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, ChatObject.isChannel(currentChat), chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); + getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, 0, !cacheEndReached[0], minDate[0], classGuid, 0, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++); loading = true; } else { if (botButtons != null) { @@ -16852,7 +17016,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (parentLayout == null) { return; } - final int channelId = obj.messageOwner.action.channel_id; + final long channelId = obj.messageOwner.action.channel_id; final BaseFragment lastFragment = parentLayout.fragmentsStack.size() > 0 ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1) : null; int index = parentLayout.fragmentsStack.indexOf(ChatActivity.this); @@ -16863,24 +17027,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not BaseFragment fragment = actionBarLayout.fragmentsStack.get(a); if (fragment instanceof ChatActivity) { final Bundle bundle = new Bundle(); - bundle.putInt("chat_id", channelId); + bundle.putLong("chat_id", channelId); actionBarLayout.addFragmentToStack(new ChatActivity(bundle), a); fragment.removeSelfFromStack(); } else if (fragment instanceof ProfileActivity) { Bundle args = new Bundle(); - args.putInt("chat_id", channelId); + args.putLong("chat_id", channelId); actionBarLayout.addFragmentToStack(new ProfileActivity(args), a); fragment.removeSelfFromStack(); } else if (fragment instanceof ChatEditActivity) { Bundle args = new Bundle(); - args.putInt("chat_id", channelId); + args.putLong("chat_id", channelId); actionBarLayout.addFragmentToStack(new ChatEditActivity(args), a); fragment.removeSelfFromStack(); } else if (fragment instanceof ChatUsersActivity) { ChatUsersActivity usersActivity = (ChatUsersActivity) fragment; if (!usersActivity.hasSelectType()) { Bundle args = fragment.getArguments(); - args.putInt("chat_id", channelId); + args.putLong("chat_id", channelId); actionBarLayout.addFragmentToStack(new ChatUsersActivity(args), a); } fragment.removeSelfFromStack(); @@ -16893,7 +17057,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } getNotificationCenter().postNotificationName(NotificationCenter.closeChats); final Bundle bundle = new Bundle(); - bundle.putInt("chat_id", obj.messageOwner.action.channel_id); + bundle.putLong("chat_id", obj.messageOwner.action.channel_id); actionBarLayout.addFragmentToStack(new ChatActivity(bundle), actionBarLayout.fragmentsStack.size() - 1); lastFragment.finishFragment(); }); @@ -17017,9 +17181,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public void onTransitionAnimationStart(boolean isOpen, boolean backward) { + super.onTransitionAnimationStart(isOpen, backward); int[] alowedNotifications = null; if (isOpen) { - fragmentBeginToShow = true; if (transitionAnimationIndex == 0) { alowedNotifications = new int[]{ NotificationCenter.dialogsNeedReload, NotificationCenter.closeChats, @@ -17053,6 +17217,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public void onTransitionAnimationEnd(boolean isOpen, boolean backward) { + super.onTransitionAnimationEnd(isOpen, backward); if (isOpen) { if (!fragmentOpened) { fragmentOpened = true; @@ -17120,7 +17285,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not SharedPreferences preferences = MessagesController.getGlobalNotificationsSettings(); boolean check; if (type == MessagesController.PROMO_TYPE_PROXY) { - if (preferences.getLong("proxychannel", 0) != dialog_id) { + if (AndroidUtilities.getPrefIntOrLong(preferences, "proxychannel", 0) != dialog_id) { message = LocaleController.getString("UseProxySponsorInfo", R.string.UseProxySponsorInfo); } else { message = null; @@ -17154,9 +17319,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } firstOpen = false; } + + if (!backward && fromPullingDownTransition && parentLayout != null && parentLayout.fragmentsStack.size() >= 2) { + BaseFragment fragment = parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2); + if (fragment instanceof ChatActivity) { + backToPreviousFragment = (ChatActivity) fragment; + parentLayout.fragmentsStack.remove(backToPreviousFragment); + } + } } else { getNotificationCenter().onAnimationFinish(transitionAnimationIndex); } + contentView.invalidate(); } @Override @@ -17817,7 +17991,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedMessageTextView[1].setLayoutParams(layoutParams5); if (threadMessageId != 0) { - MessagesController messagesController = MessagesController.getInstance(currentAccount); + MessagesController messagesController = getMessagesController(); TLRPC.MessageFwdHeader fwd_from = threadMessageObject.messageOwner.fwd_from; TLRPC.User user = null; TLRPC.Chat chat = null; @@ -18227,9 +18401,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not addToContactsButton.setVisibility(View.VISIBLE); addToContactsButton.setText(str); addToContactsButton.setTag(4); - addToContactsButton.setTextColor(Theme.getColor(Theme.key_chat_addContact)); + addToContactsButton.setTextColor(getThemedColor(Theme.key_chat_addContact)); if (Build.VERSION.SDK_INT >= 21) { - Theme.setSelectorDrawableColor(addToContactsButton.getBackground(), Theme.getColor(Theme.key_chat_addContact) & 0x19ffffff, true); + Theme.setSelectorDrawableColor(addToContactsButton.getBackground(), getThemedColor(Theme.key_chat_addContact) & 0x19ffffff, true); } reportSpamButton.setTag(Theme.key_chat_addContact); } else if (user != null) { @@ -18274,9 +18448,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (showGeo) { reportSpamButton.setText(LocaleController.getString("ReportSpamLocation", R.string.ReportSpamLocation)); reportSpamButton.setTag(R.id.object_tag, 1); - reportSpamButton.setTextColor(Theme.getColor(Theme.key_chat_addContact)); + reportSpamButton.setTextColor(getThemedColor(Theme.key_chat_addContact)); if (Build.VERSION.SDK_INT >= 21) { - Theme.setSelectorDrawableColor(reportSpamButton.getBackground(), Theme.getColor(Theme.key_chat_addContact) & 0x19ffffff, true); + Theme.setSelectorDrawableColor(reportSpamButton.getBackground(), getThemedColor(Theme.key_chat_addContact) & 0x19ffffff, true); } reportSpamButton.setTag(Theme.key_chat_addContact); } else { @@ -18291,9 +18465,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not reportSpamButton.setText(LocaleController.getString("ReportSpamAndLeave", R.string.ReportSpamAndLeave)); } reportSpamButton.setTag(R.id.object_tag, null); - reportSpamButton.setTextColor(Theme.getColor(Theme.key_chat_reportSpam)); + reportSpamButton.setTextColor(getThemedColor(Theme.key_chat_reportSpam)); if (Build.VERSION.SDK_INT >= 21) { - Theme.setSelectorDrawableColor(reportSpamButton.getBackground(), Theme.getColor(Theme.key_chat_reportSpam) & 0x19ffffff, true); + Theme.setSelectorDrawableColor(reportSpamButton.getBackground(), getThemedColor(Theme.key_chat_reportSpam) & 0x19ffffff, true); } reportSpamButton.setTag(Theme.key_chat_reportSpam); } @@ -18504,7 +18678,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not checkShowBlur(false); activityResumeTime = System.currentTimeMillis(); if (openImport && getSendMessagesHelper().getImportingHistory(dialog_id) != null) { - ImportingAlert alert = new ImportingAlert(getParentActivity(), null, this); + ImportingAlert alert = new ImportingAlert(getParentActivity(), null, this, themeDelegate); alert.setOnHideListener(dialog -> { if (fragmentContextView != null) { fragmentContextView.checkImport(false); @@ -18527,7 +18701,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Bulletin.addDelegate(this, bulletinDelegate = new Bulletin.Delegate() { @Override - public int getBottomOffset() { + public int getBottomOffset(int tag) { + if (tag == 1) { + return 0; + } int height; if (chatActivityEnterView != null && chatActivityEnterView.getVisibility() == View.VISIBLE) { if (contentView.getKeyboardHeight() < AndroidUtilities.dp(20) && chatActivityEnterView.isPopupShowing() || chatActivityEnterView.pannelAniamationInProgress()) { @@ -18653,10 +18830,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not scrimPopupWindow.setPauseNotifications(false); scrimPopupWindow.dismiss(); } - long replyId = threadMessageId; - if (replyId != 0 && currentChat != null) { - replyId |= ((long) currentChat.id) << 32; - } + int replyId = threadMessageId; getMessagesController().markDialogAsReadNow(dialog_id, replyId); MediaController.getInstance().stopRaiseToEarSensors(this, true); paused = true; @@ -18793,7 +18967,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not for (int a = 0; a < draftMessage.entities.size(); a++) { TLRPC.MessageEntity entity = draftMessage.entities.get(a); if (entity instanceof TLRPC.TL_inputMessageEntityMentionName || entity instanceof TLRPC.TL_messageEntityMentionName) { - int user_id; + long user_id; if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) { user_id = ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id; } else { @@ -19034,7 +19208,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } MessageObject message = MediaController.getInstance().getPlayingMessageObject(); if (message != null && message.isVideo()) { - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); getFileLoader().setLoadingVideoForPlayer(message.getDocument(), false); MediaController.getInstance().cleanupPlayer(true, true, false, true); @@ -19062,7 +19236,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not AlertsCreator.createDeleteMessagesAlert(this, currentUser, currentChat, currentEncryptedChat, chatInfo, mergeDialogId, finalSelectedObject, selectedMessagesIds, finalSelectedGroup, chatMode == MODE_SCHEDULED, loadParticipant, () -> { hideActionMode(); updatePinnedMessageView(true); - }); + }, themeDelegate); } private void hideActionMode() { @@ -19200,6 +19374,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not VoIPHelper.showGroupCallAlert(ChatActivity.this, currentChat, null, true, getAccountInstance()); return; } + } else if (message.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) { + showChatThemeBottomSheet(); + return; } } if (message.isSponsored() || threadMessageObjects != null && threadMessageObjects.contains(message)) { @@ -19678,9 +19855,81 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Rect rect = new Rect(); - ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity(), R.drawable.popup_fixed_alert); + ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity(), R.drawable.popup_fixed_alert, themeDelegate); popupLayout.setMinimumWidth(AndroidUtilities.dp(200)); - popupLayout.setOnTouchListener(new View.OnTouchListener() { + Rect backgroundPaddings = new Rect(); + Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); + shadowDrawable.getPadding(backgroundPaddings); + popupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); + + scrimPopupWindowItems = new ActionBarMenuSubItem[items.size() + (selectedObject.isSponsored() ? 1 : 0)]; + for (int a = 0, N = items.size(); a < N; a++) { + if (a == 0 && selectedObject.isSponsored()) { + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true, themeDelegate); + cell.setTextAndIcon(LocaleController.getString("SponsoredMessageInfo", R.string.SponsoredMessageInfo), R.drawable.menu_info); + cell.setItemHeight(56); + cell.setTag(R.id.width_tag, 240); + cell.setMultiline(); + scrimPopupWindowItems[scrimPopupWindowItems.length - 1] = cell; + popupLayout.addView(cell); + cell.setOnClickListener(v1 -> { + if (contentView == null || getParentActivity() == null) { + return; + } + BottomSheet.Builder builder = new BottomSheet.Builder(contentView.getContext()); + builder.setCustomView(new SponsoredMessageInfoView(getParentActivity(), themeDelegate)); + builder.show(); + }); + + View gap = new View(getParentActivity()); + gap.setMinimumWidth(AndroidUtilities.dp(196)); + gap.setTag(1000); + gap.setTag(R.id.object_tag, 1); + popupLayout.addView(gap); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) cell.getLayoutParams(); + if (LocaleController.isRTL) { + layoutParams.gravity = Gravity.RIGHT; + } + layoutParams.width = LayoutHelper.MATCH_PARENT; + layoutParams.height = AndroidUtilities.dp(6); + gap.setLayoutParams(layoutParams); + } + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1, themeDelegate); + cell.setMinimumWidth(AndroidUtilities.dp(200)); + cell.setTextAndIcon(items.get(a), icons.get(a)); + Integer option = options.get(a); + if (option == 1 && selectedObject.messageOwner.ttl_period != 0) { + menuDeleteItem = cell; + updateDeleteItemRunnable.run(); + cell.setSubtextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText6)); + } + scrimPopupWindowItems[a] = cell; + popupLayout.addView(cell); + final int i = a; + cell.setOnClickListener(v1 -> { + if (selectedObject == null || i >= options.size()) { + return; + } + processSelectedOption(options.get(i)); + scrimView = null; + contentView.invalidate(); + chatListView.invalidate(); + if (scrimPopupWindow != null) { + scrimPopupWindow.dismiss(); + } + }); + } + + LinearLayout scrimPopupContainerLayout = new LinearLayout(contentView.getContext()) { + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && scrimPopupWindow != null && scrimPopupWindow.isShowing()) { + scrimPopupWindow.dismiss(); + } + return super.dispatchKeyEvent(event); + } + }; + scrimPopupContainerLayout.setOnTouchListener(new View.OnTouchListener() { private int[] pos = new int[2]; @@ -19703,80 +19952,178 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return false; } }); - popupLayout.setDispatchKeyEventListener(keyEvent -> { - if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && scrimPopupWindow != null && scrimPopupWindow.isShowing()) { - scrimPopupWindow.dismiss(); - } - }); - Rect backgroundPaddings = new Rect(); - Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); - shadowDrawable.getPadding(backgroundPaddings); - popupLayout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); - - scrimPopupWindowItems = new ActionBarMenuSubItem[items.size() + (selectedObject.isSponsored() ? 1 : 0)]; - for (int a = 0, N = items.size(); a < N; a++) { - if (a == 0 && selectedObject.isSponsored()) { - ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true); - cell.setTextAndIcon(LocaleController.getString("SponsoredMessageInfo", R.string.SponsoredMessageInfo), R.drawable.menu_info); - cell.setItemHeight(56); - cell.setTag(R.id.width_tag, 240); - cell.setMultiline(); - scrimPopupWindowItems[scrimPopupWindowItems.length - 1] = cell; - popupLayout.addView(cell); - cell.setOnClickListener(v1 -> { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("SponsoredMessageAlertTitle", R.string.SponsoredMessageAlertTitle)); - builder.setMessage(LocaleController.getString("SponsoredMessageAlertText", R.string.SponsoredMessageAlertText)); - builder.setNegativeButton(LocaleController.getString("SponsoredMessageAlertLearnMore", R.string.SponsoredMessageAlertLearnMore), (dialogInterface, i) -> Browser.openUrl(getParentActivity(), LocaleController.getString("SponsoredMessageAlertLearnMoreUrl", R.string.SponsoredMessageAlertLearnMoreUrl))); - builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - showDialog(builder.create()); - scrimView = null; - contentView.invalidate(); - chatListView.invalidate(); - if (scrimPopupWindow != null) { - scrimPopupWindow.dismiss(); + scrimPopupContainerLayout.setOrientation(LinearLayout.VERTICAL); + boolean showMessageSeen = currentChat != null && message.isOutOwner() && message.isSent() && !message.isEditing() && !message.isSending() && !message.isSendError() && !message.isContentUnread() && !message.isUnread() && (ConnectionsManager.getInstance(currentAccount).getCurrentTime() - message.messageOwner.date < 7 * 86400) && (ChatObject.isMegagroup(currentChat) || !ChatObject.isChannel(currentChat)) && chatInfo != null && chatInfo.participants_count < 50; + MessageSeenView messageSeenView = null; + if (showMessageSeen) { + messageSeenView = new MessageSeenView(contentView.getContext(), currentAccount, message); + Drawable shadowDrawable2 = ContextCompat.getDrawable(contentView.getContext(), R.drawable.popup_fixed_alert).mutate(); + shadowDrawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), PorterDuff.Mode.MULTIPLY)); + FrameLayout messageSeenLayout = new FrameLayout(contentView.getContext()); + messageSeenLayout.addView(messageSeenView); + messageSeenLayout.setBackground(shadowDrawable2); + MessageSeenView finalMessageSeenView = messageSeenView; + messageSeenView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (scrimPopupWindow == null || finalMessageSeenView.users.isEmpty()) { + return; } - }); + int totalHeight = contentView.getHeightWithKeyboard(); + int availableHeight = totalHeight - scrimPopupY - AndroidUtilities.dp(46 + 16); - View gap = new View(getParentActivity()); - gap.setMinimumWidth(AndroidUtilities.dp(196)); - gap.setTag(1000); - gap.setTag(R.id.object_tag, 1); - popupLayout.addView(gap); - LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) cell.getLayoutParams(); - if (LocaleController.isRTL) { - layoutParams.gravity = Gravity.RIGHT; - } - layoutParams.width = LayoutHelper.MATCH_PARENT; - layoutParams.height = AndroidUtilities.dp(6); - gap.setLayoutParams(layoutParams); - } - ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1); - cell.setMinimumWidth(AndroidUtilities.dp(200)); - cell.setTextAndIcon(items.get(a), icons.get(a)); - Integer option = options.get(a); - if (option == 1 && selectedObject.messageOwner.ttl_period != 0) { - menuDeleteItem = cell; - updateDeleteItemRunnable.run(); - cell.setSubtextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText6)); - } - scrimPopupWindowItems[a] = cell; - popupLayout.addView(cell); - final int i = a; - cell.setOnClickListener(v1 -> { - if (selectedObject == null || i >= options.size()) { - return; - } - processSelectedOption(options.get(i)); - scrimView = null; - contentView.invalidate(); - chatListView.invalidate(); - if (scrimPopupWindow != null) { - scrimPopupWindow.dismiss(); + if (SharedConfig.messageSeenHintCount > 0 && contentView.getKeyboardHeight() < AndroidUtilities.dp(20)) { + availableHeight -= AndroidUtilities.dp(52); + Bulletin bulletin = BulletinFactory.of(ChatActivity.this).createErrorBulletin(AndroidUtilities.replaceTags(LocaleController.getString("MessageSeenTooltipMessage", R.string.MessageSeenTooltipMessage))); + bulletin.tag = 1; + bulletin.setDuration(4000); + bulletin.show(); + SharedConfig.updateMessageSeenHintCount(SharedConfig.messageSeenHintCount - 1); + } else if (contentView.getKeyboardHeight() > AndroidUtilities.dp(20)) { + availableHeight -=contentView.getKeyboardHeight() / 3f; + } + View previousPopupContentView = scrimPopupWindow.getContentView(); + + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), true, true, themeDelegate); + cell.setItemHeight(44); + cell.setTextAndIcon(LocaleController.getString("Back", R.string.Back), R.drawable.msg_arrow_back); + cell.getTextView().setPadding(LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), 0, LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0); + + Drawable shadowDrawable2 = ContextCompat.getDrawable(contentView.getContext(), R.drawable.popup_fixed_alert).mutate(); + shadowDrawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), PorterDuff.Mode.MULTIPLY)); + FrameLayout backContainer = new FrameLayout(contentView.getContext()); + backContainer.setBackground(shadowDrawable2); + + LinearLayout linearLayout = new LinearLayout(contentView.getContext()) { + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(260), MeasureSpec.AT_MOST), heightMeasureSpec); + setPivotX(getMeasuredWidth() - AndroidUtilities.dp(8)); + setPivotY(AndroidUtilities.dp(8)); + } + + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && scrimPopupWindow != null && scrimPopupWindow.isShowing()) { + if (mesageSeenUsersPopupWindow != null) { + mesageSeenUsersPopupWindow.dismiss(); + } + } + return super.dispatchKeyEvent(event); + } + }; + linearLayout.setOnTouchListener(new View.OnTouchListener() { + + private int[] pos = new int[2]; + + @Override + public boolean onTouch(View v, MotionEvent event) { + if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { + if (mesageSeenUsersPopupWindow != null && mesageSeenUsersPopupWindow.isShowing()) { + View contentView = mesageSeenUsersPopupWindow.getContentView(); + contentView.getLocationInWindow(pos); + rect.set(pos[0], pos[1], pos[0] + contentView.getMeasuredWidth(), pos[1] + contentView.getMeasuredHeight()); + if (!rect.contains((int) event.getX(), (int) event.getY())) { + mesageSeenUsersPopupWindow.dismiss(); + } + } + } else if (event.getActionMasked() == MotionEvent.ACTION_OUTSIDE) { + if (mesageSeenUsersPopupWindow != null && mesageSeenUsersPopupWindow.isShowing()) { + mesageSeenUsersPopupWindow.dismiss(); + } + } + return false; + } + }); + linearLayout.setOrientation(LinearLayout.VERTICAL); + RecyclerListView listView = finalMessageSeenView.createListView(); + int listViewTotalHeight = AndroidUtilities.dp(8) + AndroidUtilities.dp(44) * listView.getAdapter().getItemCount() + AndroidUtilities.dp(16); + + backContainer.addView(cell); + linearLayout.addView(backContainer); + linearLayout.addView(listView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 320, 0, -8, 0, 0)); + + if (listViewTotalHeight > availableHeight) { + if (availableHeight > AndroidUtilities.dp(620)) { + listView.getLayoutParams().height = AndroidUtilities.dp(620); + } else { + listView.getLayoutParams().height = availableHeight; + } + } else { + listView.getLayoutParams().height = listViewTotalHeight; + } + + Drawable shadowDrawable3 = ContextCompat.getDrawable(contentView.getContext(), R.drawable.popup_fixed_alert).mutate(); + shadowDrawable3.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), PorterDuff.Mode.MULTIPLY)); + listView.setBackground(shadowDrawable3); + boolean[] backButtonPressed = new boolean[1]; + + mesageSeenUsersPopupWindow = new ActionBarPopupWindow(linearLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { + @Override + public void dismiss(boolean animated) { + super.dismiss(animated); + if (backButtonPressed[0]) { + linearLayout.animate().alpha(0).scaleX(0).scaleY(0).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(350); + previousPopupContentView.animate().alpha(1f).scaleX(1).scaleY(1).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(350); + } else { + if (scrimPopupWindow != null) { + scrimPopupWindow.dismiss(); + + contentView.invalidate(); + chatListView.invalidate(); + } + } + if (Bulletin.getVisibleBulletin() != null && Bulletin.getVisibleBulletin().tag == 1) { + Bulletin.getVisibleBulletin().hide(); + } + mesageSeenUsersPopupWindow = null; + } + }; + mesageSeenUsersPopupWindow.setOutsideTouchable(true); + mesageSeenUsersPopupWindow.setClippingEnabled(true); + mesageSeenUsersPopupWindow.setFocusable(true); + mesageSeenUsersPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); + mesageSeenUsersPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); + mesageSeenUsersPopupWindow.getContentView().setFocusableInTouchMode(true); + + mesageSeenUsersPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, scrimPopupX, scrimPopupY); + previousPopupContentView.setPivotX(AndroidUtilities.dp(8)); + previousPopupContentView.setPivotY(AndroidUtilities.dp(8)); + previousPopupContentView.animate().alpha(0).scaleX(0f).scaleY(0f).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(350); + + linearLayout.setAlpha(0f); + linearLayout.setScaleX(0f); + linearLayout.setScaleY(0f); + linearLayout.animate().alpha(1f).scaleX(1f).scaleY(1f).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(350); + + backContainer.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (mesageSeenUsersPopupWindow != null) { + mesageSeenUsersPopupWindow.setEmptyOutAnimation(250); + backButtonPressed[0] = true; + mesageSeenUsersPopupWindow.dismiss(true); + } + } + }); + + listView.setOnItemClickListener((view1, position) -> { + TLRPC.User user = finalMessageSeenView.users.get(position); + if (user == null) { + return; + } + Bundle args = new Bundle(); + args.putLong("user_id", user.id); + ProfileActivity fragment = new ProfileActivity(args); + presentFragment(fragment); + mesageSeenUsersPopupWindow.dismiss(); + }); } }); + scrimPopupContainerLayout.addView(messageSeenLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 60)); } - scrimPopupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { + scrimPopupContainerLayout.addView(popupLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, showMessageSeen ? -8 : 0, 0, 0)); + scrimPopupWindow = new ActionBarPopupWindow(scrimPopupContainerLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override public void dismiss() { super.dismiss(); @@ -19818,6 +20165,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatActivityEnterView != null) { chatActivityEnterView.getEditField().setAllowDrawCursor(true); } + if (mesageSeenUsersPopupWindow != null) { + mesageSeenUsersPopupWindow.dismiss(); + } } }; scrimPopupWindow.setPauseNotifications(true); @@ -19826,16 +20176,20 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not scrimPopupWindow.setClippingEnabled(true); scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation); scrimPopupWindow.setFocusable(true); - popupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST)); + scrimPopupContainerLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST)); scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); scrimPopupWindow.getContentView().setFocusableInTouchMode(true); popupLayout.setFitItems(true); - int popupX = v.getLeft() + (int) x - popupLayout.getMeasuredWidth() + backgroundPaddings.left - AndroidUtilities.dp(28); + + if (messageSeenView != null) { + messageSeenView.getLayoutParams().width = scrimPopupContainerLayout.getMeasuredWidth() - AndroidUtilities.dp(16); + } + int popupX = v.getLeft() + (int) x - scrimPopupContainerLayout.getMeasuredWidth() + backgroundPaddings.left - AndroidUtilities.dp(28); if (popupX < AndroidUtilities.dp(6)) { popupX = AndroidUtilities.dp(6); - } else if (popupX > chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - popupLayout.getMeasuredWidth()) { - popupX = chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - popupLayout.getMeasuredWidth(); + } else if (popupX > chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth()) { + popupX = chatListView.getMeasuredWidth() - AndroidUtilities.dp(6) - scrimPopupContainerLayout.getMeasuredWidth(); } if (AndroidUtilities.isTablet()) { int[] location = new int[2]; @@ -19843,7 +20197,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not popupX += location[0]; } int totalHeight = contentView.getHeight(); - int height = popupLayout.getMeasuredHeight(); + int height = scrimPopupContainerLayout.getMeasuredHeight(); int keyboardHeight = contentView.measureKeyboardHeight(); if (keyboardHeight > AndroidUtilities.dp(20)) { totalHeight += keyboardHeight; @@ -19862,7 +20216,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { popupY = inBubbleMode ? 0 : AndroidUtilities.statusBarHeight; } - scrimPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, popupX, popupY); + scrimPopupWindow.showAtLocation(chatListView, Gravity.LEFT | Gravity.TOP, scrimPopupX = popupX, scrimPopupY = popupY); chatListView.stopScroll(); chatLayoutManager.setCanScrollVertically(false); scrimView = v; @@ -19985,7 +20339,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (!messageObject.scheduled) { TLRPC.TL_messages_getMessageEditData req = new TLRPC.TL_messages_getMessageEditData(); - req.peer = getMessagesController().getInputPeer((int) dialog_id); + req.peer = getMessagesController().getInputPeer(dialog_id); req.id = messageObject.getId(); editingMessageObjectReqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { editingMessageObjectReqId = 0; @@ -19993,7 +20347,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParentActivity() == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("EditMessageError", R.string.EditMessageError)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); @@ -20010,7 +20364,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - private void restartSticker(ChatMessageCell cell) { + public void restartSticker(ChatMessageCell cell) { MessageObject message = cell.getMessageObject(); TLRPC.Document document = message.getDocument(); boolean isEmoji; @@ -20051,10 +20405,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - private String getMessageContent(MessageObject messageObject, int previousUid, boolean name) { + private String getMessageContent(MessageObject messageObject, long previousUid, boolean name) { String str = ""; if (name) { - int fromId = messageObject.getFromChatId(); + long fromId = messageObject.getFromChatId(); if (previousUid != fromId) { if (fromId > 0) { TLRPC.User user = getMessagesController().getUser(fromId); @@ -20103,16 +20457,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not () -> { getMessagesController().pinMessage(currentChat, currentUser, messageObject.getId(), true, false, false); pinBulletin = null; - }).show(); + }, themeDelegate).show(); } public void openReportChat(int type) { Bundle args = new Bundle(); - int lowerId = (int) dialog_id; - if (lowerId > 0) { - args.putInt("user_id", lowerId); + if (DialogObject.isUserDialog(dialog_id)) { + args.putLong("user_id", dialog_id); } else { - args.putInt("chat_id", -lowerId); + args.putLong("chat_id", -dialog_id); } args.putInt("report", type); ChatActivity fragment = new ChatActivity(args); @@ -20228,11 +20581,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { fileType = BulletinFactory.FileType.MEDIA; } - BulletinFactory.of(this).createDownloadBulletin(fileType, filesAmount).show(); + BulletinFactory.of(this).createDownloadBulletin(fileType, filesAmount, themeDelegate).show(); } else { saveMessageToGallery(selectedObject); if (getParentActivity() != null) { - BulletinFactory.createSaveToGalleryBulletin(this, selectedObject.isVideo()).show(); + BulletinFactory.createSaveToGalleryBulletin(this, selectedObject.isVideo(), themeDelegate).show(); } } break; @@ -20264,7 +20617,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selectedObjectToEditCaption = null; return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("IncorrectTheme", R.string.IncorrectTheme)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); @@ -20280,7 +20633,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not selectedObjectToEditCaption = null; return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("IncorrectLocalization", R.string.IncorrectLocalization)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); @@ -20340,7 +20693,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } MediaController.saveFile(path, getParentActivity(), 0, null, null); - BulletinFactory.createSaveToGalleryBulletin(this, selectedObject.isVideo()).show(); + BulletinFactory.createSaveToGalleryBulletin(this, selectedObject.isVideo(), themeDelegate).show(); break; } case 8: { @@ -20348,7 +20701,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not break; } case 9: { - StickersAlert alert = new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE && (currentChat == null || ChatObject.canSendStickers(currentChat)) ? chatActivityEnterView : null); + StickersAlert alert = new StickersAlert(getParentActivity(), this, selectedObject.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE && (currentChat == null || ChatObject.canSendStickers(currentChat)) ? chatActivityEnterView : null, themeDelegate); alert.setCalcMandatoryInsets(isKeyboardVisible()); showDialog(alert); break; @@ -20377,7 +20730,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (count > 0) { - BulletinFactory.of(this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count).show(); + BulletinFactory.of(this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count, themeDelegate).show(); } }); } else { @@ -20412,7 +20765,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { fileType = BulletinFactory.FileType.UNKNOWN; } - BulletinFactory.of(this).createDownloadBulletin(fileType).show(); + BulletinFactory.of(this).createDownloadBulletin(fileType, themeDelegate).show(); }); } break; @@ -20442,7 +20795,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { mid = selectedObject.getId(); } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("PinMessageAlertTitle", R.string.PinMessageAlertTitle)); final boolean[] checks; @@ -20455,7 +20808,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not checks = new boolean[]{false, false}; if (!UserObject.isUserSelf(currentUser)) { FrameLayout frameLayout = new FrameLayout(getParentActivity()); - CheckBoxCell cell = new CheckBoxCell(getParentActivity(), 1); + CheckBoxCell cell = new CheckBoxCell(getParentActivity(), 1, themeDelegate); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setText(LocaleController.formatString("PinAlsoFor", R.string.PinAlsoFor, UserObject.getFirstName(currentUser)), "", false, false); cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(8) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(8), 0); @@ -20475,7 +20828,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not builder.setMessage(LocaleController.getString("PinMessageAlert", R.string.PinMessageAlert)); checks = new boolean[]{true, true}; FrameLayout frameLayout = new FrameLayout(getParentActivity()); - CheckBoxCell cell = new CheckBoxCell(getParentActivity(), 1); + CheckBoxCell cell = new CheckBoxCell(getParentActivity(), 1, themeDelegate); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setText(LocaleController.getString("PinNotify", R.string.PinNotify), "", true, false); cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(8) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(8), 0); @@ -20497,7 +20850,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } builder.setPositiveButton(LocaleController.getString("PinMessage", R.string.PinMessage), (dialogInterface, i) -> { getMessagesController().pinMessage(currentChat, currentUser, mid, false, !checks[1], checks[0]); - Bulletin bulletin = BulletinFactory.createPinMessageBulletin(this); + Bulletin bulletin = BulletinFactory.createPinMessageBulletin(this, themeDelegate); bulletin.show(); View view = bulletin.getLayout(); view.postDelayed(() -> { @@ -20527,7 +20880,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } case 15: { Bundle args = new Bundle(); - args.putInt("user_id", selectedObject.messageOwner.media.user_id); + args.putLong("user_id", selectedObject.messageOwner.media.user_id); args.putString("phone", selectedObject.messageOwner.media.phone_number); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); @@ -20583,7 +20936,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ClipData clip = ClipData.newPlainText("label", exportedMessageLink.link); clipboard.setPrimaryClip(clip); if (BulletinFactory.canShowBulletin(ChatActivity.this)) { - BulletinFactory.of(ChatActivity.this).createCopyLinkBulletin(!isThreadChat() && exportedMessageLink.link.contains("/c/")).show(); + BulletinFactory.of(ChatActivity.this).createCopyLinkBulletin(!isThreadChat() && exportedMessageLink.link.contains("/c/"), themeDelegate).show(); } } catch (Exception e) { FileLog.e(e); @@ -20596,10 +20949,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not case 23: { if (UserObject.isReplyUser(currentUser)) { if (selectedObject.messageOwner.fwd_from != null) { - AlertsCreator.showBlockReportSpamReplyAlert(ChatActivity.this, selectedObject, MessageObject.getPeerId(selectedObject.messageOwner.fwd_from.from_id)); + AlertsCreator.showBlockReportSpamReplyAlert(ChatActivity.this, selectedObject, MessageObject.getPeerId(selectedObject.messageOwner.fwd_from.from_id), themeDelegate); } } else { - AlertsCreator.createReportAlert(getParentActivity(), dialog_id, selectedObject.getId(), ChatActivity.this); + AlertsCreator.createReportAlert(getParentActivity(), dialog_id, selectedObject.getId(), ChatActivity.this, themeDelegate); } break; } @@ -20614,7 +20967,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not break; } case 25: { - final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3)}; + final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3, themeDelegate)}; int requestId = getSendMessagesHelper().sendVote(selectedObject, null, () -> { try { progressDialog[0].dismiss(); @@ -20636,7 +20989,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } case 26: { MessageObject object = selectedObject; - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); if (object.isQuiz()) { builder.setTitle(LocaleController.getString("StopQuizAlertTitle", R.string.StopQuizAlertTitle)); builder.setMessage(LocaleController.getString("StopQuizAlertText", R.string.StopQuizAlertText)); @@ -20645,7 +20998,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not builder.setMessage(LocaleController.getString("StopPollAlertText", R.string.StopPollAlertText)); } builder.setPositiveButton(LocaleController.getString("Stop", R.string.Stop), (dialogInterface, i) -> { - final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3)}; + final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3, themeDelegate)}; TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) object.messageOwner.media; TLRPC.TL_inputMediaPoll poll = new TLRPC.TL_inputMediaPoll(); @@ -20655,7 +21008,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not poll.poll.answers = mediaPoll.poll.answers; poll.poll.closed = true; req.media = poll; - req.peer = getMessagesController().getInputPeer((int) dialog_id); + req.peer = getMessagesController().getInputPeer(dialog_id); req.id = object.getId(); req.flags |= 16384; int requestId = getConnectionsManager().sendRequest(req, (response, error) -> { @@ -20699,7 +21052,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not getMediaController().cleanupPlayer(true, true); } TLRPC.TL_messages_sendScheduledMessages req = new TLRPC.TL_messages_sendScheduledMessages(); - req.peer = MessagesController.getInstance(currentAccount).getInputPeer((int) dialog_id); + req.peer = getMessagesController().getInputPeer(dialog_id); if (selectedObjectGroup != null) { for (int a = 0; a < selectedObjectGroup.messages.size(); a++) { req.id.add(selectedObjectGroup.messages.get(a).getId()); @@ -20710,8 +21063,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> { if (error == null) { TLRPC.Updates updates = (TLRPC.Updates) response; - MessagesController.getInstance(currentAccount).processUpdates(updates, false); - AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.messagesDeleted, req.id, (int) -dialog_id, true, dialog_id)); + getMessagesController().processUpdates(updates, false); + AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.messagesDeleted, req.id, -dialog_id, true, dialog_id)); } else if (error.text != null) { AndroidUtilities.runOnUIThread(() -> { if (error.text.startsWith("SLOWMODE_WAIT_")) { @@ -20736,7 +21089,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { SendMessagesHelper.getInstance(currentAccount).editMessage(message, null, false, ChatActivity.this, null, scheduleDate); } - }, null); + }, null, themeDelegate); break; } } @@ -20801,20 +21154,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { long did = dids.get(0); if (did != dialog_id || chatMode == MODE_PINNED) { - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", scrollToTopOnResume); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(did)); } else { - args.putInt("enc_id", high_part); - } - if (lower_part != 0) { + if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); + } else { + args.putLong("chat_id", -did); + } if (!getMessagesController().checkCanOpenChat(args, fragment)) { return; } @@ -20843,7 +21192,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not public boolean checkRecordLocked(boolean forceCloseOnDiscard) { if (chatActivityEnterView != null && chatActivityEnterView.isRecordLocked()) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); if (chatActivityEnterView.isInVideoMode()) { builder.setTitle(LocaleController.getString("DiscardVideoMessageTitle", R.string.DiscardVideoMessageTitle)); builder.setMessage(LocaleController.getString("DiscardVideoMessageDescription", R.string.DiscardVideoMessageDescription)); @@ -20893,6 +21242,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatActivityEnterView.hideBotCommands(); return false; } + if (backToPreviousFragment != null) { + parentLayout.fragmentsStack.add(parentLayout.fragmentsStack.size() - 1, backToPreviousFragment); + backToPreviousFragment = null; + } return true; } @@ -20960,7 +21313,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } int count = chatListView.getChildCount(); MessageObject editingMessageObject = chatActivityEnterView != null ? chatActivityEnterView.getEditingMessageObject() : null; - int linkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; + long linkedChatId = chatInfo != null ? chatInfo.linked_chat_id : 0; for (int a = 0; a < count; a++) { View view = chatListView.getChildAt(a); if (view instanceof ChatMessageCell) { @@ -21061,7 +21414,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParentActivity() == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); if (message.type == 3) { @@ -21090,6 +21443,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (searchIconItem != null && showSearchAsIcon) { searchIconItem.setVisibility(View.GONE); } + if (audioCallIconItem != null && showAudioCallAsIcon) { + audioCallIconItem.setVisibility(View.GONE); + } searchItemVisible = true; updateSearchButtons(0, 0, -1); updateBottomOverlay(); @@ -21226,10 +21582,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } - public void showOpenGameAlert(final TLRPC.TL_game game, final MessageObject messageObject, final String urlStr, boolean ask, final int uid) { + public void showOpenGameAlert(final TLRPC.TL_game game, final MessageObject messageObject, final String urlStr, boolean ask, final long uid) { TLRPC.User user = getMessagesController().getUser(uid); if (ask) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); String name; if (user != null) { @@ -21301,7 +21657,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (!arrayList.isEmpty()) { Bundle args = new Bundle(); long dialogId = arrayList.get(0).getDialogId(); - args.putInt("chat_id", (int) -dialogId); + args.putLong("chat_id", -dialogId); args.putInt("message_id", Math.max(1, discussionMessage.read_inbox_max_id)); args.putInt("unread_count", discussionMessage.unread_count); args.putBoolean("historyPreloaded", history != null); @@ -21328,7 +21684,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } TLRPC.messages_Messages historyFinal = history; int fnidFinal = fnid; - Utilities.stageQueue.postRunnable(() -> getMessagesController().processLoadedMessages(historyFinal, historyFinal.messages.size(), dialogId, 0, 30, maxReadId, 0, false, chatActivity.getClassGuid(), fnidFinal, 0, 0, 0, 2, true, false, 0, arrayList.get(arrayList.size() - 1).getId(), 1, false, 0, true)); + Utilities.stageQueue.postRunnable(() -> getMessagesController().processLoadedMessages(historyFinal, historyFinal.messages.size(), dialogId, 0, 30, maxReadId, 0, false, chatActivity.getClassGuid(), fnidFinal, 0, 0, 0, 2, true, 0, arrayList.get(arrayList.size() - 1).getId(), 1, false, 0, true)); } } @@ -21340,13 +21696,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not openOriginalReplyChat(fallbackMessage); } else { if (getParentActivity() != null) { - BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("ChannelPostDeleted", R.string.ChannelPostDeleted)).show(); + BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("ChannelPostDeleted", R.string.ChannelPostDeleted), themeDelegate).show(); } } } } - private void openDiscussionMessageChat(int chatId, MessageObject originalMessage, int messageId, int linkedChatId, int maxReadId, int highlightMsgId, MessageObject fallbackMessage) { + private void openDiscussionMessageChat(long chatId, MessageObject originalMessage, int messageId, long linkedChatId, int maxReadId, int highlightMsgId, MessageObject fallbackMessage) { TLRPC.Chat chat = getMessagesController().getChat(chatId); TLRPC.TL_messages_getDiscussionMessage req = new TLRPC.TL_messages_getDiscussionMessage(); req.peer = MessagesController.getInputPeer(chat); @@ -21408,11 +21764,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { if ("CHANNEL_PRIVATE".equals(error.text)) { if (getParentActivity() != null) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("JoinByPeekChannelText", R.string.JoinByPeekChannelText)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); - AlertDialog alertDialog = builder.create(); showDialog(builder.create()); } AndroidUtilities.cancelRunOnUIThread(progressRunnable); @@ -21462,11 +21817,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } Bundle args = new Bundle(); if (messageObject.messageOwner.fwd_from.saved_from_peer.channel_id != 0) { - args.putInt("chat_id", messageObject.messageOwner.fwd_from.saved_from_peer.channel_id); + args.putLong("chat_id", messageObject.messageOwner.fwd_from.saved_from_peer.channel_id); } else if (messageObject.messageOwner.fwd_from.saved_from_peer.chat_id != 0) { - args.putInt("chat_id", messageObject.messageOwner.fwd_from.saved_from_peer.chat_id); + args.putLong("chat_id", messageObject.messageOwner.fwd_from.saved_from_peer.chat_id); } else if (messageObject.messageOwner.fwd_from.saved_from_peer.user_id != 0) { - args.putInt("user_id", messageObject.messageOwner.fwd_from.saved_from_peer.user_id); + args.putLong("user_id", messageObject.messageOwner.fwd_from.saved_from_peer.user_id); } args.putInt("message_id", messageObject.messageOwner.fwd_from.saved_from_msg_id); if (getMessagesController().checkCanOpenChat(args, ChatActivity.this)) { @@ -21478,7 +21833,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (getParentActivity() == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate); builder.setTitle(LocaleController.getString("OpenUrlTitle", R.string.OpenUrlTitle)); String format = LocaleController.getString("OpenUrlAlert2", R.string.OpenUrlAlert2); int index = format.indexOf("%"); @@ -21495,7 +21850,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not linearLayout.setOrientation(LinearLayout.VERTICAL); TLRPC.User selfUser = getUserConfig().getCurrentUser(); for (int a = 0; a < (request.request_write_access ? 2 : 1); a++) { - cells[a] = new CheckBoxCell(getParentActivity(), 5); + cells[a] = new CheckBoxCell(getParentActivity(), 5, themeDelegate); cells[a].setBackgroundDrawable(Theme.getSelectorDrawable(false)); cells[a].setMultiline(true); cells[a].setTag(a); @@ -21533,7 +21888,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (!cells[0].isChecked()) { Browser.openUrl(getParentActivity(), url, false); } else { - final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3)}; + final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3, themeDelegate)}; TLRPC.TL_messages_acceptUrlAuth req = new TLRPC.TL_messages_acceptUrlAuth(); if (buttonReq.url != null) { req.url = buttonReq.url; @@ -21561,7 +21916,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else if (response instanceof TLRPC.TL_urlAuthResultDefault) { Browser.openUrl(getParentActivity(), url, false); } else if (buttonReq.url != null) { - AlertsCreator.showOpenUrlAlert(ChatActivity.this, buttonReq.url, false, ask); + AlertsCreator.showOpenUrlAlert(ChatActivity.this, buttonReq.url, false, ask, themeDelegate); } })); AndroidUtilities.runOnUIThread(() -> { @@ -21596,7 +21951,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(vcard); writer.close(); - showDialog(new PhonebookShareAlert(this, null, user, null, f, first_name, last_name)); + showDialog(new PhonebookShareAlert(this, null, user, null, f, first_name, last_name, themeDelegate)); } catch (Exception e) { FileLog.e(e); } @@ -21627,9 +21982,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not currentUser != null && !TextUtils.isEmpty(currentUser.username) && username.equals(currentUser.username.toLowerCase())) { Bundle args = new Bundle(); if (currentChat != null) { - args.putInt("chat_id", currentChat.id); + args.putLong("chat_id", currentChat.id); } else if (currentUser != null) { - args.putInt("user_id", currentUser.id); + args.putLong("user_id", currentUser.id); if (currentEncryptedChat != null) { args.putLong("dialog_id", dialog_id); } @@ -21640,7 +21995,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not fragment.setUserInfo(userInfo); presentFragment(fragment); } else { - MessagesController.getInstance(currentAccount).openByUserName(username, ChatActivity.this, 0); + getMessagesController().openByUserName(username, ChatActivity.this, 0); } } else if (str.startsWith("#") || str.startsWith("$")) { if (ChatObject.isChannel(currentChat)) { @@ -21673,9 +22028,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (forceAlert || AndroidUtilities.shouldShowUrlInAlert(url)) { if (type == 0 || type == 2) { - AlertsCreator.showOpenUrlAlert(ChatActivity.this, url, true, true, true); + AlertsCreator.showOpenUrlAlert(ChatActivity.this, url, true, true, true, themeDelegate); } else if (type == 1) { - AlertsCreator.showOpenUrlAlert(ChatActivity.this, url, true, true, false); + AlertsCreator.showOpenUrlAlert(ChatActivity.this, url, true, true, false, themeDelegate); } } else { if (type == 0) { @@ -21696,7 +22051,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ((URLSpanMono) url).copyToClipboard(); getUndoView().showWithAction(0, UndoView.ACTION_TEXT_COPIED, null); } else if (url instanceof URLSpanUserMention) { - TLRPC.User user = getMessagesController().getUser(Utilities.parseInt(((URLSpanUserMention) url).getURL())); + TLRPC.User user = getMessagesController().getUser(Utilities.parseLong(((URLSpanUserMention) url).getURL())); if (user != null) { MessagesController.openChatOrProfileWith(user, null, ChatActivity.this, 0, false); } @@ -21754,7 +22109,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } } else if (str.startsWith("card:")) { String number = str.substring(5); - final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3)}; + final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3, themeDelegate)}; TLRPC.TL_payments_getBankCardData req = new TLRPC.TL_payments_getBankCardData(); req.number = number; int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { @@ -21769,7 +22124,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } TLRPC.TL_payments_bankCardData data = (TLRPC.TL_payments_bankCardData) response; - BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); + BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate); ArrayList arrayList = new ArrayList<>(); for (int a = 0, N = data.open_urls.size(); a < N; a++) { arrayList.add(data.open_urls.get(a).name); @@ -21796,7 +22151,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not }, 500); } else { if (longPress) { - BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); + BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate); int timestamp = -1; if (str.startsWith("video?")) { timestamp = Utilities.parseInt(str); @@ -21823,27 +22178,27 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (!isMedia && finalMessageObject.replyMessageObject != null) { messageObject1 = finalMessageObject.replyMessageObject; } - int lower_id = (int) messageObject1.getDialogId(); + long dialogId = messageObject1.getDialogId(); int messageId = messageObject1.getId(); String link = null; if (messageObject1.messageOwner.fwd_from != null) { if (messageObject1.messageOwner.fwd_from.saved_from_peer != null) { - lower_id = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.saved_from_peer); + dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.saved_from_peer); messageId = messageObject1.messageOwner.fwd_from.saved_from_msg_id; } else if (messageObject1.messageOwner.fwd_from.from_id != null) { - lower_id = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.from_id); + dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.from_id); messageId = messageObject1.messageOwner.fwd_from.channel_post; } } - if (lower_id < 0) { - TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (currentChat != null && currentChat.username != null) { link = "https://t.me/" + currentChat.username + "/" + messageId + "?t=" + finalTimestamp; } } else { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null && user.username != null) { link = "https://t.me/" + user.username + "/" + messageId + "?t=" + finalTimestamp; } @@ -21873,7 +22228,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } else { final String urlFinal = ((URLSpan) url).getURL(); if (longPress) { - BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); + BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity(), false, themeDelegate); builder.setTitle(urlFinal); builder.setItems(new CharSequence[]{LocaleController.getString("Open", R.string.Open), LocaleController.getString("Copy", R.string.Copy)}, (dialog, which) -> { if (which == 0) { @@ -21943,7 +22298,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (message.isVideo()) { sendSecretMessageRead(message, true); } - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); MessageObject playingObject = MediaController.getInstance().getPlayingMessageObject(); if (cell != null && playingObject != null && playingObject.isVideo()) { getFileLoader().setLoadingVideoForPlayer(playingObject.getDocument(), false); @@ -22124,7 +22479,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not view = chatMessageCellsCache.get(0); chatMessageCellsCache.remove(0); } else { - view = new ChatMessageCell(mContext); + view = new ChatMessageCell(mContext, themeDelegate); } ChatMessageCell chatMessageCell = (ChatMessageCell) view; chatMessageCell.setDelegate(new ChatMessageCell.ChatMessageCellDelegate() { @@ -22219,7 +22574,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not arrayList = new ArrayList<>(); arrayList.add(messageObject); } - showDialog(new ShareAlert(mContext, ChatActivity.this, arrayList, null, null, ChatObject.isChannel(currentChat), null, null, false, false) { + showDialog(new ShareAlert(mContext, ChatActivity.this, arrayList, null, null, ChatObject.isChannel(currentChat), null, null, false, false, themeDelegate) { @Override public void dismissInternal() { super.dismissInternal(); @@ -22403,7 +22758,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private void openProfile(TLRPC.User user) { if (user != null && user.id != getUserConfig().getClientUserId()) { Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(currentUser != null && currentUser.id == user.id ? 1 : 0); AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid); @@ -22414,7 +22769,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private void openProfile(TLRPC.Chat chat) { if (chat != null) { Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); presentFragment(new ProfileActivity(args)); } } @@ -22422,7 +22777,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not private void openDialog(ChatMessageCell cell, TLRPC.User user) { if (user != null) { Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); if (getMessagesController().checkCanOpenChat(args, ChatActivity.this, cell.getMessageObject())) { presentFragment(new ChatActivity(args)); } @@ -22434,7 +22789,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not scrollToMessageId(postId, cell.getMessageObject().getId(), true, 0, true, 0); } else if (currentChat == null || chat.id != currentChat.id || isThreadChat()) { Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); if (postId != 0) { args.putInt("message_id", postId); } @@ -22471,7 +22826,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not return; } if (pollHintView == null) { - pollHintView = new HintView(getParentActivity(), HintView.TYPE_POLL_VOTE); + pollHintView = new HintView(getParentActivity(), HintView.TYPE_POLL_VOTE, themeDelegate); pollHintView.setAlpha(0.0f); pollHintView.setVisibility(View.INVISIBLE); int index = contentView.indexOfChild(chatActivityEnterView); @@ -22591,13 +22946,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not undoView.showWithAction(0, chatActivityEnterView.getVisibility() == View.VISIBLE && bottomOverlay.getVisibility() != View.VISIBLE ? UndoView.ACTION_DICE_INFO : UndoView.ACTION_DICE_NO_SEND_INFO, message.getDiceEmoji(), null, () -> getSendMessagesHelper().sendMessage(message.getDiceEmoji(), dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, true, 0, null)); } else if (message.isAnimatedEmoji()) { restartSticker(cell); + emojiAnimationsOverlay.onTapItem(cell, ChatActivity.this); + chatListView.cancelClickRunnables(false); } else if (message.needDrawBluredPreview()) { Runnable action = sendSecretMessageRead(message, false); cell.invalidate(); SecretMediaViewer.getInstance().setParentActivity(getParentActivity()); SecretMediaViewer.getInstance().openMedia(message, photoViewerProvider, action); } else if (message.getInputStickerSet() != null) { - StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, message.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE && (currentChat == null || ChatObject.canSendStickers(currentChat)) ? chatActivityEnterView : null); + StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, message.getInputStickerSet(), null, bottomOverlayChat.getVisibility() != View.VISIBLE && (currentChat == null || ChatObject.canSendStickers(currentChat)) ? chatActivityEnterView : null, themeDelegate); alert.setCalcMandatoryInsets(isKeyboardVisible()); showDialog(alert); } else if (message.isVideo() || message.type == 1 || message.type == 0 && !message.isWebpageDocument() || message.isGif()) { @@ -22664,13 +23021,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } boolean handled = false; if (message.canPreviewDocument()) { - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); PhotoViewer.getInstance().openPhoto(message, ChatActivity.this, message.type != 0 ? dialog_id : 0, message.type != 0 ? mergeDialogId : 0, photoViewerProvider); handled = true; } if (!handled) { try { - AndroidUtilities.openForView(message, getParentActivity()); + AndroidUtilities.openForView(message, getParentActivity(), themeDelegate); } catch (Exception e) { FileLog.e(e); alertUserOpenError(message); @@ -22695,9 +23052,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Bundle args = new Bundle(); long peerId = MessageObject.getPeerId(messageObject.messageOwner.from_id); if (peerId < 0) { - args.putInt("chat_id", -(int) peerId); //TODO long + args.putLong("chat_id", -peerId); } else { - args.putInt("user_id", (int) peerId); + args.putLong("user_id", peerId); } if (messageObject.botStartParam != null) { args.putString("inline_query", messageObject.botStartParam); @@ -22723,7 +23080,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not message = cell.getMessageObject(); } int maxReadId; - int linkedChatId; + long linkedChatId; if (message.messageOwner.replies != null) { maxReadId = message.messageOwner.replies.read_max_id; linkedChatId = message.messageOwner.replies.channel_id; @@ -22735,7 +23092,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } @Override - public String getAdminRank(int uid) { + public String getAdminRank(long uid) { if (ChatObject.isChannel(currentChat) && currentChat.megagroup) { return getMessagesController().getAdminRank(currentChat.id, uid); } @@ -22789,7 +23146,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not chatMessageCell.setAllowAssistant(true); } } else if (viewType == 1) { - view = new ChatActionCell(mContext) { + view = new ChatActionCell(mContext, themeDelegate) { @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); @@ -22798,11 +23155,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not info.setVisibleToUser(true); } }; + ((ChatActionCell) view).setInvalidateColors(true); ((ChatActionCell) view).setDelegate(new ChatActionCell.ChatActionCellDelegate() { @Override public void didClickImage(ChatActionCell cell) { MessageObject message = cell.getMessageObject(); - PhotoViewer.getInstance().setParentActivity(getParentActivity()); + PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate); TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, 640); if (photoSize != null) { ImageLocation imageLocation = ImageLocation.getForPhoto(photoSize, message.messageOwner.action.photo); @@ -22818,16 +23176,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } @Override - public void needOpenUserProfile(int uid) { + public void needOpenUserProfile(long uid) { if (uid < 0) { Bundle args = new Bundle(); - args.putInt("chat_id", -uid); + args.putLong("chat_id", -uid); if (getMessagesController().checkCanOpenChat(args, ChatActivity.this)) { presentFragment(new ChatActivity(args)); } } else if (uid != getUserConfig().getClientUserId()) { Bundle args = new Bundle(); - args.putInt("user_id", uid); + args.putLong("user_id", uid); if (currentEncryptedChat != null && uid == currentUser.id) { args.putLong("dialog_id", dialog_id); } @@ -22855,9 +23213,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); } else if (viewType == 2) { - view = new ChatUnreadCell(mContext); + view = new ChatUnreadCell(mContext, themeDelegate); } else if (viewType == 3) { - view = new BotHelpCell(mContext); + view = new BotHelpCell(mContext, themeDelegate); ((BotHelpCell) view).setDelegate(url -> { if (url.startsWith("@")) { getMessagesController().openByUserName(url.substring(1), ChatActivity.this, 0); @@ -22875,7 +23233,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); } else if (viewType == 4) { - view = new ChatLoadingCell(mContext, contentView); + view = new ChatLoadingCell(mContext, contentView, themeDelegate); } view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new RecyclerListView.Holder(view); @@ -22970,7 +23328,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedBottom = false; } } else if (currentChat != null) { - int fromId = nextMessage.getFromChatId(); + long fromId = nextMessage.getFromChatId(); pinnedBottom = fromId == message.getFromChatId(); if (!pinnedBottomByGroup && pinnedBottom && fromId < 0 && currentChat.megagroup) { pinnedBottom = false; @@ -23005,7 +23363,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not pinnedTop = false; } } else if (currentChat != null) { - int fromId = prevMessage.getFromChatId(); + long fromId = prevMessage.getFromChatId(); pinnedTop = fromId == message.getFromChatId() && !message.isImportedForward() && !prevMessage.isImportedForward(); if (!pinnedTopByGroup && pinnedTop && fromId < 0 && currentChat.megagroup) { pinnedTop = false; @@ -23638,7 +23996,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not String urlTmp = urlFinal.replace("tg:privatepost", "tg://telegram.org").replace("tg://privatepost", "tg://telegram.org"); Uri data = Uri.parse(urlTmp); int messageId = Utilities.parseInt(data.getQueryParameter("post")); - int channelId = Utilities.parseInt(data.getQueryParameter("channel")); + long channelId = Utilities.parseLong(data.getQueryParameter("channel")); int threadId = Utilities.parseInt(data.getQueryParameter("thread")); if (channelId == currentChat.id && messageId != 0) { if (threadId != 0) { @@ -23725,7 +24083,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not Matcher matcher = privateMsgUrlPattern.matcher(urlFinal); if (matcher.find(2) && matcher.find(3)) { - int channelId = Integer.parseInt(matcher.group(2)); + long channelId = Long.parseLong(matcher.group(2)); int messageId = Integer.parseInt(matcher.group(3)); if (channelId == currentChat.id && messageId != 0) { Uri data = Uri.parse(urlFinal); @@ -23813,8 +24171,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not @Override public ArrayList getThemeDescriptions() { + if (isPauseOnThemePreview) { + isPauseOnThemePreview = false; + return null; + } ThemeDescription.ThemeDescriptionDelegate selectedBackgroundDelegate = () -> { - updateVisibleRows(); if (chatActivityEnterView != null) { chatActivityEnterView.updateColors(); } @@ -23828,6 +24189,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not View child = chatListView.getChildAt(a); if (child instanceof ChatMessageCell) { ((ChatMessageCell) child).createSelectorDrawable(0); + } else if (child instanceof ChatActionCell) { + ((ChatActionCell) child).setInvalidateColors(true); } } } @@ -23842,13 +24205,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } if (scrimPopupWindowItems != null) { for (int a = 0; a < scrimPopupWindowItems.length; a++) { - scrimPopupWindowItems[a].setColors(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon)); - scrimPopupWindowItems[a].setSelectorColor(Theme.getColor(Theme.key_dialogButtonSelector)); + scrimPopupWindowItems[a].setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon)); + scrimPopupWindowItems[a].setSelectorColor(getThemedColor(Theme.key_dialogButtonSelector)); } } if (scrimPopupWindow != null) { final View contentView = scrimPopupWindow.getContentView(); - contentView.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + contentView.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); contentView.invalidate(); } @@ -23862,6 +24225,16 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (chatActivityEnterTopView != null && chatActivityEnterTopView.getEditView() != null) { chatActivityEnterTopView.getEditView().updateColors(); } + if (headerItem != null) { + headerItem.updateColor(); + } + setNavigationBarColor(getThemedColor(Theme.key_windowBackgroundGray)); + if (fragmentContextView != null) { + fragmentContextView.updateColors(); + } + if (avatarContainer != null) { + avatarContainer.updateColors(); + } }; ArrayList themeDescriptions = new ArrayList<>(); @@ -23876,6 +24249,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector)); + themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle)); + themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SUBTITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultSubtitle)); } else { themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarActionModeDefault)); themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarActionModeDefaultIcon)); @@ -23921,22 +24296,37 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageCyan)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessageBlue)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_avatar_nameInMessagePink)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, BotHelpCell.class}, null, new Drawable[]{Theme.chat_msgInDrawable, Theme.chat_msgInMediaDrawable}, null, Theme.key_chat_inBubble)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedDrawable, Theme.chat_msgInMediaSelectedDrawable}, null, Theme.key_chat_inBubbleSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInMediaDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutMediaDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedDrawable, Theme.chat_msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedDrawable, Theme.chat_msgOutSelectedDrawable}, null, Theme.key_chat_outBubbleGradientSelectedOverlay)); - themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceText)); - themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatActionCell.class}, Theme.chat_actionTextPaint, null, null, Theme.key_chat_serviceLink)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_botCardDrawalbe, Theme.chat_shareIconDrawable, Theme.chat_replyIconDrawable, Theme.chat_botInlineDrawable, Theme.chat_botLinkDrawalbe, Theme.chat_goIconDrawable, Theme.chat_commentStickerDrawable}, null, Theme.key_chat_serviceIcon)); + Theme.MessageDrawable msgInDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgIn); + Theme.MessageDrawable msgInMediaDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMedia); + Theme.MessageDrawable msgInSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInSelected); + Theme.MessageDrawable msgInMediaSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgInMediaSelected); + Theme.MessageDrawable msgOutDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOut); + Theme.MessageDrawable msgOutMediaDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMedia); + Theme.MessageDrawable msgOutSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutSelected); + Theme.MessageDrawable msgOutMediaSelectedDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMediaSelected); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, BotHelpCell.class}, null, new Drawable[]{msgInDrawable, msgInMediaDrawable}, null, Theme.key_chat_inBubble)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgInSelectedDrawable, msgInMediaSelectedDrawable}, null, Theme.key_chat_inBubbleSelected)); + + if (msgInDrawable != null) { + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, msgInDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, msgInMediaDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, msgOutDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, msgOutMediaDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); + } + + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); + if (!themeDelegate.isThemeChangeAvailable()) { + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); + } + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutSelectedDrawable, msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutSelectedDrawable, msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleGradientSelectedOverlay)); + themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatActionCell.class}, getThemedPaint(Theme.key_paint_chatActionText), null, null, Theme.key_chat_serviceText)); + themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatActionCell.class}, getThemedPaint(Theme.key_paint_chatActionText), null, null, Theme.key_chat_serviceLink)); + + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_botCardDrawalbe, getThemedDrawable(Theme.key_drawable_shareIcon), getThemedDrawable(Theme.key_drawable_replyIcon), getThemedDrawable(Theme.key_drawable_botInline), getThemedDrawable(Theme.key_drawable_botLink), getThemedDrawable(Theme.key_drawable_goIcon), getThemedDrawable(Theme.key_drawable_commentSticker)}, null, Theme.key_chat_serviceIcon)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class, ChatActionCell.class}, null, null, null, Theme.key_chat_serviceBackgroundSelected)); @@ -23945,31 +24335,31 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class, BotHelpCell.class}, null, null, null, Theme.key_chat_messageLinkIn, null)); themeDescriptions.add(new ThemeDescription(chatListView, ThemeDescription.FLAG_LINKCOLOR, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_messageLinkOut, null)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgNoSoundDrawable}, null, Theme.key_chat_mediaTimeText)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckDrawable}, null, Theme.key_chat_outSentCheck)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadDrawable, Theme.chat_msgOutHalfCheckDrawable}, null, Theme.key_chat_outSentCheckRead)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutCheckReadSelectedDrawable, Theme.chat_msgOutHalfCheckSelectedDrawable}, null, Theme.key_chat_outSentCheckReadSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutClockDrawable}, null, Theme.key_chat_outSentClock)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedClockDrawable}, null, Theme.key_chat_outSentClockSelected)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInClockDrawable}, null, Theme.key_chat_inSentClock)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedClockDrawable}, null, Theme.key_chat_inSentClockSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCheck)}, null, Theme.key_chat_outSentCheck)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCheckSelected)}, null, Theme.key_chat_outSentCheckSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCheckRead), getThemedDrawable(Theme.key_drawable_msgOutHalfCheck)}, null, Theme.key_chat_outSentCheckRead)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCheckReadSelected), getThemedDrawable(Theme.key_drawable_msgOutHalfCheckSelected)}, null, Theme.key_chat_outSentCheckReadSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outSentClock)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outSentClockSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inSentClock)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inSentClockSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaCheckDrawable, Theme.chat_msgMediaHalfCheckDrawable}, null, Theme.key_chat_mediaSentCheck)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgStickerHalfCheckDrawable, Theme.chat_msgStickerCheckDrawable, Theme.chat_msgStickerClockDrawable, Theme.chat_msgStickerViewsDrawable, Theme.chat_msgStickerRepliesDrawable, Theme.chat_msgStickerPinnedDrawable}, null, Theme.key_chat_serviceText)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaClockDrawable}, null, Theme.key_chat_mediaSentClock)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsDrawable, Theme.chat_msgOutRepliesDrawable, Theme.chat_msgOutPinnedDrawable}, null, Theme.key_chat_outViews)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutViewsSelectedDrawable, Theme.chat_msgOutRepliesSelectedDrawable, Theme.chat_msgOutPinnedSelectedDrawable}, null, Theme.key_chat_outViewsSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgStickerHalfCheck), getThemedDrawable(Theme.key_drawable_msgStickerCheck), getThemedDrawable(Theme.key_drawable_msgStickerClock), getThemedDrawable(Theme.key_drawable_msgStickerViews), getThemedDrawable(Theme.key_drawable_msgStickerReplies), getThemedDrawable(Theme.key_drawable_msgStickerPinned)}, null, Theme.key_chat_serviceText)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_mediaSentClock)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutViews), getThemedDrawable(Theme.key_drawable_msgOutReplies), getThemedDrawable(Theme.key_drawable_msgOutPinned)}, null, Theme.key_chat_outViews)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutViewsSelected), getThemedDrawable(Theme.key_drawable_msgOutRepliesSelected), getThemedDrawable(Theme.key_drawable_msgOutPinnedSelected)}, null, Theme.key_chat_outViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsDrawable, Theme.chat_msgInRepliesDrawable, Theme.chat_msgInPinnedDrawable}, null, Theme.key_chat_inViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInViewsSelectedDrawable, Theme.chat_msgInRepliesSelectedDrawable, Theme.chat_msgInPinnedSelectedDrawable}, null, Theme.key_chat_inViewsSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaViewsDrawable, Theme.chat_msgMediaRepliesDrawable, Theme.chat_msgMediaPinnedDrawable}, null, Theme.key_chat_mediaViews)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuDrawable}, null, Theme.key_chat_outMenu)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutMenuSelectedDrawable}, null, Theme.key_chat_outMenuSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutMenu)}, null, Theme.key_chat_outMenu)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutMenuSelected)}, null, Theme.key_chat_outMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuDrawable}, null, Theme.key_chat_inMenu)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInMenuSelectedDrawable}, null, Theme.key_chat_inMenuSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgMediaMenuDrawable}, null, Theme.key_chat_mediaMenu)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutInstantDrawable}, null, Theme.key_chat_outInstant)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutInstant)}, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInInstantDrawable, Theme.chat_commentDrawable, Theme.chat_commentArrowDrawable}, null, Theme.key_chat_inInstant)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallDrawable, null, Theme.key_chat_outInstant)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutCallSelectedDrawable, null, Theme.key_chat_outInstantSelected)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCallAudio), getThemedDrawable(Theme.key_drawable_msgOutCallVideo)}, null, Theme.key_chat_outInstant)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{getThemedDrawable(Theme.key_drawable_msgOutCallAudioSelected), getThemedDrawable(Theme.key_drawable_msgOutCallVideoSelected)}, null, Theme.key_chat_outInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallDrawable, null, Theme.key_chat_inInstant)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInCallSelectedDrawable, null, Theme.key_chat_inInstantSelected)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgCallUpGreenDrawable}, null, Theme.key_chat_outGreenCall)); @@ -23986,9 +24376,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outPreviewInstantSelectedText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_deleteProgressPaint, null, null, Theme.key_chat_secretTimeText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_stickerNameText)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_botButtonPaint, null, null, Theme.key_chat_botButtonText)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, getThemedPaint(Theme.key_paint_chatBotButton), null, null, Theme.key_chat_botButtonText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_botProgressPaint, null, null, Theme.key_chat_botProgress)); - themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, Theme.chat_timeBackgroundPaint, null, null, Theme.key_chat_mediaTimeBackground)); + themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, getThemedPaint(Theme.key_paint_chatTimeBackground), null, null, Theme.key_chat_mediaTimeBackground)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_outForwardedNameText)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, null, null, Theme.key_chat_inPsaNameText)); @@ -24119,35 +24509,37 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_psaHelpDrawable[0]}, null, Theme.key_chat_inViews)); themeDescriptions.add(new ThemeDescription(chatListView, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_psaHelpDrawable[1]}, null, Theme.key_chat_outViews)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_countPaint, null, null, Theme.key_chats_unreadCounter)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Paint[]{Theme.dialogs_namePaint[0], Theme.dialogs_namePaint[1], Theme.dialogs_searchNamePaint}, null, null, Theme.key_chats_name)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Paint[]{Theme.dialogs_nameEncryptedPaint[0], Theme.dialogs_nameEncryptedPaint[1], Theme.dialogs_searchNameEncryptedPaint}, null, null, Theme.key_chats_secretName)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_lockDrawable}, null, Theme.key_chats_secretIcon)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_groupDrawable, Theme.dialogs_broadcastDrawable, Theme.dialogs_botDrawable}, null, Theme.key_chats_nameIcon)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_scamDrawable, Theme.dialogs_fakeDrawable}, null, Theme.key_chats_draft)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_messagePaint[1], null, null, Theme.key_chats_message_threeLines)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_messageNamePaint, null, null, Theme.key_chats_nameMessage_threeLines)); - themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chats_nameMessage)); - themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chats_attachMessage)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, Theme.dialogs_messagePrintingPaint, null, null, Theme.key_chats_actionMessage)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_timePaint, null, null, Theme.key_chats_date)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_checkDrawable}, null, Theme.key_chats_sentCheck)); - themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_checkReadDrawable, Theme.dialogs_halfCheckDrawable}, null, Theme.key_chats_sentReadCheck)); + if (!themeDelegate.isThemeChangeAvailable()) { + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_countPaint, null, null, Theme.key_chats_unreadCounter)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Paint[]{Theme.dialogs_namePaint[0], Theme.dialogs_namePaint[1], Theme.dialogs_searchNamePaint}, null, null, Theme.key_chats_name)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Paint[]{Theme.dialogs_nameEncryptedPaint[0], Theme.dialogs_nameEncryptedPaint[1], Theme.dialogs_searchNameEncryptedPaint}, null, null, Theme.key_chats_secretName)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_lockDrawable}, null, Theme.key_chats_secretIcon)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_groupDrawable, Theme.dialogs_broadcastDrawable, Theme.dialogs_botDrawable}, null, Theme.key_chats_nameIcon)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_scamDrawable, Theme.dialogs_fakeDrawable}, null, Theme.key_chats_draft)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_messagePaint[1], null, null, Theme.key_chats_message_threeLines)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_messageNamePaint, null, null, Theme.key_chats_nameMessage_threeLines)); + themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chats_nameMessage)); + themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chats_attachMessage)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, Theme.dialogs_messagePrintingPaint, null, null, Theme.key_chats_actionMessage)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, Theme.dialogs_timePaint, null, null, Theme.key_chats_date)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_checkDrawable}, null, Theme.key_chats_sentCheck)); + themeDescriptions.add(new ThemeDescription(messagesSearchListView, 0, new Class[]{DialogCell.class}, null, new Drawable[]{Theme.dialogs_checkReadDrawable, Theme.dialogs_halfCheckDrawable}, null, Theme.key_chats_sentReadCheck)); + } - themeDescriptions.add(new ThemeDescription(mentionContainer, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(mentionContainer, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(mentionContainer, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); themeDescriptions.add(new ThemeDescription(mentionContainer, 0, null, null, new Drawable[]{Theme.chat_composeShadowRoundDrawable}, null, Theme.key_chat_messagePanelBackground)); - themeDescriptions.add(new ThemeDescription(searchContainer, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(searchContainer, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(searchContainer, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); - themeDescriptions.add(new ThemeDescription(bottomOverlay, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(bottomOverlay, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(bottomOverlay, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); - themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(bottomOverlayChat, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); - themeDescriptions.add(new ThemeDescription(bottomMessagesActionContainer, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(bottomMessagesActionContainer, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(bottomMessagesActionContainer, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); - themeDescriptions.add(new ThemeDescription(chatActivityEnterView, 0, null, Theme.chat_composeBackgroundPaint, null, null, Theme.key_chat_messagePanelBackground)); + themeDescriptions.add(new ThemeDescription(chatActivityEnterView, 0, null, getThemedPaint(Theme.key_paint_chatComposeBackground), null, null, Theme.key_chat_messagePanelBackground)); themeDescriptions.add(new ThemeDescription(chatActivityEnterView, 0, null, null, new Drawable[]{Theme.chat_composeShadowDrawable}, null, Theme.key_chat_messagePanelShadow)); themeDescriptions.add(new ThemeDescription(chatActivityEnterView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{ChatActivityEnterView.class}, new String[]{"messageEditText"}, null, null, null, Theme.key_chat_messagePanelText)); themeDescriptions.add(new ThemeDescription(chatActivityEnterView, ThemeDescription.FLAG_CURSORCOLOR, new Class[]{ChatActivityEnterView.class}, new String[]{"messageEditText"}, null, null, null, Theme.key_chat_messagePanelCursor)); @@ -24216,6 +24608,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not if (trendingStickersAlert != null) { themeDescriptions.addAll(trendingStickersAlert.getThemeDescriptions()); } + themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, new Drawable[]{chatActivityEnterView.getStickersArrowDrawable()}, null, Theme.key_chat_messagePanelIcons)); } for (int a = 0; a < 2; a++) { @@ -24355,6 +24748,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(avatarContainer != null ? avatarContainer.getTimeItem() : null, 0, null, null, null, null, Theme.key_chat_secretTimerBackground)); themeDescriptions.add(new ThemeDescription(avatarContainer != null ? avatarContainer.getTimeItem() : null, 0, null, null, null, null, Theme.key_chat_secretTimerText)); + themeDescriptions.add(new ThemeDescription(floatingDateView, 0, null, null, null, null, Theme.key_chat_serviceText)); + themeDescriptions.add(new ThemeDescription(floatingDateView, 0, null, null, null, null, Theme.key_chat_serviceBackground)); + themeDescriptions.add(new ThemeDescription(infoTopView, 0, null, null, null, null, Theme.key_chat_serviceText)); + themeDescriptions.add(new ThemeDescription(infoTopView, 0, null, null, null, null, Theme.key_chat_serviceBackground)); + themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chat_attachGalleryIcon)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chat_attachGalleryBackground)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, selectedBackgroundDelegate, Theme.key_chat_attachGalleryText)); @@ -24409,12 +24807,17 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_voipgroup_mutedByAdminGradient3)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_voipgroup_overlayAlertMutedByAdmin)); themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_voipgroup_overlayAlertMutedByAdmin2)); + themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, null, Theme.key_windowBackgroundGray)); if (chatActivityEnterView != null) { themeDescriptions.add(new ThemeDescription(chatActivityEnterView.botCommandsMenuContainer.listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{BotCommandsMenuView.BotCommandView.class}, new String[]{"description"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); themeDescriptions.add(new ThemeDescription(chatActivityEnterView.botCommandsMenuContainer.listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{BotCommandsMenuView.BotCommandView.class}, new String[]{"command"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); } + for (ThemeDescription description : themeDescriptions) { + description.resourcesProvider = themeDelegate; + } + return themeDescriptions; } @@ -24519,4 +24922,667 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not fragmentView.invalidate(); chatListView.invalidate(); } + + private void showChatThemeBottomSheet() { + chatThemeBottomSheet = new ChatThemeBottomSheet(ChatActivity.this, themeDelegate); + chatListView.setOnInterceptTouchListener(event -> true); + setChildrenEnabled(contentView, false); + showDialog(chatThemeBottomSheet, dialogInterface -> { + chatThemeBottomSheet = null; + chatListView.setOnInterceptTouchListener(null); + setChildrenEnabled(contentView, true); + ChatThemeController.clearWallpaperThumbImages(); + }); + } + + private void setChildrenEnabled(View view, boolean isEnabled) { + if (view instanceof ViewGroup) { + ViewGroup viewGroup = (ViewGroup) view; + for (int i = 0; i < viewGroup.getChildCount(); ++i) { + setChildrenEnabled(viewGroup.getChildAt(i), isEnabled); + } + } + if (view != chatListView && view != contentView) { + view.setEnabled(isEnabled); + } + } + + private void checkThemeEmoticon() { + if (!fragmentOpened) { + return; + } + String emoticon = null; + if (userInfo != null) { + emoticon = userInfo.theme_emoticon; + } + if (emoticon == null && chatInfo != null) { + emoticon = chatInfo.theme_emoticon; + } + setChatThemeEmoticon(emoticon); + } + + private void setChatThemeEmoticon(final String emoticon) { + ChatThemeController.getInstance(currentAccount).setDialogTheme(dialog_id, emoticon, false); + if (!TextUtils.isEmpty(emoticon)) { + ChatThemeController.requestChatTheme(emoticon, result -> { + themeDelegate.setCurrentTheme(result, openAnimationStartTime != 0, null); + }); + } else { + themeDelegate.setCurrentTheme(null, openAnimationStartTime != 0, null); + } + } + + @Override + public int getNavigationBarColor() { + return getThemedColor(Theme.key_windowBackgroundGray); + } + + @Override + public int getThemedColor(String key) { + Integer color = themeDelegate.getColor(key); + return color != null ? color : super.getThemedColor(key); + } + + @Override + public Drawable getThemedDrawable(String drawableKey) { + Drawable drawable = themeDelegate.getDrawable(drawableKey); + return drawable != null ? drawable : super.getThemedDrawable(drawableKey); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = themeDelegate.getPaint(paintKey); + return paint != null ? paint : Theme.getThemePaint(paintKey); + } + + public float getChatListViewPadding() { + return chatListViewPaddingTop; + } + + public FragmentContextView getFragmentContextView() { + return fragmentContextView; + } + + public Theme.ResourcesProvider getResourceProvider() { + return themeDelegate; + } + + public class ThemeDelegate implements Theme.ResourcesProvider, ChatActionCell.ThemeDelegate, ForwardingPreviewView.ResourcesDelegate { + + private final HashMap currentDrawables = new HashMap<>(); + private final HashMap currentPaints = new HashMap<>(); + private final Matrix actionMatrix = new Matrix(); + + private HashMap currentColors = new HashMap<>(); + private HashMap animatingColors; + private ChatTheme chatTheme; + private Drawable backgroundDrawable; + private ValueAnimator patternIntensityAnimator; + private Bitmap serviceBitmap; + private Bitmap serviceBitmapSource; + private Paint paint = new Paint(); + private Canvas serviceCanvas; + private BitmapShader serviceShader; + private int currentColor; + private boolean isDark; + private List cachedThemes; + private AnimatorSet patternAlphaAnimator; + + Theme.MessageDrawable animatingMessageDrawable; + Theme.MessageDrawable animatingMessageMediaDrawable; + + ThemeDelegate() { + isDark = Theme.getActiveTheme().isDark(); + boolean setup = false; + if (isThemeChangeAvailable()) { + chatTheme = ChatThemeController.getInstance(currentAccount).getDialogTheme(dialog_id); + if (chatTheme != null) { + setup = true; + setupChatTheme(chatTheme, false, true); + } + } + if (!setup) { + Theme.refreshThemeColors(); + } + } + + public List getCachedThemes() { + return cachedThemes; + } + + public void setCachedThemes(List cachedThemes) { + this.cachedThemes = cachedThemes; + } + + @Override + public Integer getColor(String key) { + if (chatTheme == null) { + return Theme.getColor(key); + } + if (animatingColors != null) { + Integer color = animatingColors.get(key); + if (color != null) { + return color; + } + } + Integer color = currentColors.get(key); + if (color == null) { + if (Theme.key_chat_outBubbleGradient1.equals(key) || Theme.key_chat_outBubbleGradient2.equals(key) || Theme.key_chat_outBubbleGradient3.equals(key)) { + color = currentColors.get(Theme.key_chat_outBubble); + if (color == null) { + color = Theme.getColorOrNull(key); + } + if (color == null) { + color = Theme.getColor(Theme.key_chat_outBubble); + } + } + if (color == null) { + String fallbackKey = Theme.getFallbackKey(key); + if (fallbackKey != null) { + color = currentColors.get(fallbackKey); + } + } + } + if (color == null) { + if (chatTheme != null) { + color = Theme.getDefaultColor(key); + } + } + return color; + } + + @Override + public Integer getCurrentColor(String key) { + return getCurrentColor(key, false); + } + + public Integer getCurrentColor(String key, boolean ignoreAnimation) { + if (chatTheme == null) { + return Theme.getColorOrNull(key); + } + Integer color = null; + if (!ignoreAnimation && animatingColors != null) { + color = animatingColors.get(key); + } + if (color == null) { + color = currentColors.get(key); + } + return color; + } + + @Override + public void setAnimatedColor(String key, int color) { + if (animatingColors != null) { + animatingColors.put(key, color); + } + } + + @Override + public void applyServiceShaderMatrix(int w, int h, float translationX, float translationY) { + if (chatTheme == null || serviceBitmap == null || serviceShader == null) { + ChatActionCell.ThemeDelegate.super.applyServiceShaderMatrix(w, h, translationX, translationY); + } else { + Theme.applyServiceShaderMatrix(serviceBitmap, serviceShader, actionMatrix, w, h, translationX, translationY); + } + } + + @Override + public int getCurrentColor() { + return chatTheme != null ? currentColor : Theme.currentColor; + } + + @Override + public boolean hasGradientService() { + return chatTheme != null ? serviceShader != null : Theme.hasGradientService(); + } + + @Override + public Drawable getDrawable(String drawableKey) { + return !currentDrawables.isEmpty() ? currentDrawables.get(drawableKey) : null; + } + + @Override + public Paint getPaint(String paintKey) { + return chatTheme != null ? currentPaints.get(paintKey) : null; + } + + public boolean isThemeChangeAvailable() { + return currentChat == null && currentEncryptedChat == null && !currentUser.bot && dialog_id >= 0; + } + + public ChatTheme getCurrentTheme() { + return chatTheme; + } + + @Override + public Drawable getWallpaperDrawable() { + return backgroundDrawable != null ? backgroundDrawable : Theme.getCachedWallpaperNonBlocking(); + } + + @Override + public boolean isWallpaperMotion() { + return chatTheme != null ? false : Theme.isWallpaperMotion(); + } + + public void setCurrentTheme(final ChatTheme chatTheme, boolean animated, Boolean forceDark) { + if (parentLayout == null) { + return; + } + final ChatTheme prevTheme = this.chatTheme; + boolean newIsDark = forceDark != null ? forceDark : Theme.getActiveTheme().isDark(); + String newEmoticon = chatTheme != null ? chatTheme.getEmoticon() : null; + String oldEmoticon = this.chatTheme != null ? this.chatTheme.getEmoticon() : null; + if (!isThemeChangeAvailable() || (TextUtils.equals(oldEmoticon, newEmoticon) && this.isDark == newIsDark)) { + return; + } + this.isDark = newIsDark; + + Theme.ThemeInfo currentTheme = newIsDark ? Theme.getCurrentNightTheme() : Theme.getCurrentTheme(); + ActionBarLayout.ThemeAnimationSettings animationSettings = new ActionBarLayout.ThemeAnimationSettings(currentTheme, currentTheme.currentAccentId, currentTheme.isDark(), !animated); + + if (this.chatTheme == null) { + Drawable background = Theme.getCachedWallpaperNonBlocking(); + isBackgroundMotion = background instanceof MotionBackgroundDrawable; + initServiceMessageColors(background); + startServiceTextColor = isBackgroundMotion ? 0xffffffff : Theme.getColor(Theme.key_chat_serviceText); + startServiceLinkColor = isBackgroundMotion ? 0xffffffff : Theme.getColor(Theme.key_chat_serviceLink); + startServiceButtonColor = isBackgroundMotion ? 0xffffffff : Theme.getColor(Theme.key_chat_serviceLink); + startServiceIconColor = isBackgroundMotion ? 0xffffffff : Theme.getColor(Theme.key_chat_serviceIcon); + } else if (isBackgroundMotion) { + startServiceBitmap = ((MotionBackgroundDrawable) backgroundDrawable).getBitmap(); + } + startServiceColor = currentServiceColor; + startServiceTextColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceText, true); + startServiceLinkColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceLink, true); + startServiceButtonColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceLink, true); + startServiceIconColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceIcon, true); + + if (chatTheme != null) { + int[] colors = AndroidUtilities.calcDrawableColor(backgroundDrawable); + currentColor = colors[0]; + initDrawables(); + initPaints(); + } + + animationSettings.applyTheme = false; + animationSettings.afterStartDescriptionsAddedRunnable = () -> { + setupChatTheme(chatTheme, animated, false); + initServiceMessageColors(backgroundDrawable); + }; + if (animated) { + animationSettings.animationProgress = new ActionBarLayout.ThemeAnimationSettings.onAnimationProgress() { + @Override + public void setProgress(float p) { + animatingMessageDrawable.crossfadeProgress = p; + animatingMessageMediaDrawable.crossfadeProgress = p; + updateServiceMessageColor(p); + } + }; + animationSettings.beforeAnimationRunnable = () -> { + animatingColors = new HashMap<>(); + animatingMessageDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOut); + animatingMessageDrawable.crossfadeFromDrawable = parentLayout.messageDrawableOutStart; + animatingMessageMediaDrawable = (Theme.MessageDrawable) getThemedDrawable(Theme.key_drawable_msgOutMedia); + animatingMessageMediaDrawable.crossfadeFromDrawable = parentLayout.messageDrawableOutMediaStart; + updateServiceMessageColor(0); + }; + animationSettings.afterAnimationRunnable = () -> { + animatingMessageDrawable.crossfadeFromDrawable = null; + animatingMessageMediaDrawable.crossfadeFromDrawable = null; + animatingColors = null; + updateServiceMessageColor(1f); + }; + } + animationSettings.onlyTopFragment = true; + animationSettings.resourcesProvider = this; + animationSettings.duration = 250; + parentLayout.animateThemedValues(animationSettings); + } + + private void setupChatTheme(ChatTheme chatTheme, boolean withAnimation, boolean createNewResources) { + this.chatTheme = chatTheme; + + Drawable prevDrawable = null; + if (fragmentView != null) { + prevDrawable = ((SizeNotifierFrameLayout) fragmentView).getBackgroundImage(); + } + final MotionBackgroundDrawable prevMotionDrawable = (prevDrawable instanceof MotionBackgroundDrawable) ? (MotionBackgroundDrawable) prevDrawable : null; + final int prevPhase = prevMotionDrawable != null ? prevMotionDrawable.getPhase() : 0; + + if (chatTheme == null || chatTheme.isDefault) { + currentColor = Theme.getServiceMessageColor(); + } + if (chatTheme == null) { + currentColors = new HashMap<>(); + currentPaints.clear(); + currentDrawables.clear(); + Drawable wallpaper = Theme.getCachedWallpaperNonBlocking(); + if (wallpaper instanceof MotionBackgroundDrawable) { + ((MotionBackgroundDrawable) wallpaper).setPhase(prevPhase); + } + backgroundDrawable = null; + + Theme.ThemeInfo activeTheme; + if (Theme.getActiveTheme().isDark() == isDark) { + activeTheme = Theme.getCurrentTheme(); + } else { + SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE); + String dayThemeName = preferences.getString("lastDayTheme", "Blue"); + if (Theme.getTheme(dayThemeName) == null) { + dayThemeName = "Blue"; + } + String nightThemeName = preferences.getString("lastDarkTheme", "Dark Blue"); + if (Theme.getTheme(nightThemeName) == null) { + nightThemeName = "Dark Blue"; + } + activeTheme = isDark ? Theme.getTheme(nightThemeName) : Theme.getTheme(dayThemeName); + } + + + Theme.applyTheme(activeTheme, false, isDark); + } else { + currentColors = chatTheme.getCurrentColors(currentAccount, isDark); + backgroundDrawable = getBackgroundDrawableFromTheme(chatTheme, prevPhase); + + if (patternAlphaAnimator != null) { + patternAlphaAnimator.cancel(); + } + if (withAnimation) { + patternAlphaAnimator = new AnimatorSet(); + if (prevMotionDrawable != null) { + ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0f); + valueAnimator.addUpdateListener(animator -> prevMotionDrawable.setPatternAlpha((float) animator.getAnimatedValue())); + valueAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + prevMotionDrawable.setPatternAlpha(1f); + } + }); + valueAnimator.setDuration(200); + patternAlphaAnimator.playTogether(valueAnimator); + } + if (backgroundDrawable instanceof MotionBackgroundDrawable) { + final MotionBackgroundDrawable currentBackgroundDrawable = (MotionBackgroundDrawable) backgroundDrawable; + currentBackgroundDrawable.setPatternAlpha(0f); + ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f); + valueAnimator.addUpdateListener(animator -> currentBackgroundDrawable.setPatternAlpha((float) animator.getAnimatedValue())); + valueAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + currentBackgroundDrawable.setPatternAlpha(1f); + } + }); + valueAnimator.setDuration(250); + patternAlphaAnimator.playTogether(valueAnimator); + } + patternAlphaAnimator.start(); + } + + if (createNewResources) { + int[] colors = AndroidUtilities.calcDrawableColor(backgroundDrawable); + currentColor = colors[0]; + initDrawables(); + initPaints(); + initServiceMessageColors(backgroundDrawable); + updateServiceMessageColor(1f); + } + + } + } + + private void initDrawables() { + Map chatDrawablesMap = Theme.getThemeDrawablesMap(); + for (Map.Entry entry : chatDrawablesMap.entrySet()) { + Drawable drawable; + switch (entry.getKey()) { + case Theme.key_drawable_msgIn: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, false, false, this); + break; + case Theme.key_drawable_msgInSelected: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, false, true, this); + break; + case Theme.key_drawable_msgInMedia: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, false, false, this); + break; + case Theme.key_drawable_msgInMediaSelected: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, false, true, this); + break; + case Theme.key_drawable_msgOut: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, true, false, this); + break; + case Theme.key_drawable_msgOutSelected: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, true, true, this); + break; + case Theme.key_drawable_msgOutMedia: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, true, false, this); + break; + case Theme.key_drawable_msgOutMediaSelected: + drawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, true, true, this); + break; + default: + drawable = entry.getValue(); + Drawable.ConstantState constantState = drawable.getConstantState(); + if (constantState != null) { + drawable = constantState.newDrawable().mutate(); + } else { + drawable = null; + } + if (drawable != null) { + String colorKey = Theme.getThemeDrawableColorKey(entry.getKey()); + if (colorKey != null) { + Integer color = getColor(colorKey); + if (color == null) { + color = Theme.getColor(colorKey); + } + Theme.setDrawableColor(drawable, color); + } + } + } + if (drawable != null) { + currentDrawables.put(entry.getKey(), drawable); + } + } + } + + private void initPaints() { + Map chatPaintsMap = Theme.getThemePaintsMap(); + for (Map.Entry entry : chatPaintsMap.entrySet()) { + Paint oldPaint = entry.getValue(); + Paint newPaint; + if (oldPaint instanceof TextPaint) { + newPaint = new TextPaint(); + newPaint.setTextSize(oldPaint.getTextSize()); + newPaint.setTypeface(oldPaint.getTypeface()); + } else { + newPaint = new Paint(); + } + if ((oldPaint.getFlags() & Paint.ANTI_ALIAS_FLAG) != 0) { + newPaint.setFlags(Paint.ANTI_ALIAS_FLAG); + } + + String colorKey = Theme.getThemePaintColorKey(entry.getKey()); + if (colorKey != null) { + Integer color = getColor(colorKey); + if (color == null) { + color = Theme.getColor(colorKey); + } + newPaint.setColor(color); + } + currentPaints.put(entry.getKey(), newPaint); + } + } + + int startServiceTextColor; + int startServiceLinkColor; + int startServiceButtonColor; + int startServiceIconColor; + int startServiceColor; + Bitmap startServiceBitmap; + + int currentServiceColor; + boolean isBackgroundMotion; + + private void initServiceMessageColors(Drawable backgroundDrawable) { + int[] result = AndroidUtilities.calcDrawableColor(backgroundDrawable); + int currentServiceMessageColor = result[0]; + + Integer serviceColor = getCurrentColor(Theme.key_chat_serviceBackground); + Integer serviceColor2 = serviceColor; + if (serviceColor == null) { + serviceColor = currentServiceMessageColor; + } + currentServiceColor = serviceColor; + + isBackgroundMotion = backgroundDrawable instanceof MotionBackgroundDrawable; + + if (isBackgroundMotion) { + serviceBitmap = Bitmap.createBitmap(60, 80, Bitmap.Config.ARGB_8888); + serviceBitmapSource = ((MotionBackgroundDrawable) backgroundDrawable).getBitmap(); + serviceCanvas = new Canvas(serviceBitmap); + serviceCanvas.drawBitmap(serviceBitmapSource, 0, 0, null); + serviceShader = new BitmapShader(serviceBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + } else { + serviceBitmap = null; + serviceShader = null; + } + + Paint actionBackgroundPaint = getPaint(Theme.key_paint_chatActionBackground); + Paint actionBackgroundSelectedPaint = getPaint(Theme.key_paint_chatActionBackgroundSelected); + + if (actionBackgroundPaint != null) { + if (isBackgroundMotion) { + ColorMatrix colorMatrix = new ColorMatrix(); + colorMatrix.setSaturation(((MotionBackgroundDrawable) backgroundDrawable).getIntensity() >= 0 ? 1.8f : 0.5f); + actionBackgroundPaint.setAlpha(127); + actionBackgroundPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); + actionBackgroundPaint.setShader(serviceShader); + actionBackgroundSelectedPaint.setAlpha(127); + actionBackgroundSelectedPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); + actionBackgroundSelectedPaint.setShader(serviceShader); + } else { + actionBackgroundPaint.setColorFilter(null); + actionBackgroundPaint.setShader(null); + actionBackgroundSelectedPaint.setColorFilter(null); + actionBackgroundSelectedPaint.setShader(null); + } + } + } + + private void updateServiceMessageColor(float progress) { + if (currentPaints.isEmpty()) { + return; + } + Paint actionBackgroundPaint = getPaint(Theme.key_paint_chatActionBackground); + Paint actionBackgroundSelectedPaint = getPaint(Theme.key_paint_chatActionBackgroundSelected); + + int serviceColor = currentServiceColor; + int serviceTextColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceText, true); + int serviceLinkColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceLink, true); + int serviceButtonColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceLink, true); + int serviceIconColor = isBackgroundMotion ? 0xffffffff : getCurrentColorOrDefault(Theme.key_chat_serviceIcon, true); + if (progress != 1f) { + serviceColor = ColorUtils.blendARGB(startServiceColor, serviceColor, progress); + serviceTextColor = ColorUtils.blendARGB(startServiceTextColor, serviceTextColor, progress); + serviceLinkColor = ColorUtils.blendARGB(startServiceLinkColor, serviceLinkColor, progress); + serviceButtonColor = ColorUtils.blendARGB(startServiceButtonColor, serviceButtonColor, progress); + serviceIconColor = ColorUtils.blendARGB(startServiceIconColor, serviceIconColor, progress); + } + if (actionBackgroundPaint != null && !isBackgroundMotion) { + actionBackgroundPaint.setColor(serviceColor); + actionBackgroundSelectedPaint.setColor(serviceColor); + } + + currentColor = serviceColor; + + Paint linkPaint = getPaint(Theme.key_paint_chatActionText); + if (linkPaint != null) { + ((TextPaint) linkPaint).linkColor = serviceLinkColor; + getPaint(Theme.key_paint_chatActionText).setColor(serviceTextColor); + getPaint(Theme.key_paint_chatBotButton).setColor(serviceButtonColor); + } + + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerCheck), serviceTextColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerClock), serviceTextColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerHalfCheck), serviceTextColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerPinned), serviceTextColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerReplies), serviceTextColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_msgStickerViews), serviceTextColor); + + Theme.setDrawableColor(getDrawable(Theme.key_drawable_botInline), serviceIconColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_botLink), serviceIconColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_commentSticker), serviceIconColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_goIcon), serviceIconColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_replyIcon), serviceIconColor); + Theme.setDrawableColor(getDrawable(Theme.key_drawable_shareIcon), serviceIconColor); + + if (serviceCanvas != null && serviceBitmapSource != null) { + if (progress != 1f && startServiceBitmap != null) { + serviceCanvas.drawBitmap(startServiceBitmap, 0, 0, null); + paint.setAlpha((int) (255 * progress)); + serviceCanvas.drawBitmap(serviceBitmapSource, 0, 0, paint); + } else { + serviceCanvas.drawBitmap(serviceBitmapSource, 0, 0, null); + } + } + } + + private Drawable getBackgroundDrawableFromTheme(ChatTheme chatTheme, int prevPhase) { + Drawable drawable; + if (chatTheme.isDefault) { + Theme.ThemeInfo themeInfo = ChatTheme.getDefaultThemeInfo(isDark); + HashMap currentColors = chatTheme.getCurrentColors(currentAccount, isDark); + String wallpaperLink = chatTheme.getWallpaperLink(isDark); + Theme.BackgroundDrawableSettings settings = Theme.createBackgroundDrawable(themeInfo, currentColors, wallpaperLink, prevPhase); + drawable = settings.wallpaper; + } else { + Integer backgroundColor = getColor(Theme.key_chat_wallpaper); + Integer gradientColor1 = getColor(Theme.key_chat_wallpaper_gradient_to1); + Integer gradientColor2 = getColor(Theme.key_chat_wallpaper_gradient_to2); + Integer gradientColor3 = getColor(Theme.key_chat_wallpaper_gradient_to3); + if (gradientColor3 == null) { + gradientColor3 = 0; + } + + MotionBackgroundDrawable motionDrawable = new MotionBackgroundDrawable(); + motionDrawable.setPatternBitmap(chatTheme.getWallpaper(isDark).settings.intensity); + motionDrawable.setColors(backgroundColor, gradientColor1, gradientColor2, gradientColor3, true); + motionDrawable.setPhase(prevPhase); + int patternColor = motionDrawable.getPatternColor(); + final boolean isDarkTheme = isDark; + chatTheme.loadWallpaper(isDark, pair -> { + if (pair == null) { + return; + } + long themeId = pair.first; + Bitmap bitmap = pair.second; + if (this.chatTheme != null && themeId == this.chatTheme.getTlTheme(isDark).id && bitmap != null) { + if (patternIntensityAnimator != null) { + patternIntensityAnimator.cancel(); + } + int intensity = chatTheme.getWallpaper(isDarkTheme).settings.intensity; + motionDrawable.setPatternBitmap(intensity, bitmap); + motionDrawable.setPatternColorFilter(patternColor); + patternIntensityAnimator = ValueAnimator.ofFloat(0, 1f); + patternIntensityAnimator.addUpdateListener(animator -> { + float value = (float) animator.getAnimatedValue(); + motionDrawable.setPatternAlpha(value); + }); + patternIntensityAnimator.setDuration(250); + patternIntensityAnimator.start(); + } + }); + drawable = motionDrawable; + } + return drawable; + } + + private int getCurrentColorOrDefault(String key, boolean ignoreAnimation) { + Integer color = getCurrentColor(key, ignoreAnimation); + if (color == null) { + color = Theme.getColor(key, null, ignoreAnimation); + } + return color; + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatEditActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatEditActivity.java index dd93185e2..a77832b18 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatEditActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatEditActivity.java @@ -125,7 +125,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image private TLRPC.FileLocation avatar; private TLRPC.Chat currentChat; private TLRPC.ChatFull info; - private int chatId; + private long chatId; private boolean signMessages; private boolean isChannel; @@ -185,16 +185,16 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image super(args); avatarDrawable = new AvatarDrawable(); imageUpdater = new ImageUpdater(true); - chatId = args.getInt("chat_id", 0); + chatId = args.getLong("chat_id", 0); } @Override public boolean onFragmentCreate() { - currentChat = MessagesController.getInstance(currentAccount).getChat(chatId); + currentChat = getMessagesController().getChat(chatId); if (currentChat == null) { currentChat = MessagesStorage.getInstance(currentAccount).getChatSync(chatId); if (currentChat != null) { - MessagesController.getInstance(currentAccount).putChat(currentChat, true); + getMessagesController().putChat(currentChat, true); } else { return false; } @@ -794,7 +794,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image blockCell.setVisibility(ChatObject.isChannel(currentChat) || currentChat.creator || ChatObject.hasAdminRights(currentChat) && ChatObject.canChangeChatInfo(currentChat) ? View.VISIBLE : View.GONE); blockCell.setOnClickListener(v -> { Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); args.putInt("type", !isChannel && !currentChat.gigagroup ? ChatUsersActivity.TYPE_KICKED : ChatUsersActivity.TYPE_BANNED); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(info); @@ -813,7 +813,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image adminCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); adminCell.setOnClickListener(v -> { Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_ADMIN); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(info); @@ -824,7 +824,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image membersCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); membersCell.setOnClickListener(v -> { Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_USERS); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(info); @@ -900,13 +900,13 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image deleteContainer.addView(deleteCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); deleteCell.setOnClickListener(v -> AlertsCreator.createClearOrDeleteDialogAlert(ChatEditActivity.this, false, true, false, currentChat, null, false, true, (param) -> { if (AndroidUtilities.isTablet()) { - getNotificationCenter().postNotificationName(NotificationCenter.closeChats, -(long) chatId); + getNotificationCenter().postNotificationName(NotificationCenter.closeChats, -chatId); } else { getNotificationCenter().postNotificationName(NotificationCenter.closeChats); } finishFragment(); - getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, (long) -currentChat.id, null, currentChat, param); - })); + getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, -currentChat.id, null, currentChat, param); + }, null)); deleteInfoCell = new ShadowSectionCell(context); deleteInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); @@ -947,7 +947,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image if (avatarImage == null) { return; } - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat == null) { return; } @@ -1025,7 +1025,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image AndroidUtilities.runOnUIThread(() -> { avatar = smallSize.location; if (photo != null || video != null) { - MessagesController.getInstance(currentAccount).changeChatAvatar(chatId, null, photo, video, videoStartTimestamp, videoPath, smallSize.location, bigSize.location, null); + getMessagesController().changeChatAvatar(chatId, null, photo, video, videoStartTimestamp, videoPath, smallSize.location, bigSize.location, null); if (createAfterUpload) { try { if (progressDialog != null && progressDialog.isShowing()) { @@ -1112,13 +1112,13 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image } donePressed = true; if (!ChatObject.isChannel(currentChat) && !historyHidden) { - MessagesController.getInstance(currentAccount).convertToMegaGroup(getParentActivity(), chatId, this, param -> { + getMessagesController().convertToMegaGroup(getParentActivity(), chatId, this, param -> { if (param == 0) { donePressed = false; return; } chatId = param; - currentChat = MessagesController.getInstance(currentAccount).getChat(param); + currentChat = getMessagesController().getChat(param); donePressed = false; if (info != null) { info.hidden_prehistory = true; @@ -1131,7 +1131,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image if (info != null) { if (ChatObject.isChannel(currentChat) && info.hidden_prehistory != historyHidden) { info.hidden_prehistory = historyHidden; - MessagesController.getInstance(currentAccount).toogleChannelInvitesHistory(chatId, historyHidden); + getMessagesController().toogleChannelInvitesHistory(chatId, historyHidden); } } @@ -1148,15 +1148,15 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image } if (!currentChat.title.equals(nameTextView.getText().toString())) { - MessagesController.getInstance(currentAccount).changeChatTitle(chatId, nameTextView.getText().toString()); + getMessagesController().changeChatTitle(chatId, nameTextView.getText().toString()); } String about = info != null && info.about != null ? info.about : ""; if (descriptionTextView != null && !about.equals(descriptionTextView.getText().toString())) { - MessagesController.getInstance(currentAccount).updateChatAbout(chatId, descriptionTextView.getText().toString(), info); + getMessagesController().updateChatAbout(chatId, descriptionTextView.getText().toString(), info); } if (signMessages != currentChat.signatures) { currentChat.signatures = true; - MessagesController.getInstance(currentAccount).toogleChannelSignatures(chatId, signMessages); + getMessagesController().toogleChannelSignatures(chatId, signMessages); } finishFragment(); } @@ -1244,7 +1244,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image info = chatFull; if (chatFull != null) { if (currentChat == null) { - currentChat = MessagesController.getInstance(currentAccount).getChat(chatId); + currentChat = getMessagesController().getChat(chatId); } historyHidden = !ChatObject.isChannel(currentChat) || info.hidden_prehistory; } @@ -1252,7 +1252,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image private void updateFields(boolean updateChat) { if (updateChat) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat != null) { currentChat = chat; } @@ -1325,7 +1325,7 @@ public class ChatEditActivity extends BaseFragment implements ImageUpdater.Image if (isPrivate) { link = LocaleController.getString("TypeLocationGroupEdit", R.string.TypeLocationGroupEdit); } else { - link = String.format("https://" + MessagesController.getInstance(currentAccount).linkPrefix + "/%s", currentChat.username); + link = String.format("https://" + getMessagesController().linkPrefix + "/%s", currentChat.username); } typeCell.setTextAndValue(LocaleController.getString("TypeLocationGroup", R.string.TypeLocationGroup), link, historyCell != null && historyCell.getVisibility() == View.VISIBLE || linkedCell != null && linkedCell.getVisibility() == View.VISIBLE); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatEditTypeActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatEditTypeActivity.java index ed24ddce5..ec6c659b6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatEditTypeActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatEditTypeActivity.java @@ -85,7 +85,7 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe private TLRPC.Chat currentChat; private TLRPC.ChatFull info; - private int chatId; + private long chatId; private boolean isChannel; private boolean canCreatePublic = true; @@ -104,12 +104,12 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe private boolean ignoreTextChanges; private boolean isForcePublic; - HashMap usersMap = new HashMap<>(); + HashMap usersMap = new HashMap<>(); private final static int done_button = 1; private InviteLinkBottomSheet inviteLinkBottomSheet; - public ChatEditTypeActivity(int id, boolean forcePublic) { + public ChatEditTypeActivity(long id, boolean forcePublic) { chatId = id; isForcePublic = forcePublic; } @@ -388,11 +388,6 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe manageLinksTextView = new TextCell(context); manageLinksTextView.setBackgroundDrawable(Theme.getSelectorDrawable(true)); - manageLinksTextView.setOnClickListener(v -> { - if (invite == null) { - return; - } - }); manageLinksTextView.setTextAndIcon(LocaleController.getString("ManageInviteLinks", R.string.ManageInviteLinks), R.drawable.actions_link, false); manageLinksTextView.setOnClickListener(v -> { ManageLinksActivity fragment = new ManageLinksActivity(chatId, 0, 0); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatLinkActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatLinkActivity.java index 11ba705c1..d956f7ddf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatLinkActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatLinkActivity.java @@ -74,7 +74,7 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter private boolean waitingForChatCreate; private boolean chatsLoaded; - private int currentChatId; + private long currentChatId; private int helpRow; private int createChatRow; @@ -96,7 +96,7 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter private int currentAccount = UserConfig.selectedAccount; - private static final String stickerSetName = "tg_placeholders"; + private static final String stickerSetName = AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME; public EmptyView(Context context) { super(context); @@ -158,16 +158,16 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter } } - public ChatLinkActivity(int chatId) { + public ChatLinkActivity(long chatId) { super(); currentChatId = chatId; - currentChat = MessagesController.getInstance(currentAccount).getChat(chatId); + currentChat = getMessagesController().getChat(chatId); isChannel = ChatObject.isChannel(currentChat) && !currentChat.megagroup; } private void updateRows() { - currentChat = MessagesController.getInstance(currentAccount).getChat(currentChatId); + currentChat = getMessagesController().getChat(currentChatId); if (currentChat == null) { return; } @@ -340,7 +340,7 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter showLinkAlert(chat, true); } else { Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); presentFragment(new ChatActivity(args)); } return; @@ -348,9 +348,8 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter if (position == createChatRow) { if (isChannel && info.linked_chat_id == 0) { Bundle args = new Bundle(); - ArrayList result = new ArrayList<>(); - result.add(getUserConfig().getClientUserId()); - args.putIntegerArrayList("result", result); + long[] array = new long[]{getUserConfig().getClientUserId()}; + args.putLongArray("result", array); args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP); GroupCreateFinalActivity activity = new GroupCreateFinalActivity(args); activity.setDelegate(new GroupCreateFinalActivity.GroupCreateFinalActivityDelegate() { @@ -360,7 +359,7 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter } @Override - public void didFinishChatCreation(GroupCreateFinalActivity fragment, int chatId) { + public void didFinishChatCreation(GroupCreateFinalActivity fragment, long chatId) { linkChat(getMessagesController().getChat(chatId), fragment); } @@ -502,7 +501,7 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter imageView.setForUserOrChat(chat, avatarDrawable); builder.setPositiveButton(LocaleController.getString("DiscussionLinkGroup", R.string.DiscussionLinkGroup), (dialogInterface, i) -> { if (chatFull.hidden_prehistory) { - MessagesController.getInstance(currentAccount).toogleChannelInvitesHistory(chat.id, false); + getMessagesController().toogleChannelInvitesHistory(chat.id, false); } linkChat(chat, null); }); @@ -515,9 +514,9 @@ public class ChatLinkActivity extends BaseFragment implements NotificationCenter return; } if (!ChatObject.isChannel(chat)) { - MessagesController.getInstance(currentAccount).convertToMegaGroup(getParentActivity(), chat.id, this, param -> { + getMessagesController().convertToMegaGroup(getParentActivity(), chat.id, this, param -> { if (param != 0) { - MessagesController.getInstance(currentAccount).toogleChannelInvitesHistory(param, false); + getMessagesController().toogleChannelInvitesHistory(param, false); linkChat(getMessagesController().getChat(param), createFragment); } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatPullingDownDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatPullingDownDrawable.java index ee23fcad7..0c1324ad2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatPullingDownDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatPullingDownDrawable.java @@ -18,8 +18,6 @@ import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.View; -import com.google.android.exoplayer2.util.Log; - import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DialogObject; @@ -67,7 +65,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC float swipeToReleaseProgress; float bounceProgress; - boolean animateSwipeToRelease; + public boolean animateSwipeToRelease; boolean animateCheck; float checkProgress; long lastHapticTime; @@ -75,31 +73,35 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC boolean emptyStub; float progressToBottomPannel; private final View fragmentView; + public long lastShowingReleaseTime; boolean drawFolderBackground; Runnable onAnimationFinishRunnable; public long nextDialogId; View parentView; - CounterView.CounterDrawable counterDrawable = new CounterView.CounterDrawable(null); + CounterView.CounterDrawable counterDrawable = new CounterView.CounterDrawable(null, null); int params[] = new int[3]; private final int currentAccount; private final int folderId; private final int filterId; private final long currentDialog; + private final Theme.ResourcesProvider resourcesProvider; - public ChatPullingDownDrawable(int currentAccount, View fragmentView, long currentDialog, int folderId, int filterId) { + public ChatPullingDownDrawable(int currentAccount, View fragmentView, long currentDialog, int folderId, int filterId, Theme.ResourcesProvider resourcesProvider) { this.fragmentView = fragmentView; this.currentAccount = currentAccount; this.currentDialog = currentDialog; this.folderId = folderId; this.filterId = filterId; + this.resourcesProvider = resourcesProvider; arrowPaint.setStrokeWidth(AndroidUtilities.dpf2(2.8f)); arrowPaint.setStrokeCap(Paint.Cap.ROUND); counterDrawable.gravity = Gravity.LEFT; counterDrawable.setType(CounterView.CounterDrawable.TYPE_CHAT_PULLING_DOWN); - counterDrawable.circlePaint = Theme.chat_actionBackgroundPaint; + counterDrawable.addServiceGradient = true; + counterDrawable.circlePaint = getThemedPaint(Theme.key_paint_chatActionBackground); counterDrawable.textPaint = textPaint; textPaint.setTextSize(AndroidUtilities.dp(13)); @@ -120,9 +122,9 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC dialogFolderId = params[1]; dialogFilterId = params[2]; emptyStub = false; - nextChat = MessagesController.getInstance(currentAccount).getChat((int) -dialog.id); + nextChat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); if (nextChat == null) { - MessagesController.getInstance(currentAccount).getChat((int) dialog.id); + MessagesController.getInstance(currentAccount).getChat(dialog.id); } AvatarDrawable avatarDrawable = new AvatarDrawable(); avatarDrawable.setInfo(nextChat); @@ -130,6 +132,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC MessagesController.getInstance(currentAccount).ensureMessagesLoaded(dialog.id, 0, null); counterDrawable.setCount(dialog.unread_count, false); } else { + nextChat = null; drawFolderBackground = false; emptyStub = true; } @@ -192,16 +195,16 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC } Theme.applyServiceShaderMatrix(lastWidth, parent.getMeasuredHeight(), 0, parent.getMeasuredHeight() - offset); - textPaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); - arrowPaint.setColor(Theme.getColor(Theme.key_chat_serviceText)); - textPaint2.setColor(Theme.getColor(Theme.key_chat_messagePanelHint)); + textPaint.setColor(getThemedColor(Theme.key_chat_serviceText)); + arrowPaint.setColor(getThemedColor(Theme.key_chat_serviceText)); + textPaint2.setColor(getThemedColor(Theme.key_chat_messagePanelHint)); - oldAlpha = Theme.chat_actionBackgroundPaint.getAlpha(); + oldAlpha = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha(); oldAlpha1 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha(); oldAlpha2 = textPaint.getAlpha(); oldAlpha3 = arrowPaint.getAlpha(); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha1 * alpha)); - Theme.chat_actionBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha * alpha)); textPaint.setAlpha((int) (oldAlpha2 * alpha)); imageReceiver.setAlpha(alpha); @@ -218,6 +221,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC animateSwipeToRelease = true; animateCheck = true; showReleaseState(true, parent); + lastShowingReleaseTime = System.currentTimeMillis(); } else if (progress != 1f && animateSwipeToRelease) { animateSwipeToRelease = false; showReleaseState(false, parent); @@ -256,20 +260,23 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC if (emptyStub) { float top = (-AndroidUtilities.dp(8) - AndroidUtilities.dp2(8) * progress - size) * (1f - swipeToReleaseProgress) + (-offset - AndroidUtilities.dp(2)) * swipeToReleaseProgress + bounceOffset; arrowPaint.setAlpha(oldAlpha3); + canvas.save(); + canvas.scale(progress, progress, cx, top + AndroidUtilities.dp(28)); drawCheck(canvas, cx, top + AndroidUtilities.dp(28)); + canvas.restore(); } canvas.restore(); } if (chatNameLayout != null && swipeToReleaseProgress > 0) { - Theme.chat_actionBackgroundPaint.setAlpha((int) (oldAlpha * alpha)); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha * alpha)); textPaint.setAlpha((int) (oldAlpha2 * alpha)); float y = AndroidUtilities.dp(20) * (1f - swipeToReleaseProgress) - AndroidUtilities.dp(36) * swipeToReleaseProgress + bounceOffset; AndroidUtilities.rectTmp.set((lastWidth - chatNameWidth) / 2f, y, lastWidth - (lastWidth - chatNameWidth) / 2f, y + chatNameLayout.getHeight()); AndroidUtilities.rectTmp.inset(-AndroidUtilities.dp(8), -AndroidUtilities.dp(4)); - canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(15), AndroidUtilities.dp(15), Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(15), AndroidUtilities.dp(15), getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(15), AndroidUtilities.dp(15), Theme.chat_actionBackgroundGradientDarkenPaint); } @@ -305,7 +312,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC } } - Theme.chat_actionBackgroundPaint.setAlpha(oldAlpha); + getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha); Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha1); textPaint.setAlpha(oldAlpha2); arrowPaint.setAlpha(oldAlpha3); @@ -364,13 +371,13 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC path.rQuadTo(roundRadius, 0, roundRadius, -roundRadius); path.rLineTo(0, -(h - (2 * roundRadius))); path.close(); - canvas.drawPath(path, Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + canvas.drawPath(path, getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { canvas.drawPath(path, Theme.chat_actionBackgroundGradientDarkenPaint); } } else { - canvas.drawRoundRect(AndroidUtilities.rectTmp, circleRadius, circleRadius, Theme.chat_actionBackgroundPaint); - if (Theme.hasGradientService()) { + canvas.drawRoundRect(AndroidUtilities.rectTmp, circleRadius, circleRadius, getThemedPaint(Theme.key_paint_chatActionBackground)); + if (hasGradientService()) { canvas.drawRoundRect(AndroidUtilities.rectTmp, circleRadius, circleRadius, Theme.chat_actionBackgroundGradientDarkenPaint); } } @@ -505,7 +512,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC params[1] = folderId; params[2] = filterId; } - ArrayList dialogs = null; + ArrayList dialogs; if (filterId != 0) { dialogs = messagesController.dialogFiltersById.get(filterId).dialogs; } else { @@ -516,8 +523,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC } for (int i = 0; i < dialogs.size(); i++) { TLRPC.Dialog dialog = dialogs.get(i); - int lower_id = (int) dialog.id; - TLRPC.Chat chat = messagesController.getChat(-lower_id); + TLRPC.Chat chat = messagesController.getChat(-dialog.id); if (chat != null && dialog.id != currentDialogId && dialog.unread_count > 0 && DialogObject.isChannel(dialog) && !chat.megagroup && !messagesController.isPromoDialog(dialog.id, false)) { return dialog; } @@ -556,7 +562,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC return null; } - public int getChatId() { + public long getChatId() { return nextChat.id; } @@ -576,11 +582,12 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC fragmentView.invalidate(); } } - int oldAlpha = Theme.chat_composeBackgroundPaint.getAlpha(); + Paint composeBackgroundPaint = getThemedPaint(Theme.key_paint_chatComposeBackground); + int oldAlpha = composeBackgroundPaint.getAlpha(); int oldAlphaText = textPaint2.getAlpha(); - Theme.chat_composeBackgroundPaint.setAlpha((int) (oldAlpha * progressToBottomPannel)); - canvas.drawRect(0, top, width, bottom, Theme.chat_composeBackgroundPaint); + composeBackgroundPaint.setAlpha((int) (oldAlpha * progressToBottomPannel)); + canvas.drawRect(0, top, width, bottom, composeBackgroundPaint); if (layout1 != null && swipeToReleaseProgress < 1f) { @@ -602,7 +609,7 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC } textPaint2.setAlpha(oldAlpha); - Theme.chat_composeBackgroundPaint.setAlpha(oldAlpha); + composeBackgroundPaint.setAlpha(oldAlpha); } boolean showBottomPanel; @@ -668,4 +675,18 @@ public class ChatPullingDownDrawable implements NotificationCenter.NotificationC checkProgress = 0; animateCheck = false; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } + + private boolean hasGradientService() { + return resourcesProvider != null ? resourcesProvider.hasGradientService() : Theme.hasGradientService(); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatRightsEditActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatRightsEditActivity.java index 4973074a7..5a34f7110 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatRightsEditActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatRightsEditActivity.java @@ -73,7 +73,7 @@ public class ChatRightsEditActivity extends BaseFragment { private ListAdapter listViewAdapter; private RecyclerListView listView; - private int chatId; + private long chatId; private TLRPC.User currentUser; private TLRPC.Chat currentChat; private int currentType; @@ -133,7 +133,7 @@ public class ChatRightsEditActivity extends BaseFragment { private final static int done_button = 1; - public ChatRightsEditActivity(int userId, int channelId, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBannedDefault, TLRPC.TL_chatBannedRights rightsBanned, String rank, int type, boolean edit, boolean addingNew) { + public ChatRightsEditActivity(long userId, long channelId, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBannedDefault, TLRPC.TL_chatBannedRights rightsBanned, String rank, int type, boolean edit, boolean addingNew) { super(); isAddingNew = addingNew; chatId = channelId; @@ -314,7 +314,7 @@ public class ChatRightsEditActivity extends BaseFragment { } if (position == 0) { Bundle args = new Bundle(); - args.putInt("user_id", currentUser.id); + args.putLong("user_id", currentUser.id); presentFragment(new ProfileActivity(args)); } else if (position == removeAdminRow) { if (currentType == TYPE_ADMIN) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatUsersActivity.java index 314d6c053..dc166580c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatUsersActivity.java @@ -38,6 +38,7 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.LinearLayoutManager; @@ -108,15 +109,15 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente private ArrayList contacts = new ArrayList<>(); private boolean botsEndReached; private boolean contactsEndReached; - private SparseArray participantsMap = new SparseArray<>(); - private SparseArray botsMap = new SparseArray<>(); - private SparseArray contactsMap = new SparseArray<>(); - private int chatId; + private LongSparseArray participantsMap = new LongSparseArray<>(); + private LongSparseArray botsMap = new LongSparseArray<>(); + private LongSparseArray contactsMap = new LongSparseArray<>(); + private long chatId; private int type; private boolean loadingUsers; private boolean firstLoaded; - private SparseArray ignoredUsers; + private LongSparseArray ignoredUsers; private int permissionsSectionRow; private int sendMessagesRow; @@ -186,7 +187,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente private View progressBar; public interface ChatUsersActivityDelegate { - default void didAddParticipantToList(int uid, TLObject participant) { + default void didAddParticipantToList(long uid, TLObject participant) { } @@ -194,11 +195,11 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } - default void didSelectUser(int uid) { + default void didSelectUser(long uid) { } - default void didKickParticipant(int userId) { + default void didKickParticipant(long userId) { } } @@ -409,7 +410,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente public ChatUsersActivity(Bundle args) { super(args); - chatId = arguments.getInt("chat_id"); + chatId = arguments.getLong("chat_id"); type = arguments.getInt("type"); needOpenSearch = arguments.getBoolean("open_search"); selectType = arguments.getInt("selectType"); @@ -845,7 +846,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente if (position == addNewRow) { if (type == TYPE_BANNED || type == TYPE_KICKED) { Bundle bundle = new Bundle(); - bundle.putInt("chat_id", chatId); + bundle.putLong("chat_id", chatId); bundle.putInt("type", ChatUsersActivity.TYPE_USERS); bundle.putInt("selectType", type == TYPE_BANNED ? 2 : 3); ChatUsersActivity fragment = new ChatUsersActivity(bundle); @@ -853,7 +854,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente fragment.setDelegate(new ChatUsersActivityDelegate() { @Override - public void didAddParticipantToList(int uid, TLObject participant) { + public void didAddParticipantToList(long uid, TLObject participant) { if (participantsMap.get(uid) == null) { DiffCallback diffCallback = saveState(); participants.add(participant); @@ -864,7 +865,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } @Override - public void didKickParticipant(int uid) { + public void didKickParticipant(long uid) { if (participantsMap.get(uid) == null) { DiffCallback diffCallback = saveState(); TLRPC.TL_channelParticipantBanned chatParticipant = new TLRPC.TL_channelParticipantBanned(); @@ -888,13 +889,13 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente presentFragment(fragment); } else if (type == TYPE_ADMIN) { Bundle bundle = new Bundle(); - bundle.putInt("chat_id", chatId); + bundle.putLong("chat_id", chatId); bundle.putInt("type", ChatUsersActivity.TYPE_USERS); bundle.putInt("selectType", 1); ChatUsersActivity fragment = new ChatUsersActivity(bundle); fragment.setDelegate(new ChatUsersActivityDelegate() { @Override - public void didAddParticipantToList(int uid, TLObject participant) { + public void didAddParticipantToList(long uid, TLObject participant) { if (participant != null && participantsMap.get(uid) == null) { DiffCallback diffCallback = saveState(); participants.add(participant); @@ -910,7 +911,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } @Override - public void didSelectUser(int uid) { + public void didSelectUser(long uid) { final TLRPC.User user = getMessagesController().getUser(uid); if (user != null) { AndroidUtilities.runOnUIThread(() -> { @@ -941,7 +942,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } else if (type == TYPE_USERS) { Bundle args = new Bundle(); args.putBoolean("addToGroup", true); - args.putInt(isChannel ? "channelId" : "chatId", currentChat.id); + args.putLong(isChannel ? "channelId" : "chatId", currentChat.id); GroupCreateActivity fragment = new GroupCreateActivity(args); fragment.setInfo(info); fragment.setIgnoreUsers(contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap); @@ -950,7 +951,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente public void didSelectUsers(ArrayList users, int fwdCount) { DiffCallback savedState = saveState(); ArrayList array = contactsMap != null && contactsMap.size() != 0 ? contacts : participants; - SparseArray map = contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap; + LongSparseArray map = contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap; int k = 0; for (int a = 0, N = users.size(); a < N; a++) { TLRPC.User user = users.get(a); @@ -997,7 +998,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente return; } else if (position == removedUsersRow) { Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_BANNED); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(info); @@ -1014,7 +1015,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente editActivity.removeSelfFromStack(); Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); ChatEditActivity fragment = new ChatEditActivity(args); fragment.setInfo(info); parentLayout.addFragmentToStack(fragment, parentLayout.fragmentsStack.size() - 1); @@ -1122,8 +1123,8 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente TLRPC.TL_chatAdminRights adminRights = null; String rank = ""; final TLObject participant; - int peerId = 0; - int promoted_by = 0; + long peerId = 0; + long promoted_by = 0; boolean canEditAdmin = false; if (listAdapter) { participant = listViewAdapter.getItem(position); @@ -1222,9 +1223,9 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } Bundle args = new Bundle(); if (peerId > 0) { - args.putInt("user_id", peerId); + args.putLong("user_id", peerId); } else { - args.putInt("chat_id", -peerId); + args.putLong("chat_id", -peerId); } presentFragment(new ProfileActivity(args)); } else { @@ -1309,7 +1310,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente return -1; } if (lhs instanceof TLRPC.ChannelParticipant && rhs instanceof TLRPC.ChannelParticipant) { - return MessageObject.getPeerId(((TLRPC.ChannelParticipant) lhs).peer) - MessageObject.getPeerId(((TLRPC.ChannelParticipant) rhs).peer); + return (int) (MessageObject.getPeerId(((TLRPC.ChannelParticipant) lhs).peer) - MessageObject.getPeerId(((TLRPC.ChannelParticipant) rhs).peer)); } return 0; }); @@ -1377,7 +1378,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente }); } - public void setIgnoresUsers(SparseArray participants) { + public void setIgnoresUsers(LongSparseArray participants) { ignoredUsers = participants; } @@ -1386,7 +1387,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente boolean foundAny = false; currentChat.creator = false; for (int a = 0; a < 3; a++) { - SparseArray map; + LongSparseArray map; ArrayList arrayList; boolean found = false; if (a == 0) { @@ -1412,7 +1413,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente found = true; foundAny = true; } - int selfUserId = getUserConfig().getClientUserId(); + long selfUserId = getUserConfig().getClientUserId(); object = map.get(selfUserId); if (object instanceof TLRPC.ChannelParticipant) { TLRPC.TL_channelParticipantAdmin admin = new TLRPC.TL_channelParticipantAdmin(); @@ -1465,7 +1466,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } } - private void openRightsEdit2(int peerId, int date, TLObject participant, TLRPC.TL_chatAdminRights adminRights, TLRPC.TL_chatBannedRights bannedRights, String rank, boolean canEditAdmin, int type, boolean removeFragment) { + private void openRightsEdit2(long peerId, int date, TLObject participant, TLRPC.TL_chatAdminRights adminRights, TLRPC.TL_chatBannedRights bannedRights, String rank, boolean canEditAdmin, int type, boolean removeFragment) { boolean[] needShowBulletin = new boolean[1]; final boolean isAdmin = participant instanceof TLRPC.TL_channelParticipantAdmin || participant instanceof TLRPC.TL_chatParticipantAdmin; ChatRightsEditActivity fragment = new ChatRightsEditActivity(peerId, chatId, adminRights, defaultBannedRights, bannedRights, rank, type, true, false) { @@ -1558,7 +1559,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente return checkDiscard(); } - private void openRightsEdit(int user_id, TLObject participant, TLRPC.TL_chatAdminRights adminRights, TLRPC.TL_chatBannedRights bannedRights, String rank, boolean canEditAdmin, int type, boolean removeFragment) { + private void openRightsEdit(long user_id, TLObject participant, TLRPC.TL_chatAdminRights adminRights, TLRPC.TL_chatBannedRights bannedRights, String rank, boolean canEditAdmin, int type, boolean removeFragment) { ChatRightsEditActivity fragment = new ChatRightsEditActivity(user_id, chatId, adminRights, defaultBannedRights, bannedRights, rank, type, canEditAdmin, participant == null); fragment.setDelegate(new ChatRightsEditActivity.ChatRightsEditActivityDelegate() { @Override @@ -1587,7 +1588,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente presentFragment(fragment, removeFragment); } - private void removeParticipant(int userId) { + private void removeParticipant(long userId) { if (!ChatObject.isChannel(currentChat)) { return; } @@ -1599,9 +1600,9 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente finishFragment(); } - private TLObject getAnyParticipant(int userId) { + private TLObject getAnyParticipant(long userId) { for (int a = 0; a < 3; a++) { - SparseArray map; + LongSparseArray map; if (a == 0) { map = contactsMap; } else if (a == 1) { @@ -1627,11 +1628,11 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } } - private void removeParticipants(int peerId) { + private void removeParticipants(long peerId) { boolean updated = false; DiffCallback savedState = saveState(); for (int a = 0; a < 3; a++) { - SparseArray map; + LongSparseArray map; ArrayList arrayList; if (a == 0) { map = contactsMap; @@ -1661,10 +1662,10 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } } - private void updateParticipantWithRights(TLRPC.ChannelParticipant channelParticipant, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, int user_id, boolean withDelegate) { + private void updateParticipantWithRights(TLRPC.ChannelParticipant channelParticipant, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, long user_id, boolean withDelegate) { boolean delegateCalled = false; for (int a = 0; a < 3; a++) { - SparseArray map; + LongSparseArray map; if (a == 0) { map = contactsMap; } else if (a == 1) { @@ -1692,7 +1693,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente if (participant == null || selectType != 0) { return false; } - int peerId; + long peerId; boolean canEdit; int date; TLRPC.TL_chatBannedRights bannedRights; @@ -2190,7 +2191,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } } else if (type == TYPE_USERS) { if (info != null) { - int selfUserId = getUserConfig().clientUserId; + long selfUserId = getUserConfig().clientUserId; for (int a = 0, size = info.participants.participants.size(); a < size; a++) { TLRPC.ChatParticipant participant = info.participants.participants.get(a); if (selectType != 0 && participant.user_id == selfUserId) { @@ -2288,7 +2289,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } getMessagesController().putUsers(res.users, false); getMessagesController().putChats(res.chats, false); - int selfId = getUserConfig().getClientUserId(); + long selfId = getUserConfig().getClientUserId(); if (selectType != 0) { for (int a = 0; a < res.participants.size(); a++) { if (MessageObject.getPeerId(res.participants.get(a).peer) == selfId) { @@ -2298,7 +2299,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente } } ArrayList objects; - SparseArray map; + LongSparseArray map; if (type == TYPE_USERS) { delayResults--; if (req.filter instanceof TLRPC.TL_channelParticipantsContacts) { @@ -2332,7 +2333,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente continue; } TLRPC.ChannelParticipant participant = (TLRPC.ChannelParticipant) object; - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); boolean remove = false; if (contactsMap.get(peerId) != null || botsMap.get(peerId) != null) { remove = true; @@ -2384,8 +2385,8 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente Collections.sort(objects, (lhs, rhs) -> { TLRPC.ChannelParticipant p1 = (TLRPC.ChannelParticipant) lhs; TLRPC.ChannelParticipant p2 = (TLRPC.ChannelParticipant) rhs; - int peer1 = MessageObject.getPeerId(p1.peer); - int peer2 = MessageObject.getPeerId(p2.peer); + long peer1 = MessageObject.getPeerId(p1.peer); + long peer2 = MessageObject.getPeerId(p2.peer); int status1 = 0; if (peer1 > 0) { TLRPC.User user1 = getMessagesController().getUser(MessageObject.getPeerId(p1.peer)); @@ -2489,7 +2490,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente private Context mContext; private ArrayList searchResult = new ArrayList<>(); - private SparseArray searchResultMap = new SparseArray<>(); + private LongSparseArray searchResultMap = new LongSparseArray<>(); private ArrayList searchResultNames = new ArrayList<>(); private SearchAdapterHelper searchAdapterHelper; private Runnable searchRunnable; @@ -2549,7 +2550,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente Utilities.searchQueue.postRunnable(() -> { String search1 = query.trim().toLowerCase(); if (search1.length() == 0) { - updateSearchResults(new ArrayList<>(), new SparseArray<>(), new ArrayList<>(), new ArrayList<>()); + updateSearchResults(new ArrayList<>(), new LongSparseArray<>(), new ArrayList<>(), new ArrayList<>()); return; } String search2 = LocaleController.getInstance().getTranslitString(search1); @@ -2562,13 +2563,13 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente search[1] = search2; } ArrayList resultArray = new ArrayList<>(); - SparseArray resultMap = new SparseArray<>(); + LongSparseArray resultMap = new LongSparseArray<>(); ArrayList resultArrayNames = new ArrayList<>(); ArrayList resultArray2 = new ArrayList<>(); if (participantsCopy != null) { for (int a = 0, N = participantsCopy.size(); a < N; a++) { - int peerId; + long peerId; TLObject o = participantsCopy.get(a); if (o instanceof TLRPC.ChatParticipant) { peerId = ((TLRPC.ChatParticipant) o).user_id; @@ -2668,7 +2669,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente }); } - private void updateSearchResults(final ArrayList users, final SparseArray usersMap, final ArrayList names, final ArrayList participants) { + private void updateSearchResults(final ArrayList users, final LongSparseArray usersMap, final ArrayList names, final ArrayList participants) { AndroidUtilities.runOnUIThread(() -> { if (!searching) { return; @@ -2739,7 +2740,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente super.notifyDataSetChanged(); } - public void removeUserId(int userId) { + public void removeUserId(long userId) { searchAdapterHelper.removeUserId(userId); Object object = searchResultMap.get(userId); if (object != null) { @@ -2822,7 +2823,7 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente if (object instanceof TLRPC.User) { peerObject = object; } else if (object instanceof TLRPC.ChannelParticipant) { - int peerId = MessageObject.getPeerId(((TLRPC.ChannelParticipant) object).peer); + long peerId = MessageObject.getPeerId(((TLRPC.ChannelParticipant) object).peer); if (peerId > 0) { TLRPC.User user = getMessagesController().getUser(peerId); un = user.username; @@ -3114,9 +3115,9 @@ public class ChatUsersActivity extends BaseFragment implements NotificationCente lastRow = botEndRow; } - int peerId; - int kickedBy; - int promotedBy; + long peerId; + long kickedBy; + long promotedBy; TLRPC.TL_chatBannedRights bannedRights; boolean banned; boolean creator; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AdminLogFilterAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AdminLogFilterAlert.java index 5acbb3542..544b4dbe9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AdminLogFilterAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AdminLogFilterAlert.java @@ -15,7 +15,6 @@ import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Drawable; import android.os.Build; -import android.util.SparseArray; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; @@ -38,13 +37,14 @@ import org.telegram.ui.ContentPreviewViewer; import java.util.ArrayList; import java.util.regex.Pattern; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class AdminLogFilterAlert extends BottomSheet { public interface AdminLogFilterAlertDelegate { - void didSelectRights(TLRPC.TL_channelAdminLogEventsFilter filter, SparseArray admins); + void didSelectRights(TLRPC.TL_channelAdminLogEventsFilter filter, LongSparseArray admins); } private Pattern urlPattern; @@ -62,7 +62,7 @@ public class AdminLogFilterAlert extends BottomSheet { private TLRPC.TL_channelAdminLogEventsFilter currentFilter; private ArrayList currentAdmins; - private SparseArray selectedAdmins; + private LongSparseArray selectedAdmins; private boolean isMegagroup; private int restrictionsRow; @@ -77,7 +77,7 @@ public class AdminLogFilterAlert extends BottomSheet { private int callsRow; private int allAdminsRow; - public AdminLogFilterAlert(Context context, TLRPC.TL_channelAdminLogEventsFilter filter, SparseArray admins, boolean megagroup) { + public AdminLogFilterAlert(Context context, TLRPC.TL_channelAdminLogEventsFilter filter, LongSparseArray admins, boolean megagroup) { super(context, false); if (filter != null) { currentFilter = new TLRPC.TL_channelAdminLogEventsFilter(); @@ -197,7 +197,7 @@ public class AdminLogFilterAlert extends BottomSheet { listView = new RecyclerListView(context) { @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, 0, null); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, 0, null, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } @@ -247,7 +247,7 @@ public class AdminLogFilterAlert extends BottomSheet { } } else if (position == allAdminsRow) { if (isChecked) { - selectedAdmins = new SparseArray<>(); + selectedAdmins = new LongSparseArray<>(); } else { selectedAdmins = null; } @@ -309,7 +309,7 @@ public class AdminLogFilterAlert extends BottomSheet { } else if (view instanceof CheckBoxUserCell) { CheckBoxUserCell checkBoxUserCell = (CheckBoxUserCell) view; if (selectedAdmins == null) { - selectedAdmins = new SparseArray<>(); + selectedAdmins = new LongSparseArray<>(); RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(allAdminsRow); if (holder != null) { ((CheckBoxCell) holder.itemView).setChecked(false, true); @@ -415,7 +415,7 @@ public class AdminLogFilterAlert extends BottomSheet { FrameLayout view = null; switch (viewType) { case 0: - view = new CheckBoxCell(context, 1, 21); + view = new CheckBoxCell(context, 1, 21, resourcesProvider); break; case 1: ShadowSectionCell shadowSectionCell = new ShadowSectionCell(context, 18); @@ -466,7 +466,7 @@ public class AdminLogFilterAlert extends BottomSheet { } case 2: { CheckBoxUserCell userCell = (CheckBoxUserCell) holder.itemView; - int userId = MessageObject.getPeerId(currentAdmins.get(position - allAdminsRow - 1).peer); + long userId = MessageObject.getPeerId(currentAdmins.get(position - allAdminsRow - 1).peer); userCell.setChecked(selectedAdmins == null || selectedAdmins.indexOfKey(userId) >= 0, false); break; } @@ -511,7 +511,7 @@ public class AdminLogFilterAlert extends BottomSheet { } case 2: { CheckBoxUserCell userCell = (CheckBoxUserCell) holder.itemView; - int userId = MessageObject.getPeerId(currentAdmins.get(position - allAdminsRow - 1).peer); + long userId = MessageObject.getPeerId(currentAdmins.get(position - allAdminsRow - 1).peer); userCell.setUser(MessagesController.getInstance(currentAccount).getUser(userId), selectedAdmins == null || selectedAdmins.indexOfKey(userId) >= 0, position != getItemCount() - 1); break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java index 82ebee4c1..2b4448a8e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java @@ -61,6 +61,7 @@ import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; @@ -483,9 +484,8 @@ public class AlertsCreator { } public static boolean checkSlowMode(Context context, int currentAccount, long did, boolean few) { - int lowerId = (int) did; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); if (chat != null && chat.slowmode_enabled && !ChatObject.hasAdminRights(chat)) { if (!few) { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chat.id); @@ -510,6 +510,10 @@ public class AlertsCreator { } public static AlertDialog.Builder createSimpleAlert(Context context, final String title, final String text) { + return createSimpleAlert(context, title, text, null); + } + + public static AlertDialog.Builder createSimpleAlert(Context context, final String title, final String text, Theme.ResourcesProvider resourcesProvider) { if (context == null || text == null) { return null; } @@ -525,16 +529,20 @@ public class AlertsCreator { } public static Dialog showSimpleAlert(BaseFragment baseFragment, final String title, final String text) { + return showSimpleAlert(baseFragment, title, text, null); + } + + public static Dialog showSimpleAlert(BaseFragment baseFragment, final String title, final String text, Theme.ResourcesProvider resourcesProvider) { if (text == null || baseFragment == null || baseFragment.getParentActivity() == null) { return null; } - AlertDialog.Builder builder = createSimpleAlert(baseFragment.getParentActivity(), title, text); + AlertDialog.Builder builder = createSimpleAlert(baseFragment.getParentActivity(), title, text, resourcesProvider); Dialog dialog = builder.create(); baseFragment.showDialog(dialog); return dialog; } - public static void showBlockReportSpamReplyAlert(ChatActivity fragment, MessageObject messageObject, int peerId) { + public static void showBlockReportSpamReplyAlert(ChatActivity fragment, MessageObject messageObject, long peerId, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || fragment.getParentActivity() == null || messageObject == null) { return; } @@ -545,7 +553,7 @@ public class AlertsCreator { if (user == null && chat == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("BlockUser", R.string.BlockUser)); if (user != null) { @@ -558,7 +566,7 @@ public class AlertsCreator { LinearLayout linearLayout = new LinearLayout(fragment.getParentActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); - cells[0] = new CheckBoxCell(fragment.getParentActivity(), 1); + cells[0] = new CheckBoxCell(fragment.getParentActivity(), 1, resourcesProvider); cells[0].setBackgroundDrawable(Theme.getSelectorDrawable(false)); cells[0].setTag(0); cells[0].setText(LocaleController.getString("DeleteReportSpam", R.string.DeleteReportSpam), "", true, false); @@ -575,9 +583,9 @@ public class AlertsCreator { builder.setPositiveButton(LocaleController.getString("BlockAndDeleteReplies", R.string.BlockAndDeleteReplies), (dialogInterface, i) -> { if (user != null) { - accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), 0, user.id); + accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), user.id); } else { - accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), 0, -chat.id); + accountInstance.getMessagesStorage().deleteUserChatHistory(fragment.getDialogId(), -chat.id); } TLRPC.TL_contacts_blockFromReplies request = new TLRPC.TL_contacts_blockFromReplies(); request.msg_id = messageObject.getId(); @@ -589,7 +597,7 @@ public class AlertsCreator { if (fragment instanceof ChatActivity) { fragment.getUndoView().showWithAction(0, UndoView.ACTION_REPORT_SENT, null); } else if (fragment != null) { - BulletinFactory.of(fragment).createReportSent().show(); + BulletinFactory.of(fragment).createReportSent(resourcesProvider).show(); } else { Toast.makeText(fragment.getParentActivity(), LocaleController.getString("ReportChatSent", R.string.ReportChatSent), Toast.LENGTH_SHORT).show(); } @@ -610,12 +618,12 @@ public class AlertsCreator { } } - public static void showBlockReportSpamAlert(BaseFragment fragment, long dialog_id, TLRPC.User currentUser, TLRPC.Chat currentChat, TLRPC.EncryptedChat encryptedChat, boolean isLocation, TLRPC.ChatFull chatInfo, MessagesStorage.IntCallback callback) { + public static void showBlockReportSpamAlert(BaseFragment fragment, long dialog_id, TLRPC.User currentUser, TLRPC.Chat currentChat, TLRPC.EncryptedChat encryptedChat, boolean isLocation, TLRPC.ChatFull chatInfo, MessagesStorage.IntCallback callback, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || fragment.getParentActivity() == null) { return; } AccountInstance accountInstance = fragment.getAccountInstance(); - AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider); CharSequence reportText; CheckBoxCell[] cells; SharedPreferences preferences = MessagesController.getNotificationsSettings(fragment.getCurrentAccount()); @@ -632,7 +640,7 @@ public class AlertsCreator { if (a == 0 && !showReport) { continue; } - cells[a] = new CheckBoxCell(fragment.getParentActivity(), 1); + cells[a] = new CheckBoxCell(fragment.getParentActivity(), 1, resourcesProvider); cells[a].setBackgroundDrawable(Theme.getSelectorDrawable(false)); cells[a].setTag(a); if (a == 0) { @@ -681,7 +689,7 @@ public class AlertsCreator { if (ChatObject.isNotInChat(currentChat)) { accountInstance.getMessagesController().deleteDialog(dialog_id, 0); } else { - accountInstance.getMessagesController().deleteParticipantFromChat((int) -dialog_id, accountInstance.getMessagesController().getUser(accountInstance.getUserConfig().getClientUserId()), null); + accountInstance.getMessagesController().deleteParticipantFromChat(-dialog_id, accountInstance.getMessagesController().getUser(accountInstance.getUserConfig().getClientUserId()), null); } } else { accountInstance.getMessagesController().deleteDialog(dialog_id, 0); @@ -872,7 +880,7 @@ public class AlertsCreator { parentFragment.showDialog(builder.create()); } - public static AlertDialog showSecretLocationAlert(Context context, int currentAccount, final Runnable onSelectRunnable, boolean inChat) { + public static AlertDialog showSecretLocationAlert(Context context, int currentAccount, final Runnable onSelectRunnable, boolean inChat, Theme.ResourcesProvider resourcesProvider) { ArrayList arrayList = new ArrayList<>(); ArrayList types = new ArrayList<>(); int providers = MessagesController.getInstance(currentAccount).availableMapProviders; @@ -891,14 +899,14 @@ public class AlertsCreator { arrayList.add(LocaleController.getString("MapPreviewProviderNobody", R.string.MapPreviewProviderNobody)); types.add(2); - AlertDialog.Builder builder = new AlertDialog.Builder(context); + AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider); builder.setTitle(LocaleController.getString("MapPreviewProviderTitle", R.string.MapPreviewProviderTitle)); final LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); builder.setView(linearLayout); for (int a = 0; a < arrayList.size(); a++) { - RadioColorCell cell = new RadioColorCell(context); + RadioColorCell cell = new RadioColorCell(context, resourcesProvider); cell.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); cell.setTag(a); cell.setCheckColor(Theme.getColor(Theme.key_radioBackground), Theme.getColor(Theme.key_dialogRadioBackgroundChecked)); @@ -958,10 +966,14 @@ public class AlertsCreator { } public static void showOpenUrlAlert(BaseFragment fragment, String url, boolean punycode, boolean ask) { - showOpenUrlAlert(fragment, url, punycode, true, ask); + showOpenUrlAlert(fragment, url, punycode, true, ask, null); } - public static void showOpenUrlAlert(BaseFragment fragment, String url, boolean punycode, boolean tryTelegraph, boolean ask) { + public static void showOpenUrlAlert(BaseFragment fragment, String url, boolean punycode, boolean ask, Theme.ResourcesProvider resourcesProvider) { + showOpenUrlAlert(fragment, url, punycode, true, ask, resourcesProvider); + } + + public static void showOpenUrlAlert(BaseFragment fragment, String url, boolean punycode, boolean tryTelegraph, boolean ask, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || fragment.getParentActivity() == null) { return; } @@ -982,7 +994,7 @@ public class AlertsCreator { } else { urlFinal = url; } - AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("OpenUrlTitle", R.string.OpenUrlTitle)); String format = LocaleController.getString("OpenUrlAlert2", R.string.OpenUrlAlert2); int index = format.indexOf("%"); @@ -1038,7 +1050,7 @@ public class AlertsCreator { private static void performAskAQuestion(BaseFragment fragment) { int currentAccount = fragment.getCurrentAccount(); final SharedPreferences preferences = MessagesController.getMainSettings(currentAccount); - int uid = preferences.getInt("support_id", 0); + long uid = AndroidUtilities.getPrefIntOrLong(preferences, "support_id2", 0); TLRPC.User supportUser = null; if (uid != 0) { supportUser = MessagesController.getInstance(currentAccount).getUser(uid); @@ -1072,7 +1084,7 @@ public class AlertsCreator { final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response; AndroidUtilities.runOnUIThread(() -> { SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("support_id", res.user.id); + editor.putLong("support_id2", res.user.id); SerializedData data = new SerializedData(); res.user.serializeToStream(data); editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)); @@ -1088,7 +1100,7 @@ public class AlertsCreator { MessagesStorage.getInstance(currentAccount).putUsersAndChats(users, null, true, true); MessagesController.getInstance(currentAccount).putUser(res.user, false); Bundle args = new Bundle(); - args.putInt("user_id", res.user.id); + args.putLong("user_id", res.user.id); fragment.presentFragment(new ChatActivity(args)); }); } else { @@ -1104,7 +1116,7 @@ public class AlertsCreator { } else { MessagesController.getInstance(currentAccount).putUser(supportUser, true); Bundle args = new Bundle(); - args.putInt("user_id", supportUser.id); + args.putLong("user_id", supportUser.id); fragment.presentFragment(new ChatActivity(args)); } } @@ -1117,7 +1129,7 @@ public class AlertsCreator { Context context = fragment.getParentActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(context); - int selfUserId = UserConfig.getInstance(account).getClientUserId(); + long selfUserId = UserConfig.getInstance(account).getClientUserId(); TextView messageTextView = new TextView(context); messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); @@ -1193,22 +1205,26 @@ public class AlertsCreator { } public static void createClearOrDeleteDialogAlert(BaseFragment fragment, boolean clear, TLRPC.Chat chat, TLRPC.User user, boolean secret, MessagesStorage.BooleanCallback onProcessRunnable) { - createClearOrDeleteDialogAlert(fragment, clear, false, false, chat, user, secret, false, onProcessRunnable); + createClearOrDeleteDialogAlert(fragment, clear, false, false, chat, user, secret, false, onProcessRunnable, null); } public static void createClearOrDeleteDialogAlert(BaseFragment fragment, boolean clear, TLRPC.Chat chat, TLRPC.User user, boolean secret, boolean checkDeleteForAll, MessagesStorage.BooleanCallback onProcessRunnable) { - createClearOrDeleteDialogAlert(fragment, clear, chat != null && chat.creator, false, chat, user, secret, checkDeleteForAll, onProcessRunnable); + createClearOrDeleteDialogAlert(fragment, clear, chat != null && chat.creator, false, chat, user, secret, checkDeleteForAll, onProcessRunnable, null); } - public static void createClearOrDeleteDialogAlert(BaseFragment fragment, boolean clear, boolean admin, boolean second, TLRPC.Chat chat, TLRPC.User user, boolean secret, boolean checkDeleteForAll, MessagesStorage.BooleanCallback onProcessRunnable) { + public static void createClearOrDeleteDialogAlert(BaseFragment fragment, boolean clear, TLRPC.Chat chat, TLRPC.User user, boolean secret, boolean checkDeleteForAll, MessagesStorage.BooleanCallback onProcessRunnable, Theme.ResourcesProvider resourcesProvider) { + createClearOrDeleteDialogAlert(fragment, clear, chat != null && chat.creator, false, chat, user, secret, checkDeleteForAll, onProcessRunnable, resourcesProvider); + } + + public static void createClearOrDeleteDialogAlert(BaseFragment fragment, boolean clear, boolean admin, boolean second, TLRPC.Chat chat, TLRPC.User user, boolean secret, boolean checkDeleteForAll, MessagesStorage.BooleanCallback onProcessRunnable, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || fragment.getParentActivity() == null || chat == null && user == null) { return; } int account = fragment.getCurrentAccount(); Context context = fragment.getParentActivity(); - AlertDialog.Builder builder = new AlertDialog.Builder(context); - int selfUserId = UserConfig.getInstance(account).getClientUserId(); + AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider); + long selfUserId = UserConfig.getInstance(account).getClientUserId(); CheckBoxCell[] cell = new CheckBoxCell[1]; @@ -1294,7 +1310,7 @@ public class AlertsCreator { boolean deleteChatForAll = false; if (!second && (secret && !clear || canDeleteInbox) && !UserObject.isDeleted(user) || (deleteChatForAll = checkDeleteForAll && !clear && chat != null && chat.creator)) { - cell[0] = new CheckBoxCell(context, 1); + cell[0] = new CheckBoxCell(context, 1, resourcesProvider); cell[0].setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (deleteChatForAll) { if (ChatObject.isChannel(chat) && !chat.megagroup) { @@ -1438,12 +1454,12 @@ public class AlertsCreator { builder.setPositiveButton(actionText, (dialogInterface, i) -> { if (!clearingCache && !second && !secret) { if (UserObject.isUserSelf(user)) { - createClearOrDeleteDialogAlert(fragment, clear, admin, true, chat, user, false, checkDeleteForAll, onProcessRunnable); + createClearOrDeleteDialogAlert(fragment, clear, admin, true, chat, user, false, checkDeleteForAll, onProcessRunnable, resourcesProvider); return; } else if (user != null && deleteForAll[0]) { MessagesStorage.getInstance(fragment.getCurrentAccount()).getMessagesCount(user.id, (count) -> { if (count >= 50) { - createClearOrDeleteDialogAlert(fragment, clear, admin, true, chat, user, false, checkDeleteForAll, onProcessRunnable); + createClearOrDeleteDialogAlert(fragment, clear, admin, true, chat, user, false, checkDeleteForAll, onProcessRunnable, resourcesProvider); } else { if (onProcessRunnable != null) { onProcessRunnable.run(deleteForAll[0]); @@ -1524,7 +1540,7 @@ public class AlertsCreator { fragment.showDialog(dialog); } - public static void createChangeBioAlert(String currentBio, int peerId, Context context, int currentAccount) { + public static void createChangeBioAlert(String currentBio, long peerId, Context context, int currentAccount) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(peerId > 0 ? LocaleController.getString("UserBio", R.string.UserBio) : LocaleController.getString("DescriptionPlaceholder", R.string.DescriptionPlaceholder)); builder.setMessage(peerId > 0 ? LocaleController.getString("VoipGroupBioEditAlertText", R.string.VoipGroupBioEditAlertText) : LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo)); @@ -1668,10 +1684,10 @@ public class AlertsCreator { } - public static void createChangeNameAlert(int peerId, Context context, int currentAccount) { + public static void createChangeNameAlert(long peerId, Context context, int currentAccount) { String currentName; String currentLastName = null; - if (peerId > 0) { + if (DialogObject.isUserDialog(peerId)) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(peerId); currentName = user.first_name; currentLastName = user.last_name; @@ -2055,15 +2071,32 @@ public class AlertsCreator { public final int subMenuBackgroundColor; public final int subMenuSelectorColor; - public final int buttonTextColor = Theme.getColor(Theme.key_featuredStickers_buttonText); - public final int buttonBackgroundColor = Theme.getColor(Theme.key_featuredStickers_addButton); - public final int buttonBackgroundPressedColor = Theme.getColor(Theme.key_featuredStickers_addButtonPressed); + public final int buttonTextColor; + public final int buttonBackgroundColor; + public final int buttonBackgroundPressedColor; private ScheduleDatePickerColors() { - this(Theme.getColor(Theme.key_dialogTextBlack), Theme.getColor(Theme.key_dialogBackground), Theme.getColor(Theme.key_sheet_other), Theme.getColor(Theme.key_player_actionBarSelector), Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), Theme.getColor(Theme.key_listSelector)); + this(null); + } + + private ScheduleDatePickerColors(Theme.ResourcesProvider rp) { + this(rp != null ? rp.getColorOrDefault(Theme.key_dialogTextBlack) : Theme.getColor(Theme.key_dialogTextBlack), + rp != null ? rp.getColorOrDefault(Theme.key_dialogBackground) : Theme.getColor(Theme.key_dialogBackground), + rp != null ? rp.getColorOrDefault(Theme.key_sheet_other) : Theme.getColor(Theme.key_sheet_other), + rp != null ? rp.getColorOrDefault(Theme.key_player_actionBarSelector) : Theme.getColor(Theme.key_player_actionBarSelector), + rp != null ? rp.getColorOrDefault(Theme.key_actionBarDefaultSubmenuItem) : Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), + rp != null ? rp.getColorOrDefault(Theme.key_actionBarDefaultSubmenuBackground) : Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground), + rp != null ? rp.getColorOrDefault(Theme.key_listSelector) : Theme.getColor(Theme.key_listSelector), + rp != null ? rp.getColorOrDefault(Theme.key_featuredStickers_buttonText) : Theme.getColor(Theme.key_featuredStickers_buttonText), + rp != null ? rp.getColorOrDefault(Theme.key_featuredStickers_addButton) : Theme.getColor(Theme.key_featuredStickers_addButton), + rp != null ? rp.getColorOrDefault(Theme.key_featuredStickers_addButtonPressed) : Theme.getColor(Theme.key_featuredStickers_addButtonPressed)); } public ScheduleDatePickerColors(int textColor, int backgroundColor, int iconColor, int iconSelectorColor, int subMenuTextColor, int subMenuBackgroundColor, int subMenuSelectorColor) { + this(textColor, backgroundColor, iconColor, iconSelectorColor, subMenuTextColor, subMenuBackgroundColor, subMenuSelectorColor, Theme.getColor(Theme.key_featuredStickers_buttonText), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed)); + } + + public ScheduleDatePickerColors(int textColor, int backgroundColor, int iconColor, int iconSelectorColor, int subMenuTextColor, int subMenuBackgroundColor, int subMenuSelectorColor, int buttonTextColor, int buttonBackgroundColor, int buttonBackgroundPressedColor) { this.textColor = textColor; this.backgroundColor = backgroundColor; this.iconColor = iconColor; @@ -2071,6 +2104,9 @@ public class AlertsCreator { this.subMenuTextColor = subMenuTextColor; this.subMenuBackgroundColor = subMenuBackgroundColor; this.subMenuSelectorColor = subMenuSelectorColor; + this.buttonTextColor = buttonTextColor; + this.buttonBackgroundColor = buttonBackgroundColor; + this.buttonBackgroundPressedColor = buttonBackgroundPressedColor; } } @@ -2078,33 +2114,41 @@ public class AlertsCreator { return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, null); } - public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, final ScheduleDatePickerDelegate datePickerDelegate, final ScheduleDatePickerColors datePickerColors) { - return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, null, datePickerColors); + public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, final ScheduleDatePickerDelegate datePickerDelegate, Theme.ResourcesProvider resourcesProvider) { + return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, null, resourcesProvider); } - public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable) { - return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, cancelRunnable); + public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, final ScheduleDatePickerDelegate datePickerDelegate, final ScheduleDatePickerColors datePickerColors) { + return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, null, datePickerColors, null); + } + + public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable, Theme.ResourcesProvider resourcesProvider) { + return createScheduleDatePickerDialog(context, dialogId, -1, datePickerDelegate, cancelRunnable, resourcesProvider); } public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, long currentDate, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable) { - return createScheduleDatePickerDialog(context, dialogId, currentDate, datePickerDelegate, cancelRunnable, new ScheduleDatePickerColors()); + return createScheduleDatePickerDialog(context, dialogId, currentDate, datePickerDelegate, cancelRunnable, new ScheduleDatePickerColors(), null); } - public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, long currentDate, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable, final ScheduleDatePickerColors datePickerColors) { + public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, long currentDate, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable, Theme.ResourcesProvider resourcesProvider) { + return createScheduleDatePickerDialog(context, dialogId, currentDate, datePickerDelegate, cancelRunnable, new ScheduleDatePickerColors(resourcesProvider), resourcesProvider); + } + + public static BottomSheet.Builder createScheduleDatePickerDialog(Context context, long dialogId, long currentDate, final ScheduleDatePickerDelegate datePickerDelegate, final Runnable cancelRunnable, final ScheduleDatePickerColors datePickerColors, Theme.ResourcesProvider resourcesProvider) { if (context == null) { return null; } - int selfUserId = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); + long selfUserId = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); - BottomSheet.Builder builder = new BottomSheet.Builder(context, false); + BottomSheet.Builder builder = new BottomSheet.Builder(context, false, resourcesProvider); builder.setApplyBottomPadding(false); - final NumberPicker dayPicker = new NumberPicker(context); + final NumberPicker dayPicker = new NumberPicker(context, resourcesProvider); dayPicker.setTextColor(datePickerColors.textColor); dayPicker.setTextOffset(AndroidUtilities.dp(10)); dayPicker.setItemCount(5); - final NumberPicker hourPicker = new NumberPicker(context) { + final NumberPicker hourPicker = new NumberPicker(context, resourcesProvider) { @Override protected CharSequence getContentDescription(int value) { return LocaleController.formatPluralString("Hours", value); @@ -2113,7 +2157,7 @@ public class AlertsCreator { hourPicker.setItemCount(5); hourPicker.setTextColor(datePickerColors.textColor); hourPicker.setTextOffset(-AndroidUtilities.dp(10)); - final NumberPicker minutePicker = new NumberPicker(context) { + final NumberPicker minutePicker = new NumberPicker(context, resourcesProvider) { @Override protected CharSequence getContentDescription(int value) { return LocaleController.formatPluralString("Minutes", value); @@ -2171,15 +2215,15 @@ public class AlertsCreator { titleLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 12, 0, 0)); titleView.setOnTouchListener((v, event) -> true); - if ((int) dialogId > 0 && dialogId != selfUserId) { - TLRPC.User user = MessagesController.getInstance(UserConfig.selectedAccount).getUser((int) dialogId); + if (DialogObject.isUserDialog(dialogId) && dialogId != selfUserId) { + TLRPC.User user = MessagesController.getInstance(UserConfig.selectedAccount).getUser(dialogId); if (user != null && !user.bot && user.status != null && user.status.expires > 0) { String name = UserObject.getFirstName(user); if (name.length() > 10) { name = name.substring(0, 10) + "\u2026"; } - ActionBarMenuItem optionsButton = new ActionBarMenuItem(context, null, 0, datePickerColors.iconColor); + ActionBarMenuItem optionsButton = new ActionBarMenuItem(context, null, 0, datePickerColors.iconColor, false, resourcesProvider); optionsButton.setLongClickEnabled(false); optionsButton.setSubMenuOpenSide(2); optionsButton.setIcon(R.drawable.ic_ab_other); @@ -2544,21 +2588,21 @@ public class AlertsCreator { } } - public static BottomSheet.Builder createCalendarPickerDialog(Context context, long minDate, final MessagesStorage.IntCallback callback) { + public static BottomSheet.Builder createCalendarPickerDialog(Context context, long minDate, final MessagesStorage.IntCallback callback, Theme.ResourcesProvider resourcesProvider) { if (context == null) { return null; } - BottomSheet.Builder builder = new BottomSheet.Builder(context, false); + BottomSheet.Builder builder = new BottomSheet.Builder(context, false, resourcesProvider); builder.setApplyBottomPadding(false); - final NumberPicker dayPicker = new NumberPicker(context); + final NumberPicker dayPicker = new NumberPicker(context, resourcesProvider); dayPicker.setTextOffset(AndroidUtilities.dp(10)); dayPicker.setItemCount(5); - final NumberPicker monthPicker = new NumberPicker(context); + final NumberPicker monthPicker = new NumberPicker(context, resourcesProvider); monthPicker.setItemCount(5); monthPicker.setTextOffset(-AndroidUtilities.dp(10)); - final NumberPicker yearPicker = new NumberPicker(context); + final NumberPicker yearPicker = new NumberPicker(context, resourcesProvider); yearPicker.setItemCount(5); yearPicker.setTextOffset(-AndroidUtilities.dp(24)); @@ -2600,7 +2644,7 @@ public class AlertsCreator { TextView titleView = new TextView(context); titleView.setText(LocaleController.getString("ChooseDate", R.string.ChooseDate)); - titleView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + titleView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack, resourcesProvider)); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 12, 0, 0)); @@ -2703,11 +2747,11 @@ public class AlertsCreator { buttonTextView.setPadding(AndroidUtilities.dp(34), 0, AndroidUtilities.dp(34), 0); buttonTextView.setGravity(Gravity.CENTER); - buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText, resourcesProvider)); buttonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); buttonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); buttonTextView.setText(LocaleController.getString("JumpToDate", R.string.JumpToDate)); - buttonTextView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + buttonTextView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton, resourcesProvider), Theme.getColor(Theme.key_featuredStickers_addButtonPressed, resourcesProvider))); container.addView(buttonTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM, 16, 15, 16, 16)); buttonTextView.setOnClickListener(v -> { checkCalendarDate(minDate, dayPicker, monthPicker, yearPicker); @@ -2725,12 +2769,12 @@ public class AlertsCreator { return builder; } - public static BottomSheet createMuteAlert(BaseFragment fragment, final long dialog_id) { + public static BottomSheet createMuteAlert(BaseFragment fragment, final long dialog_id, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || fragment.getParentActivity() == null) { return null; } - BottomSheet.Builder builder = new BottomSheet.Builder(fragment.getParentActivity()); + BottomSheet.Builder builder = new BottomSheet.Builder(fragment.getParentActivity(), false, resourcesProvider); builder.setTitle(LocaleController.getString("Notifications", R.string.Notifications), true); CharSequence[] items = new CharSequence[]{ LocaleController.formatString("MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 1)), @@ -2751,7 +2795,7 @@ public class AlertsCreator { } NotificationsController.getInstance(UserConfig.selectedAccount).setDialogNotificationsSettings(dialog_id, setting); if (BulletinFactory.canShowBulletin(fragment)) { - BulletinFactory.createMuteBulletin(fragment, setting).show(); + BulletinFactory.createMuteBulletin(fragment, setting, resourcesProvider).show(); } } ); @@ -2782,11 +2826,15 @@ public class AlertsCreator { } public static void createReportAlert(final Context context, final long dialog_id, final int messageId, final BaseFragment parentFragment) { + createReportAlert(context, dialog_id, messageId, parentFragment, null); + } + + public static void createReportAlert(final Context context, final long dialog_id, final int messageId, final BaseFragment parentFragment, Theme.ResourcesProvider resourcesProvider) { if (context == null || parentFragment == null) { return; } - BottomSheet.Builder builder = new BottomSheet.Builder(context); + BottomSheet.Builder builder = new BottomSheet.Builder(context, true, resourcesProvider); builder.setTitle(LocaleController.getString("ReportChat", R.string.ReportChat), true); CharSequence[] items; int[] icons; @@ -2847,7 +2895,7 @@ public class AlertsCreator { if (messageId != 0) { ids.add(messageId); } - TLRPC.InputPeer peer = MessagesController.getInstance(UserConfig.selectedAccount).getInputPeer((int) dialog_id); + TLRPC.InputPeer peer = MessagesController.getInstance(UserConfig.selectedAccount).getInputPeer(dialog_id); sendReport(peer, type, message, ids); if (parentFragment instanceof ChatActivity) { ((ChatActivity) parentFragment).getUndoView().showWithAction(0, UndoView.ACTION_REPORT_SENT, null); @@ -2857,7 +2905,7 @@ public class AlertsCreator { return; } TLObject req; - TLRPC.InputPeer peer = MessagesController.getInstance(UserConfig.selectedAccount).getInputPeer((int) dialog_id); + TLRPC.InputPeer peer = MessagesController.getInstance(UserConfig.selectedAccount).getInputPeer(dialog_id); if (messageId != 0) { TLRPC.TL_messages_report request = new TLRPC.TL_messages_report(); request.peer = peer; @@ -2896,7 +2944,7 @@ public class AlertsCreator { if (parentFragment instanceof ChatActivity) { ((ChatActivity) parentFragment).getUndoView().showWithAction(0, UndoView.ACTION_REPORT_SENT, null); } else { - BulletinFactory.of(parentFragment).createReportSent().show(); + BulletinFactory.of(parentFragment).createReportSent(resourcesProvider).show(); } }); BottomSheet sheet = builder.create(); @@ -2933,11 +2981,11 @@ public class AlertsCreator { fragment.showDialog(builder.create(), true, null); } - public static void showSendMediaAlert(int result, final BaseFragment fragment) { + public static void showSendMediaAlert(int result, final BaseFragment fragment, Theme.ResourcesProvider resourcesProvider) { if (result == 0) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (result == 1) { builder.setMessage(LocaleController.getString("ErrorSendRestrictedStickers", R.string.ErrorSendRestrictedStickers)); @@ -3072,7 +3120,7 @@ public class AlertsCreator { if (preferences.contains("color_" + dialog_id)) { currentColor = preferences.getInt("color_" + dialog_id, 0xff0000ff); } else { - if ((int) dialog_id < 0) { + if (DialogObject.isChatDialog(dialog_id)) { currentColor = preferences.getInt("GroupLed", 0xff0000ff); } else { currentColor = preferences.getInt("MessagesLed", 0xff0000ff); @@ -3273,7 +3321,7 @@ public class AlertsCreator { return builder.create(); } - public static Dialog createLocationUpdateDialog(final Activity parentActivity, TLRPC.User user, final MessagesStorage.IntCallback callback) { + public static Dialog createLocationUpdateDialog(final Activity parentActivity, TLRPC.User user, final MessagesStorage.IntCallback callback, Theme.ResourcesProvider resourcesProvider) { final int[] selected = new int[1]; String[] descriptions = new String[]{ @@ -3291,16 +3339,19 @@ public class AlertsCreator { } else { titleTextView.setText(LocaleController.getString("LiveLocationAlertGroup", R.string.LiveLocationAlertGroup)); } - titleTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + int textColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTextBlack) : Theme.getColor(Theme.key_dialogTextBlack); + titleTextView.setTextColor(textColor); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); titleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); linearLayout.addView(titleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 24, 0, 24, 8)); for (int a = 0; a < descriptions.length; a++) { - RadioColorCell cell = new RadioColorCell(parentActivity); + RadioColorCell cell = new RadioColorCell(parentActivity, resourcesProvider); cell.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); cell.setTag(a); - cell.setCheckColor(Theme.getColor(Theme.key_radioBackground), Theme.getColor(Theme.key_dialogRadioBackgroundChecked)); + int color1 = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_radioBackground) : Theme.getColor(Theme.key_radioBackground); + int color2 = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogRadioBackgroundChecked) : Theme.getColor(Theme.key_dialogRadioBackgroundChecked); + cell.setCheckColor(color1, color2); cell.setTextAndValue(descriptions[a], selected[0] == a); linearLayout.addView(cell); cell.setOnClickListener(v -> { @@ -3315,8 +3366,9 @@ public class AlertsCreator { } }); } - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); - builder.setTopImage(new ShareLocationDrawable(parentActivity, 0), Theme.getColor(Theme.key_dialogTopBackground)); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); + int topImageColor = resourcesProvider != null ? resourcesProvider.getColorOrDefault(Theme.key_dialogTopBackground) : Theme.getColor(Theme.key_dialogTopBackground); + builder.setTopImage(new ShareLocationDrawable(parentActivity, 0), topImageColor); builder.setView(linearLayout); builder.setPositiveButton(LocaleController.getString("ShareFile", R.string.ShareFile), (dialog, which) -> { int time; @@ -3334,11 +3386,11 @@ public class AlertsCreator { } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - public static AlertDialog.Builder createBackgroundLocationPermissionDialog(Activity activity, TLRPC.User selfUser, Runnable cancelRunnable) { + public static AlertDialog.Builder createBackgroundLocationPermissionDialog(Activity activity, TLRPC.User selfUser, Runnable cancelRunnable, Theme.ResourcesProvider resourcesProvider) { if (activity == null || Build.VERSION.SDK_INT < 29) { return null; } - AlertDialog.Builder builder = new AlertDialog.Builder(activity); + AlertDialog.Builder builder = new AlertDialog.Builder(activity, resourcesProvider); String svg = RLottieDrawable.readRes(null, Theme.getCurrentTheme().isDark() ? R.raw.permission_map_dark : R.raw.permission_map); String pinSvg = RLottieDrawable.readRes(null, Theme.getCurrentTheme().isDark() ? R.raw.permission_pin_dark : R.raw.permission_pin); FrameLayout frameLayout = new FrameLayout(activity); @@ -3770,8 +3822,8 @@ public class AlertsCreator { return builder.create(); } - public static AlertDialog.Builder createTTLAlert(final Context context, final TLRPC.EncryptedChat encryptedChat) { - AlertDialog.Builder builder = new AlertDialog.Builder(context); + public static AlertDialog.Builder createTTLAlert(final Context context, final TLRPC.EncryptedChat encryptedChat, Theme.ResourcesProvider resourcesProvider) { + AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider); builder.setTitle(LocaleController.getString("MessageLifetime", R.string.MessageLifetime)); final NumberPicker numberPicker = new NumberPicker(context); numberPicker.setMinValue(0); @@ -3914,7 +3966,7 @@ public class AlertsCreator { void didPressedNewCard(); } - public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User user, TLRPC.Chat chat, TLRPC.EncryptedChat encryptedChat, TLRPC.ChatFull chatInfo, long mergeDialogId, MessageObject selectedMessage, SparseArray[] selectedMessages, MessageObject.GroupedMessages selectedGroup, boolean scheduled, int loadParticipant, Runnable onDelete) { + public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User user, TLRPC.Chat chat, TLRPC.EncryptedChat encryptedChat, TLRPC.ChatFull chatInfo, long mergeDialogId, MessageObject selectedMessage, SparseArray[] selectedMessages, MessageObject.GroupedMessages selectedGroup, boolean scheduled, int loadParticipant, Runnable onDelete, Theme.ResourcesProvider resourcesProvider) { if (fragment == null || user == null && chat == null && encryptedChat == null) { return; } @@ -3924,7 +3976,7 @@ public class AlertsCreator { } int currentAccount = fragment.getCurrentAccount(); - AlertDialog.Builder builder = new AlertDialog.Builder(activity); + AlertDialog.Builder builder = new AlertDialog.Builder(activity, resourcesProvider); int count; if (selectedGroup != null) { count = selectedGroup.messages.size(); @@ -3936,7 +3988,7 @@ public class AlertsCreator { long dialogId; if (encryptedChat != null) { - dialogId = ((long) encryptedChat.id) << 32; + dialogId = DialogObject.makeEncryptedDialogId(encryptedChat.id); } else if (user != null) { dialogId = user.id; } else { @@ -3987,9 +4039,9 @@ public class AlertsCreator { myMessagesCount++; } } else { - int from_id = -1; + long from_id = -1; for (int a = 1; a >= 0; a--) { - int channelId = 0; + long channelId = 0; for (int b = 0; b < selectedMessages[a].size(); b++) { MessageObject msg = selectedMessages[a].valueAt(b); if (from_id == -1) { @@ -4043,7 +4095,7 @@ public class AlertsCreator { } else if (error != null && "USER_NOT_PARTICIPANT".equals(error.text)) { loadType = 0; } - createDeleteMessagesAlert(fragment, user, chat, encryptedChat, chatInfo, mergeDialogId, selectedMessage, selectedMessages, selectedGroup, scheduled, loadType, onDelete); + createDeleteMessagesAlert(fragment, user, chat, encryptedChat, chatInfo, mergeDialogId, selectedMessage, selectedMessages, selectedGroup, scheduled, loadType, onDelete, resourcesProvider); })); AndroidUtilities.runOnUIThread(() -> { if (progressDialog[0] == null) { @@ -4060,7 +4112,7 @@ public class AlertsCreator { if ((loadParticipant == 2 || !canBan) && a == 0) { continue; } - CheckBoxCell cell = new CheckBoxCell(activity, 1); + CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setTag(a); if (a == 0) { @@ -4087,7 +4139,7 @@ public class AlertsCreator { } else if (!hasNotOut && myMessagesCount > 0 && hasNonDiceMessages) { hasDeleteForAllCheck = true; FrameLayout frameLayout = new FrameLayout(activity); - CheckBoxCell cell = new CheckBoxCell(activity, 1); + CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (chat != null && hasNotOut) { cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false); @@ -4114,7 +4166,8 @@ public class AlertsCreator { selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionEmpty || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall || selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage || - selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) && (selectedMessage.isOut() || canRevokeInbox || ChatObject.hasAdminRights(chat)) && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit; + selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached || + selectedMessage.messageOwner.action instanceof TLRPC.TL_messageActionSetChatTheme) && (selectedMessage.isOut() || canRevokeInbox || ChatObject.hasAdminRights(chat)) && (currentDate - selectedMessage.messageOwner.date) <= revokeTimeLimit; if (hasOutgoing) { myMessagesCount++; } @@ -4145,7 +4198,7 @@ public class AlertsCreator { if (myMessagesCount > 0 && hasNonDiceMessages && (user == null || !UserObject.isDeleted(user))) { hasDeleteForAllCheck = true; FrameLayout frameLayout = new FrameLayout(activity); - CheckBoxCell cell = new CheckBoxCell(activity, 1); + CheckBoxCell cell = new CheckBoxCell(activity, 1, resourcesProvider); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (canDeleteInbox) { cell.setText(LocaleController.formatString("DeleteMessagesOptionAlso", R.string.DeleteMessagesOptionAlso, UserObject.getFirstName(user)), "", false, false); @@ -4189,7 +4242,7 @@ public class AlertsCreator { random_ids.add(selectedMessage.messageOwner.random_id); } } - MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, selectedMessage.messageOwner.peer_id.channel_id, deleteForAll[0], scheduled); + MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, deleteForAll[0], scheduled); } else { for (int a = 1; a >= 0; a--) { ids = new ArrayList<>(); @@ -4197,7 +4250,7 @@ public class AlertsCreator { ids.add(selectedMessages[a].keyAt(b)); } ArrayList random_ids = null; - int channelId = 0; + long channelId = 0; if (!ids.isEmpty()) { MessageObject msg = selectedMessages[a].get(ids.get(0)); if (msg.messageOwner.peer_id.channel_id != 0) { @@ -4213,7 +4266,7 @@ public class AlertsCreator { } } } - MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, channelId, deleteForAll[0], scheduled); + MessagesController.getInstance(currentAccount).deleteMessages(ids, random_ids, encryptedChat, dialogId, deleteForAll[0], scheduled); selectedMessages[a].clear(); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedArrowDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedArrowDrawable.java index 19fcb2015..033f949d6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedArrowDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedArrowDrawable.java @@ -92,6 +92,7 @@ public class AnimatedArrowDrawable extends Drawable { public void setColor(int color) { paint.setColor(color); + invalidateSelf(); } @Keep diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java index c09c2a8f4..355318046 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java @@ -59,6 +59,7 @@ import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildConfig; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; @@ -224,8 +225,8 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. } }; - public AudioPlayerAlert(final Context context) { - super(context, true); + public AudioPlayerAlert(final Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, true, resourcesProvider); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (messageObject != null) { @@ -379,7 +380,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. shadowDrawable.draw(canvas); if (rad != 1.0f) { - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_dialogBackground)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(Theme.key_dialogBackground)); rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24)); canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * rad, AndroidUtilities.dp(12) * rad, Theme.dialogs_onlineCirclePaint); } @@ -388,14 +389,14 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. float alphaProgress = 1.0f; int w = AndroidUtilities.dp(36); rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4)); - int color = Theme.getColor(Theme.key_sheet_scrollUp); + int color = getThemedColor(Theme.key_sheet_scrollUp); int alpha = Color.alpha(color); Theme.dialogs_onlineCirclePaint.setColor(color); Theme.dialogs_onlineCirclePaint.setAlpha((int) (alpha * alphaProgress * rad)); canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint); } - int color1 = Theme.getColor(Theme.key_dialogBackground); + int color1 = getThemedColor(Theme.key_dialogBackground); int finalColor = Color.argb((int) (255 * actionBar.getAlpha()), (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); Theme.dialogs_onlineCirclePaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, 0, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, Theme.dialogs_onlineCirclePaint); @@ -407,7 +408,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. super.onAttachedToWindow(); Bulletin.addDelegate(this, new Bulletin.Delegate() { @Override - public int getBottomOffset() { + public int getBottomOffset(int tag) { return playerLayout.getHeight(); } }); @@ -422,47 +423,43 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. containerView.setWillNotDraw(false); containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0); - actionBar = new ActionBar(context) { + actionBar = new ActionBar(context, resourcesProvider) { @Override public void setAlpha(float alpha) { super.setAlpha(alpha); containerView.invalidate(); } }; - actionBar.setBackgroundColor(Theme.getColor(Theme.key_player_actionBar)); + actionBar.setBackgroundColor(getThemedColor(Theme.key_player_actionBar)); actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setItemsColor(Theme.getColor(Theme.key_player_actionBarTitle), false); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_player_actionBarSelector), false); - actionBar.setTitleColor(Theme.getColor(Theme.key_player_actionBarTitle)); + actionBar.setItemsColor(getThemedColor(Theme.key_player_actionBarTitle), false); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_player_actionBarSelector), false); + actionBar.setTitleColor(getThemedColor(Theme.key_player_actionBarTitle)); actionBar.setTitle(LocaleController.getString("AttachMusic", R.string.AttachMusic)); - actionBar.setSubtitleColor(Theme.getColor(Theme.key_player_actionBarSubtitle)); + actionBar.setSubtitleColor(getThemedColor(Theme.key_player_actionBarSubtitle)); actionBar.setOccupyStatusBar(false); actionBar.setAlpha(0.0f); if (messageObject != null && !MediaController.getInstance().currentPlaylistIsGlobalSearch()) { long did = messageObject.getDialogId(); - int lower_id = (int) did; - int high_id = (int) (did >> 32); - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); - if (user != null) { - actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); - } - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (chat != null) { - actionBar.setTitle(chat.title); - } - } - } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(did)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(did)); if (encryptedChat != null) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); if (user != null) { actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); } } + } else if (DialogObject.isUserDialog(did)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); + if (user != null) { + actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); + } + } else { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); + if (chat != null) { + actionBar.setTitle(chat.title); + } } } @@ -501,9 +498,9 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search)); EditTextBoldCursor editText = searchItem.getSearchField(); editText.setHint(LocaleController.getString("Search", R.string.Search)); - editText.setTextColor(Theme.getColor(Theme.key_player_actionBarTitle)); - editText.setHintTextColor(Theme.getColor(Theme.key_player_time)); - editText.setCursorColor(Theme.getColor(Theme.key_player_actionBarTitle)); + editText.setTextColor(getThemedColor(Theme.key_player_actionBarTitle)); + editText.setHintTextColor(getThemedColor(Theme.key_player_time)); + editText.setCursorColor(getThemedColor(Theme.key_player_actionBarTitle)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override @@ -521,7 +518,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. actionBarShadow.setBackgroundResource(R.drawable.header_shadow); playerShadow = new View(context); - playerShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + playerShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); playerLayout = new FrameLayout(context) { @Override @@ -567,7 +564,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. @Override protected TextView createTextView() { final TextView textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_player_actionBarTitle)); + textView.setTextColor(getThemedColor(Theme.key_player_actionBarTitle)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setEllipsize(TextUtils.TruncateAt.END); @@ -581,12 +578,12 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. @Override protected TextView createTextView() { final TextView textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_player_time)); + textView.setTextColor(getThemedColor(Theme.key_player_time)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setSingleLine(true); textView.setPadding(AndroidUtilities.dp(6), 0, AndroidUtilities.dp(6), AndroidUtilities.dp(1)); - textView.setBackground(Theme.createRadSelectorDrawable(Theme.getColor(Theme.key_listSelector), AndroidUtilities.dp(4), AndroidUtilities.dp(4))); + textView.setBackground(Theme.createRadSelectorDrawable(getThemedColor(Theme.key_listSelector), AndroidUtilities.dp(4), AndroidUtilities.dp(4))); textView.setOnClickListener(view -> { int dialogsCount = MessagesController.getInstance(currentAccount).getTotalDialogsCount(); @@ -613,7 +610,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. }; playerLayout.addView(authorTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 14, 47, 72, 0)); - seekBarView = new SeekBarView(context) { + seekBarView = new SeekBarView(context, resourcesProvider) { @Override boolean onTouch(MotionEvent ev) { if (rewindingState != 0) { @@ -651,25 +648,25 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. progressView = new LineProgressView(context); progressView.setVisibility(View.INVISIBLE); - progressView.setBackgroundColor(Theme.getColor(Theme.key_player_progressBackground)); - progressView.setProgressColor(Theme.getColor(Theme.key_player_progress)); + progressView.setBackgroundColor(getThemedColor(Theme.key_player_progressBackground)); + progressView.setProgressColor(getThemedColor(Theme.key_player_progress)); playerLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.TOP | Gravity.LEFT, 21, 90, 21, 0)); timeTextView = new SimpleTextView(context); timeTextView.setTextSize(12); timeTextView.setText("0:00"); - timeTextView.setTextColor(Theme.getColor(Theme.key_player_time)); + timeTextView.setTextColor(getThemedColor(Theme.key_player_time)); timeTextView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); playerLayout.addView(timeTextView, LayoutHelper.createFrame(100, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 98, 0, 0)); durationTextView = new TextView(context); durationTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); - durationTextView.setTextColor(Theme.getColor(Theme.key_player_time)); + durationTextView.setTextColor(getThemedColor(Theme.key_player_time)); durationTextView.setGravity(Gravity.CENTER); durationTextView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); playerLayout.addView(durationTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT, 0, 96, 20, 0)); - playbackSpeedButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_dialogTextBlack)); + playbackSpeedButton = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider); playbackSpeedButton.setLongClickEnabled(false); playbackSpeedButton.setShowSubmenuByMove(false); playbackSpeedButton.setAdditionalYOffset(-AndroidUtilities.dp(224)); @@ -725,12 +722,12 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. }; playerLayout.addView(bottomView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 66, Gravity.TOP | Gravity.LEFT, 0, 111, 0, 0)); - buttons[0] = repeatButton = new ActionBarMenuItem(context, null, 0, 0); + buttons[0] = repeatButton = new ActionBarMenuItem(context, null, 0, 0, false, resourcesProvider); repeatButton.setLongClickEnabled(false); repeatButton.setShowSubmenuByMove(false); repeatButton.setAdditionalYOffset(-AndroidUtilities.dp(166)); if (Build.VERSION.SDK_INT >= 21) { - repeatButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1, AndroidUtilities.dp(18))); + repeatButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1, AndroidUtilities.dp(18))); } bottomView.addView(repeatButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); repeatButton.setOnClickListener(v -> { @@ -774,7 +771,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. updateRepeatButton(); }); - final int iconColor = Theme.getColor(Theme.key_player_button); + final int iconColor = getThemedColor(Theme.key_player_button); float touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); buttons[1] = prevButton = new RLottieImageView(context) { @@ -910,7 +907,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. prevButton.setLayerColor("Triangle 4.**", iconColor); prevButton.setLayerColor("Rectangle 4.**", iconColor); if (Build.VERSION.SDK_INT >= 21) { - prevButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1, AndroidUtilities.dp(22))); + prevButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1, AndroidUtilities.dp(22))); } bottomView.addView(prevButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); prevButton.setContentDescription(LocaleController.getString("AccDescrPrevious", R.string.AccDescrPrevious)); @@ -919,9 +916,9 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. playButton.setScaleType(ImageView.ScaleType.CENTER); playButton.setImageDrawable(playPauseDrawable = new PlayPauseDrawable(28)); playPauseDrawable.setPause(!MediaController.getInstance().isMessagePaused(), false); - playButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_player_button), PorterDuff.Mode.MULTIPLY)); + playButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_player_button), PorterDuff.Mode.MULTIPLY)); if (Build.VERSION.SDK_INT >= 21) { - playButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1, AndroidUtilities.dp(24))); + playButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1, AndroidUtilities.dp(24))); } bottomView.addView(playButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); playButton.setOnClickListener(v -> { @@ -1028,19 +1025,19 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. nextButton.setLayerColor("Rectangle 4.**", iconColor); nextButton.setRotation(180f); if (Build.VERSION.SDK_INT >= 21) { - nextButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1, AndroidUtilities.dp(22))); + nextButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1, AndroidUtilities.dp(22))); } bottomView.addView(nextButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); nextButton.setContentDescription(LocaleController.getString("Next", R.string.Next)); - buttons[4] = optionsButton = new ActionBarMenuItem(context, null, 0, iconColor); + buttons[4] = optionsButton = new ActionBarMenuItem(context, null, 0, iconColor, false, resourcesProvider); optionsButton.setLongClickEnabled(false); optionsButton.setShowSubmenuByMove(false); optionsButton.setIcon(R.drawable.ic_ab_other); optionsButton.setSubMenuOpenSide(2); optionsButton.setAdditionalYOffset(-AndroidUtilities.dp(157)); if (Build.VERSION.SDK_INT >= 21) { - optionsButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1, AndroidUtilities.dp(18))); + optionsButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1, AndroidUtilities.dp(18))); } bottomView.addView(optionsButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP)); optionsButton.addSubItem(1, R.drawable.msg_forward, LocaleController.getString("Forward", R.string.Forward)); @@ -1061,11 +1058,11 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. emptyImageView = new ImageView(context); emptyImageView.setImageResource(R.drawable.music_empty); - emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); + emptyImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); emptyTitleTextView = new TextView(context); - emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptyTitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptyTitleTextView.setGravity(Gravity.CENTER); emptyTitleTextView.setText(LocaleController.getString("NoAudioFound", R.string.NoAudioFound)); emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -1074,7 +1071,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0)); emptySubtitleTextView = new TextView(context); - emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptySubtitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptySubtitleTextView.setGravity(Gravity.CENTER); emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0); @@ -1123,7 +1120,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. listView.setVerticalScrollBarEnabled(false); containerView.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter = new ListAdapter(context)); - listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + listView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); listView.setOnItemClickListener((view, position) -> { if (view instanceof AudioPlayerCell) { ((AudioPlayerCell) view).didPressedButton(); @@ -1285,11 +1282,11 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. private void setMenuItemChecked(ActionBarMenuSubItem item, boolean checked) { if (checked) { - item.setTextColor(Theme.getColor(Theme.key_player_buttonActive)); - item.setIconColor(Theme.getColor(Theme.key_player_buttonActive)); + item.setTextColor(getThemedColor(Theme.key_player_buttonActive)); + item.setIconColor(getThemedColor(Theme.key_player_buttonActive)); } else { - item.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); - item.setIconColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + item.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); + item.setIconColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); } } @@ -1317,18 +1314,18 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. } else { playbackSpeedButton.setIcon(R.drawable.voice_mini_0_5); } - playbackSpeedButton.setIconColor(Theme.getColor(key)); + playbackSpeedButton.setIconColor(getThemedColor(key)); if (Build.VERSION.SDK_INT >= 21) { - playbackSpeedButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(key) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + playbackSpeedButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(key) & 0x19ffffff, 1, AndroidUtilities.dp(14))); } for (int a = 0; a < speedItems.length; a++) { if (a == 0 && Math.abs(currentPlaybackSpeed - 0.5f) < 0.001f || a == 1 && Math.abs(currentPlaybackSpeed - 1.0f) < 0.001f || a == 2 && Math.abs(currentPlaybackSpeed - 1.5f) < 0.001f || a == 3 && Math.abs(currentPlaybackSpeed - 1.8f) < 0.001f) { - speedItems[a].setColors(Theme.getColor(Theme.key_inappPlayerPlayPause), Theme.getColor(Theme.key_inappPlayerPlayPause)); + speedItems[a].setColors(getThemedColor(Theme.key_inappPlayerPlayPause), getThemedColor(Theme.key_inappPlayerPlayPause)); } else { - speedItems[a].setColors(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon)); + speedItems[a].setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon)); } } } @@ -1360,18 +1357,14 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. fragment1.finishFragment(); } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); } else { - args1.putInt("enc_id", high_part); + args1.putLong("chat_id", -did); } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats); ChatActivity chatActivity = new ChatActivity(args1); @@ -1401,11 +1394,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. if (f.exists()) { Intent intent = new Intent(Intent.ACTION_SEND); - if (messageObject != null) { - intent.setType(messageObject.getMimeType()); - } else { - intent.setType("audio/mp3"); - } + intent.setType(messageObject.getMimeType()); if (Build.VERSION.SDK_INT >= 24) { try { intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(ApplicationLoader.applicationContext, BuildConfig.APPLICATION_ID + ".provider", f)); @@ -1435,21 +1424,17 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. Bundle args = new Bundle(); long did = messageObject.getDialogId(); - int lower_part = (int) did; - int high_id = (int) (did >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); } else { - args.putInt("enc_id", high_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", did); + did = -chat.migrated_to.channel_id; + } + args.putLong("chat_id", -did); } args.putInt("message_id", messageObject.getId()); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats); @@ -1474,7 +1459,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. if (path == null || path.length() == 0) { path = FileLoader.getPathToMessage(messageObject.messageOwner).toString(); } - MediaController.saveFile(path, parentActivity, 3, fileName, messageObject.getDocument() != null ? messageObject.getDocument().mime_type : "", () -> BulletinFactory.of((FrameLayout) containerView).createDownloadBulletin(BulletinFactory.FileType.AUDIO).show()); + MediaController.saveFile(path, parentActivity, 3, fileName, messageObject.getDocument() != null ? messageObject.getDocument().mime_type : "", () -> BulletinFactory.of((FrameLayout) containerView, resourcesProvider).createDownloadBulletin(BulletinFactory.FileType.AUDIO).show()); } } @@ -1560,7 +1545,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. } } } - } else if (id == NotificationCenter.messagePlayingDidStart) { + } else { MessageObject messageObject = (MessageObject) args[0]; if (messageObject.eventId != 0) { return; @@ -1756,13 +1741,13 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. } if (mode == 0 && !SharedConfig.shuffleMusic && !SharedConfig.playOrderReversed) { repeatButton.setTag(Theme.key_player_button); - repeatButton.setIconColor(Theme.getColor(Theme.key_player_button)); - Theme.setSelectorDrawableColor(repeatButton.getBackground(), Theme.getColor(Theme.key_listSelector), true); + repeatButton.setIconColor(getThemedColor(Theme.key_player_button)); + Theme.setSelectorDrawableColor(repeatButton.getBackground(), getThemedColor(Theme.key_listSelector), true); repeatButton.setContentDescription(LocaleController.getString("AccDescrRepeatOff", R.string.AccDescrRepeatOff)); } else { repeatButton.setTag(Theme.key_player_buttonActive); - repeatButton.setIconColor(Theme.getColor(Theme.key_player_buttonActive)); - Theme.setSelectorDrawableColor(repeatButton.getBackground(), Theme.getColor(Theme.key_player_buttonActive) & 0x19ffffff, true); + repeatButton.setIconColor(getThemedColor(Theme.key_player_buttonActive)); + Theme.setSelectorDrawableColor(repeatButton.getBackground(), getThemedColor(Theme.key_player_buttonActive) & 0x19ffffff, true); if (mode == 0) { if (SharedConfig.shuffleMusic) { repeatButton.setContentDescription(LocaleController.getString("ShuffleList", R.string.ShuffleList)); @@ -1776,8 +1761,8 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. } else if (mode == 2) { repeatButton.setIcon(R.drawable.player_new_repeatone); repeatButton.setTag(Theme.key_player_buttonActive); - repeatButton.setIconColor(Theme.getColor(Theme.key_player_buttonActive)); - Theme.setSelectorDrawableColor(repeatButton.getBackground(), Theme.getColor(Theme.key_player_buttonActive) & 0x19ffffff, true); + repeatButton.setIconColor(getThemedColor(Theme.key_player_buttonActive)); + Theme.setSelectorDrawableColor(repeatButton.getBackground(), getThemedColor(Theme.key_player_buttonActive) & 0x19ffffff, true); repeatButton.setContentDescription(LocaleController.getString("AccDescrRepeatOne", R.string.AccDescrRepeatOne)); } } @@ -2001,7 +1986,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. public void notifyDataSetChanged() { super.notifyDataSetChanged(); if (playlist.size() > 1) { - playerLayout.setBackgroundColor(Theme.getColor(Theme.key_player_background)); + playerLayout.setBackgroundColor(getThemedColor(Theme.key_player_background)); playerShadow.setVisibility(View.VISIBLE); listView.setPadding(0, listView.getPaddingTop(), 0, AndroidUtilities.dp(179)); } else { @@ -2027,7 +2012,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = new AudioPlayerCell(context, MediaController.getInstance().currentPlaylistIsGlobalSearch() ? AudioPlayerCell.VIEW_TYPE_GLOBAL_SEARCH : AudioPlayerCell.VIEW_TYPE_DEFAULT); + View view = new AudioPlayerCell(context, MediaController.getInstance().currentPlaylistIsGlobalSearch() ? AudioPlayerCell.VIEW_TYPE_GLOBAL_SEARCH : AudioPlayerCell.VIEW_TYPE_DEFAULT, resourcesProvider); return new RecyclerListView.Holder(view); } @@ -2151,23 +2136,23 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter. ThemeDescription.ThemeDescriptionDelegate delegate = () -> { EditTextBoldCursor editText = searchItem.getSearchField(); - editText.setCursorColor(Theme.getColor(Theme.key_player_actionBarTitle)); + editText.setCursorColor(getThemedColor(Theme.key_player_actionBarTitle)); - repeatButton.setIconColor(Theme.getColor((String) repeatButton.getTag())); - Theme.setSelectorDrawableColor(repeatButton.getBackground(), Theme.getColor(Theme.key_listSelector), true); + repeatButton.setIconColor(getThemedColor((String) repeatButton.getTag())); + Theme.setSelectorDrawableColor(repeatButton.getBackground(), getThemedColor(Theme.key_listSelector), true); - optionsButton.setIconColor(Theme.getColor(Theme.key_player_button)); - Theme.setSelectorDrawableColor(optionsButton.getBackground(), Theme.getColor(Theme.key_listSelector), true); + optionsButton.setIconColor(getThemedColor(Theme.key_player_button)); + Theme.setSelectorDrawableColor(optionsButton.getBackground(), getThemedColor(Theme.key_listSelector), true); - progressView.setBackgroundColor(Theme.getColor(Theme.key_player_progressBackground)); - progressView.setProgressColor(Theme.getColor(Theme.key_player_progress)); + progressView.setBackgroundColor(getThemedColor(Theme.key_player_progressBackground)); + progressView.setProgressColor(getThemedColor(Theme.key_player_progress)); updateSubMenu(); - repeatButton.redrawPopup(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + repeatButton.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); - optionsButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), false); - optionsButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), true); - optionsButton.redrawPopup(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + optionsButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false); + optionsButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), true); + optionsButton.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); }; themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_player_actionBar)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarDrawable.java index 45cd100f0..9b7223383 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarDrawable.java @@ -60,10 +60,15 @@ public class AvatarDrawable extends Drawable { public static final int AVATAR_TYPE_FILTER_ARCHIVED = 11; private int alpha = 255; + private Theme.ResourcesProvider resourcesProvider; public AvatarDrawable() { - super(); + this((Theme.ResourcesProvider) null); + } + public AvatarDrawable(Theme.ResourcesProvider resourcesProvider) { + super(); + this.resourcesProvider = resourcesProvider; namePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); namePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); namePaint.setTextSize(AndroidUtilities.dp(18)); @@ -98,39 +103,39 @@ public class AvatarDrawable extends Drawable { isProfile = value; } - private static int getColorIndex(int id) { + private static int getColorIndex(long id) { if (id >= 0 && id < 7) { - return id; + return (int) id; } - return Math.abs(id % Theme.keys_avatar_background.length); + return (int) Math.abs(id % Theme.keys_avatar_background.length); } - public static int getColorForId(int id) { + public static int getColorForId(long id) { return Theme.getColor(Theme.keys_avatar_background[getColorIndex(id)]); } - public static int getButtonColorForId(int id) { + public static int getButtonColorForId(long id) { return Theme.getColor(Theme.key_avatar_actionBarSelectorBlue); } - public static int getIconColorForId(int id) { + public static int getIconColorForId(long id) { return Theme.getColor(Theme.key_avatar_actionBarIconBlue); } - public static int getProfileColorForId(int id) { + public static int getProfileColorForId(long id) { return Theme.getColor(Theme.keys_avatar_background[getColorIndex(id)]); } - public static int getProfileTextColorForId(int id) { + public static int getProfileTextColorForId(long id) { return Theme.getColor(Theme.key_avatar_subtitleInProfileBlue); } - public static int getProfileBackColorForId(int id) { + public static int getProfileBackColorForId(long id) { return Theme.getColor(Theme.key_avatar_backgroundActionBarBlue); } - public static int getNameColorForId(int id) { - return Theme.getColor(Theme.keys_avatar_nameInMessage[getColorIndex(id)]); + public static String getNameColorNameForId(long id) { + return Theme.keys_avatar_nameInMessage[getColorIndex(id)]; } public void setInfo(TLRPC.User user) { @@ -155,30 +160,30 @@ public class AvatarDrawable extends Drawable { public void setAvatarType(int value) { avatarType = value; if (avatarType == AVATAR_TYPE_ARCHIVED) { - color = Theme.getColor(Theme.key_avatar_backgroundArchivedHidden); + color = getThemedColor(Theme.key_avatar_backgroundArchivedHidden); } else if (avatarType == AVATAR_TYPE_REPLIES) { - color = Theme.getColor(Theme.key_avatar_backgroundSaved); + color = getThemedColor(Theme.key_avatar_backgroundSaved); } else if (avatarType == AVATAR_TYPE_SAVED) { - color = Theme.getColor(Theme.key_avatar_backgroundSaved); + color = getThemedColor(Theme.key_avatar_backgroundSaved); } else if (avatarType == AVATAR_TYPE_SHARES) { - color = getColorForId(5); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]); } else { if (avatarType == AVATAR_TYPE_FILTER_CONTACTS) { - color = getColorForId(5); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]); } else if (avatarType == AVATAR_TYPE_FILTER_NON_CONTACTS) { - color = getColorForId(4); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]); } else if (avatarType == AVATAR_TYPE_FILTER_GROUPS) { - color = getColorForId(3); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(3)]); } else if (avatarType == AVATAR_TYPE_FILTER_CHANNELS) { - color = getColorForId(1); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(1)]); } else if (avatarType == AVATAR_TYPE_FILTER_BOTS) { - color = getColorForId(0); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(0)]); } else if (avatarType == AVATAR_TYPE_FILTER_MUTED) { - color = getColorForId(6); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(6)]); } else if (avatarType == AVATAR_TYPE_FILTER_READ) { - color = getColorForId(5); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]); } else { - color = getColorForId(4); + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]); } } needApplyColorAccent = avatarType != AVATAR_TYPE_ARCHIVED && avatarType != AVATAR_TYPE_SAVED && avatarType != AVATAR_TYPE_REPLIES; @@ -207,7 +212,7 @@ public class AvatarDrawable extends Drawable { namePaint.setTextSize(size); } - public void setInfo(int id, String firstName, String lastName) { + public void setInfo(long id, String firstName, String lastName) { setInfo(id, firstName, lastName, null); } @@ -215,12 +220,8 @@ public class AvatarDrawable extends Drawable { return needApplyColorAccent ? Theme.changeColorAccent(color) : color; } - public void setInfo(int id, String firstName, String lastName, String custom) { - if (isProfile) { - color = getProfileColorForId(id); - } else { - color = getColorForId(id); - } + public void setInfo(long id, String firstName, String lastName, String custom) { + color = getThemedColor(Theme.keys_avatar_background[getColorIndex(id)]); needApplyColorAccent = id == 5; // Tinting manually set blue color avatarType = AVATAR_TYPE_NORMAL; @@ -289,7 +290,7 @@ public class AvatarDrawable extends Drawable { return; } int size = bounds.width(); - namePaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_avatar_text), alpha)); + namePaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_avatar_text), alpha)); Theme.avatar_backgroundPaint.setColor(ColorUtils.setAlphaComponent(getColor(), alpha)); canvas.save(); canvas.translate(bounds.left, bounds.top); @@ -297,7 +298,7 @@ public class AvatarDrawable extends Drawable { if (avatarType == AVATAR_TYPE_ARCHIVED) { if (archivedAvatarProgress != 0) { - Theme.avatar_backgroundPaint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_avatar_backgroundArchived), alpha)); + Theme.avatar_backgroundPaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_avatar_backgroundArchived), alpha)); canvas.drawCircle(size / 2.0f, size / 2.0f, size / 2.0f * archivedAvatarProgress, Theme.avatar_backgroundPaint); if (Theme.dialogs_archiveAvatarDrawableRecolored) { Theme.dialogs_archiveAvatarDrawable.beginApplyLayerColors(); @@ -415,4 +416,9 @@ public class AvatarDrawable extends Drawable { public int getIntrinsicHeight() { return 0; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarsImageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarsImageView.java index def100f43..db9b202b7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarsImageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AvatarsImageView.java @@ -17,6 +17,7 @@ import androidx.core.graphics.ColorUtils; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; @@ -34,6 +35,7 @@ public class AvatarsImageView extends FrameLayout { public final static int STYLE_GROUP_CALL_TOOLTIP = 10; + public final static int STYLE_MESSAGE_SEEN = 11; DrawingState[] currentStates = new DrawingState[3]; DrawingState[] animatingStates = new DrawingState[3]; @@ -168,7 +170,7 @@ public class AvatarsImageView extends FrameLayout { private ImageReceiver imageReceiver; TLRPC.TL_groupCallParticipant participant; - private int id; + private long id; private int animationType; private int moveFromIndex; @@ -183,13 +185,13 @@ public class AvatarsImageView extends FrameLayout { currentStates[a].imageReceiver = new ImageReceiver(this); currentStates[a].imageReceiver.setRoundRadius(AndroidUtilities.dp(12)); currentStates[a].avatarDrawable = new AvatarDrawable(); - currentStates[a].avatarDrawable.setTextSize(AndroidUtilities.dp(9)); + currentStates[a].avatarDrawable.setTextSize(AndroidUtilities.dp(12)); animatingStates[a] = new DrawingState(); animatingStates[a].imageReceiver = new ImageReceiver(this); animatingStates[a].imageReceiver.setRoundRadius(AndroidUtilities.dp(12)); animatingStates[a].avatarDrawable = new AvatarDrawable(); - animatingStates[a].avatarDrawable.setTextSize(AndroidUtilities.dp(9)); + animatingStates[a].avatarDrawable.setTextSize(AndroidUtilities.dp(12)); } isInCall = inCall; setWillNotDraw(false); @@ -211,8 +213,8 @@ public class AvatarsImageView extends FrameLayout { if (object instanceof TLRPC.TL_groupCallParticipant) { TLRPC.TL_groupCallParticipant participant = (TLRPC.TL_groupCallParticipant) object; animatingStates[index].participant = participant; - int id = MessageObject.getPeerId(participant.peer); - if (id > 0) { + long id = MessageObject.getPeerId(participant.peer); + if (DialogObject.isUserDialog(id)) { currentUser = MessagesController.getInstance(account).getUser(id); animatingStates[index].avatarDrawable.setInfo(currentUser); } else { @@ -261,14 +263,19 @@ public class AvatarsImageView extends FrameLayout { boolean bigAvatars = currentStyle == 4 || currentStyle == STYLE_GROUP_CALL_TOOLTIP; int size = AndroidUtilities.dp(bigAvatars ? 32 : 24); - int toAdd = AndroidUtilities.dp(bigAvatars ? 24 : 20); + int toAdd; + if (currentStyle == STYLE_MESSAGE_SEEN) { + toAdd = AndroidUtilities.dp(12); + } else { + toAdd = AndroidUtilities.dp(bigAvatars ? 24 : 20); + } int drawCount = 0; for (int i = 0; i < 3; i++) { if (currentStates[i].id != 0) { drawCount++; } } - int startPadding = (currentStyle == 0 || currentStyle == STYLE_GROUP_CALL_TOOLTIP) ? 0 : AndroidUtilities.dp(10); + int startPadding = (currentStyle == 0 || currentStyle == STYLE_GROUP_CALL_TOOLTIP || currentStyle == STYLE_MESSAGE_SEEN) ? 0 : AndroidUtilities.dp(10); int ax = centered ? (getMeasuredWidth() - drawCount * toAdd - AndroidUtilities.dp(bigAvatars ? 8 : 4)) / 2 : startPadding; boolean isMuted = VoIPService.getSharedInstance() != null && VoIPService.getSharedInstance().isMicMute(); if (currentStyle == 4) { @@ -283,7 +290,7 @@ public class AvatarsImageView extends FrameLayout { animateToDrawCount++; } } - boolean useAlphaLayer = currentStyle == 0 || currentStyle == 1 || currentStyle == 3 || currentStyle == 4 || currentStyle == 5 || currentStyle == STYLE_GROUP_CALL_TOOLTIP; + boolean useAlphaLayer = currentStyle == 0 || currentStyle == 1 || currentStyle == 3 || currentStyle == 4 || currentStyle == 5 || currentStyle == STYLE_GROUP_CALL_TOOLTIP || currentStyle == STYLE_MESSAGE_SEEN; if (useAlphaLayer) { float padding = currentStyle == STYLE_GROUP_CALL_TOOLTIP ? AndroidUtilities.dp(16) : 0; canvas.saveLayerAlpha(-padding, -padding, getMeasuredWidth() + padding, getMeasuredHeight() + padding, 255, Canvas.ALL_SAVE_FLAG); @@ -310,7 +317,7 @@ public class AvatarsImageView extends FrameLayout { imageReceiver.setImageX(ax + toAdd * a); } - if (currentStyle == 0 || currentStyle == STYLE_GROUP_CALL_TOOLTIP) { + if (currentStyle == 0 || currentStyle == STYLE_GROUP_CALL_TOOLTIP || currentStyle == STYLE_MESSAGE_SEEN) { imageReceiver.setImageY((getMeasuredHeight() - size) / 2f); } else { imageReceiver.setImageY(AndroidUtilities.dp(currentStyle == 4 ? 8 : 6)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BlockingUpdateView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BlockingUpdateView.java index 6beacf395..8f414e579 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BlockingUpdateView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BlockingUpdateView.java @@ -8,6 +8,9 @@ import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; import android.net.Uri; import android.os.Build; import android.provider.Settings; @@ -22,6 +25,8 @@ import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; +import com.google.android.exoplayer2.util.Log; + import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildConfig; @@ -37,6 +42,7 @@ import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.Components.voip.CellFlickerDrawable; import java.io.File; import java.util.Locale; @@ -48,6 +54,7 @@ public class BlockingUpdateView extends FrameLayout implements NotificationCente private FrameLayout radialProgressView; private FrameLayout acceptButton; private RadialProgress radialProgress; + private ScrollView scrollView; private AnimatorSet progressAnimation; @@ -63,11 +70,12 @@ public class BlockingUpdateView extends FrameLayout implements NotificationCente int top = Build.VERSION.SDK_INT >= 21 ? (int) (AndroidUtilities.statusBarHeight / AndroidUtilities.density) : 0; FrameLayout view = new FrameLayout(context); - view.setBackgroundColor(0xff4fa9e6); addView(view, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(176) + (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0))); - ImageView imageView = new ImageView(context); - imageView.setImageResource(R.drawable.intro_tg_plane); + RLottieImageView imageView = new RLottieImageView(context); + imageView.setAnimation(R.raw.qr_code_logo, 108, 108); + imageView.playAnimation(); + imageView.getAnimatedDrawable().setAutoRepeat(1); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setPadding(0, 0, 0, AndroidUtilities.dp(14)); view.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, top, 0, 0)); @@ -80,12 +88,15 @@ public class BlockingUpdateView extends FrameLayout implements NotificationCente } }); - ScrollView scrollView = new ScrollView(context); - AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault)); - addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 27, 206 + top, 27, 130)); - FrameLayout container = new FrameLayout(context); - scrollView.addView(container, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); + scrollView = new ScrollView(context); + AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault)); + scrollView.setPadding(0, AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16)); + scrollView.setClipToPadding(false); + addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 27, 178 + top, 27, 130)); + + + scrollView.addView(container); TextView titleTextView = new TextView(context); titleTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); @@ -104,10 +115,38 @@ public class BlockingUpdateView extends FrameLayout implements NotificationCente textView.setLineSpacing(AndroidUtilities.dp(2), 1.0f); container.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 44, 0, 0)); - acceptButton = new FrameLayout(context); - acceptButton.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), 0xff50a8eb, 0xff439bde)); + + acceptButton = new FrameLayout(context) { + CellFlickerDrawable cellFlickerDrawable; + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (cellFlickerDrawable == null) { + cellFlickerDrawable = new CellFlickerDrawable(); + cellFlickerDrawable.drawFrame = false; + cellFlickerDrawable.repeatProgress = 2f; + } + cellFlickerDrawable.setParentWidth(getMeasuredWidth()); + AndroidUtilities.rectTmp.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); + cellFlickerDrawable.draw(canvas, AndroidUtilities.rectTmp, AndroidUtilities.dp(4)); + invalidate(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int size = MeasureSpec.getSize(widthMeasureSpec); + if (size > AndroidUtilities.dp(260)) { + super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(320), MeasureSpec.EXACTLY), heightMeasureSpec); + } else { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + } + }; acceptButton.setPadding(AndroidUtilities.dp(34), 0, AndroidUtilities.dp(34), 0); - addView(acceptButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 42, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, 45)); + acceptButton.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + acceptButton.setPadding(AndroidUtilities.dp(34), 0, AndroidUtilities.dp(34), 0); + addView(acceptButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 46, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, 45)); acceptButton.setOnClickListener(view1 -> { if (!checkApkInstallPermissions(getContext())) { return; @@ -329,4 +368,18 @@ public class BlockingUpdateView extends FrameLayout implements NotificationCente })); } } + + Drawable gradientDrawableTop = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Theme.getColor(Theme.key_windowBackgroundWhite), Color.TRANSPARENT }); + Drawable gradientDrawableBottom = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, new int[] {Theme.getColor(Theme.key_windowBackgroundWhite), Color.TRANSPARENT }); + + @Override + protected void dispatchDraw(Canvas canvas) { + super.dispatchDraw(canvas); + gradientDrawableTop.setBounds(scrollView.getLeft(), scrollView.getTop(), scrollView.getRight(), scrollView.getTop() + AndroidUtilities.dp(16)); + gradientDrawableTop.draw(canvas); + + gradientDrawableBottom.setBounds(scrollView.getLeft(), scrollView.getBottom() - AndroidUtilities.dp(18), scrollView.getRight(), scrollView.getBottom()); + gradientDrawableBottom.draw(canvas); + } + } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BlurBehindDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BlurBehindDrawable.java index 63e5faaf7..ec9f80556 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BlurBehindDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BlurBehindDrawable.java @@ -13,6 +13,7 @@ import org.telegram.messenger.DispatchQueue; import org.telegram.messenger.FileLog; import org.telegram.messenger.Utilities; import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.ChatActivity; import static android.graphics.Canvas.ALL_SAVE_FLAG; @@ -58,16 +59,16 @@ public class BlurBehindDrawable { Paint emptyPaint = new Paint(Paint.FILTER_BITMAP_FLAG); Paint errorBlackoutPaint = new Paint(); + private final Theme.ResourcesProvider resourcesProvider; - public BlurBehindDrawable(View behindView, View parentView, int type) { + public BlurBehindDrawable(View behindView, View parentView, int type, Theme.ResourcesProvider resourcesProvider) { this.type = type; this.behindView = behindView; this.parentView = parentView; - + this.resourcesProvider = resourcesProvider; errorBlackoutPaint.setColor(Color.BLACK); } - public void draw(Canvas canvas) { if (type == 1 && !wasDraw && !animateAlpha) { generateBlurredBitmaps(); @@ -107,12 +108,16 @@ public class BlurBehindDrawable { if (type == 1) { canvas.translate(0, panTranslationY); } - canvas.drawBitmap(bitmap[1], 0, 0, null); + canvas.save(); + canvas.scale( parentView.getMeasuredWidth() / (float) bitmap[1].getWidth(), parentView.getMeasuredHeight() / (float) bitmap[1].getHeight()); + canvas.drawBitmap(bitmap[1], 0, 0, emptyPaint); + canvas.restore(); canvas.save(); if (type == 0) { canvas.translate(0, panTranslationY); } - canvas.drawBitmap(bitmap[0], 0, 0, null); + canvas.scale(parentView.getMeasuredWidth() / (float) bitmap[0].getWidth(),toolbarH / (float) bitmap[0].getHeight()); + canvas.drawBitmap(bitmap[0], 0, 0, emptyPaint); canvas.restore(); wasDraw = true; canvas.drawColor(0x1a000000); @@ -130,7 +135,7 @@ public class BlurBehindDrawable { if (blurredBitmapTmp[i] == null || parentView.getMeasuredWidth() != lastW || parentView.getMeasuredHeight() != lastH) { int lastH = parentView.getMeasuredHeight(); int lastW = parentView.getMeasuredWidth(); - toolbarH = AndroidUtilities.statusBarHeight + AndroidUtilities.dp(100); + toolbarH = AndroidUtilities.statusBarHeight + AndroidUtilities.dp(200); try { int h = i == 0 ? toolbarH : lastH; blurredBitmapTmp[i] = Bitmap.createBitmap((int) (lastW / DOWN_SCALE), (int) (h / DOWN_SCALE), Bitmap.Config.ARGB_8888); @@ -147,13 +152,13 @@ public class BlurBehindDrawable { blurredBitmapTmp[i].eraseColor(Color.TRANSPARENT); } if (i == 1) { - blurredBitmapTmp[i].eraseColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + blurredBitmapTmp[i].eraseColor(getThemedColor(Theme.key_windowBackgroundWhite)); } blurCanvas[i].save(); blurCanvas[i].scale(1f / DOWN_SCALE, 1f / DOWN_SCALE, 0, 0); Drawable backDrawable = behindView.getBackground(); if (backDrawable == null) { - backDrawable = Theme.getCachedWallpaperNonBlocking(); + backDrawable = getBackgroundDrawable(); } behindView.setTag(TAG_DRAWING_AS_BACKGROUND, i); if (i == STATIC_CONTENT) { @@ -271,7 +276,7 @@ public class BlurBehindDrawable { for (int i = 0; i < 2; i++) { int lastH = parentView.getMeasuredHeight(); int lastW = parentView.getMeasuredWidth(); - toolbarH = AndroidUtilities.statusBarHeight + AndroidUtilities.dp(100); + toolbarH = AndroidUtilities.statusBarHeight + AndroidUtilities.dp(200); int h = i == 0 ? toolbarH : lastH; if (bitmap[i] == null || bitmap[i].getHeight() != h || bitmap[i].getWidth() != parentView.getMeasuredWidth()) { @@ -281,11 +286,13 @@ public class BlurBehindDrawable { blurredBitmapTmp[i] = Bitmap.createBitmap((int) (lastW / DOWN_SCALE), (int) (h / DOWN_SCALE), Bitmap.Config.ARGB_8888); if (i == 1) { - blurredBitmapTmp[i].eraseColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + blurredBitmapTmp[i].eraseColor(getThemedColor(Theme.key_windowBackgroundWhite)); } blurCanvas[i] = new Canvas(blurredBitmapTmp[i]); - renderingBitmap[i] = Bitmap.createBitmap(lastW, i == 0 ? toolbarH : lastH, Bitmap.Config.ARGB_8888); + int bitmapH = (int) ((i == 0 ? toolbarH : lastH) / DOWN_SCALE); + int bitmapW = (int) (lastW / DOWN_SCALE); + renderingBitmap[i] = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888); renderingBitmapCanvas[i] = new Canvas(renderingBitmap[i]); renderingBitmapCanvas[i].scale((float) renderingBitmap[i].getWidth() / (float) blurredBitmapTmp[i].getWidth(), (float) renderingBitmap[i].getHeight() / (float) blurredBitmapTmp[i].getHeight()); @@ -293,7 +300,7 @@ public class BlurBehindDrawable { blurCanvas[i].scale(1f / DOWN_SCALE, 1f / DOWN_SCALE, 0, 0); Drawable backDrawable = behindView.getBackground(); if (backDrawable == null) { - backDrawable = Theme.getCachedWallpaperNonBlocking(); + backDrawable = getBackgroundDrawable(); } behindView.setTag(TAG_DRAWING_AS_BACKGROUND, i); if (i == STATIC_CONTENT) { @@ -315,7 +322,7 @@ public class BlurBehindDrawable { Utilities.stackBlurBitmap(blurredBitmapTmp[i], getBlurRadius()); emptyPaint.setAlpha(255); if (i == 1) { - renderingBitmap[i].eraseColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + renderingBitmap[i].eraseColor(getThemedColor(Theme.key_windowBackgroundWhite)); } renderingBitmapCanvas[i].drawBitmap(blurredBitmapTmp[i], 0, 0, emptyPaint); } @@ -347,9 +354,11 @@ public class BlurBehindDrawable { backgroundBitmap = new Bitmap[2]; backgroundBitmapCanvas = new Canvas[2]; } + int bitmapWidth = (int) (width / DOWN_SCALE); for (int i = 0; i < 2; i++) { - int h = i == 0 ? toolbarH : height; - if (backgroundBitmap[i] != null && (backgroundBitmap[i].getHeight() != h || backgroundBitmap[i].getWidth() != width)) { + int h = (int) ((i == 0 ? toolbarH : height) / DOWN_SCALE); + + if (backgroundBitmap[i] != null && (backgroundBitmap[i].getHeight() != h || backgroundBitmap[i].getWidth() != bitmapWidth)) { if (backgroundBitmap[i] != null) { backgroundBitmap[i].recycle(); backgroundBitmap[i] = null; @@ -357,17 +366,17 @@ public class BlurBehindDrawable { } long t = System.currentTimeMillis(); if (backgroundBitmap[i] == null) { - int w = width; + int w = bitmapWidth; try { backgroundBitmap[i] = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); backgroundBitmapCanvas[i] = new Canvas(backgroundBitmap[i]); - backgroundBitmapCanvas[i].scale(width / (float) blurredBitmapTmp[i].getWidth(), h / (float) blurredBitmapTmp[i].getHeight()); + backgroundBitmapCanvas[i].scale(bitmapWidth / (float) blurredBitmapTmp[i].getWidth(), h / (float) blurredBitmapTmp[i].getHeight()); } catch (Throwable e) { FileLog.e(e); } } if (i == 1) { - backgroundBitmap[i].eraseColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + backgroundBitmap[i].eraseColor(getThemedColor(Theme.key_windowBackgroundWhite)); } else { backgroundBitmap[i].eraseColor(Color.TRANSPARENT); } @@ -402,4 +411,15 @@ public class BlurBehindDrawable { }); } } + + private Drawable getBackgroundDrawable() { + return (resourcesProvider instanceof ChatActivity.ThemeDelegate) + ? ((ChatActivity.ThemeDelegate) resourcesProvider).getWallpaperDrawable() + : Theme.getCachedWallpaperNonBlocking(); + } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BluredView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BluredView.java index aee1873f9..2701bd196 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BluredView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BluredView.java @@ -4,13 +4,15 @@ import android.content.Context; import android.graphics.Canvas; import android.view.View; +import org.telegram.ui.ActionBar.Theme; + public class BluredView extends View { public final BlurBehindDrawable drawable; - public BluredView(Context context, View parentView) { + public BluredView(Context context, View parentView, Theme.ResourcesProvider resourcesProvider) { super(context); - drawable = new BlurBehindDrawable(parentView, this, 1); + drawable = new BlurBehindDrawable(parentView, this, 1, resourcesProvider); drawable.setAnimateAlpha(false); drawable.show(true); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BotCommandsMenuView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BotCommandsMenuView.java index 581d0b216..99b67b2d0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BotCommandsMenuView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BotCommandsMenuView.java @@ -10,7 +10,6 @@ import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; -import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.View; @@ -19,6 +18,7 @@ import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; @@ -65,7 +65,7 @@ public class BotCommandsMenuView extends View { private void updateColors() { paint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground)); - int textColor = Theme.getColor(Theme.key_windowBackgroundWhite); + int textColor = Theme.getColor(Theme.key_chat_messagePanelVoicePressed); backDrawable.setBackColor(textColor); backDrawable.setIconColor(textColor); textPaint.setColor(textColor); @@ -200,7 +200,7 @@ public class BotCommandsMenuView extends View { return newResult.size(); } - public void setBotInfo(SparseArray botInfo) { + public void setBotInfo(LongSparseArray botInfo) { newResult.clear(); newResultHelp.clear(); for (int b = 0; b < botInfo.size(); b++) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BotKeyboardView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BotKeyboardView.java index e5002304e..53fb3d62b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BotKeyboardView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BotKeyboardView.java @@ -25,6 +25,7 @@ import java.util.ArrayList; public class BotKeyboardView extends LinearLayout { + private final Theme.ResourcesProvider resourcesProvider; private LinearLayout container; private TLRPC.TL_replyKeyboardMarkup botButtons; private BotKeyboardViewDelegate delegate; @@ -38,8 +39,9 @@ public class BotKeyboardView extends LinearLayout { void didPressedButton(TLRPC.KeyboardButton button); } - public BotKeyboardView(Context context) { + public BotKeyboardView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setOrientation(VERTICAL); @@ -52,11 +54,11 @@ public class BotKeyboardView extends LinearLayout { } public void updateColors() { - AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_chat_emojiPanelBackground)); - setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, getThemedColor(Theme.key_chat_emojiPanelBackground)); + setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); for (int i = 0; i < buttonViews.size(); i++) { - buttonViews.get(i).setTextColor(Theme.getColor(Theme.key_chat_botKeyboardButtonText)); - buttonViews.get(i).setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_chat_botKeyboardButtonBackground), Theme.getColor(Theme.key_chat_botKeyboardButtonBackgroundPressed))); + buttonViews.get(i).setTextColor(getThemedColor(Theme.key_chat_botKeyboardButtonText)); + buttonViews.get(i).setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_chat_botKeyboardButtonBackground), getThemedColor(Theme.key_chat_botKeyboardButtonBackgroundPressed))); } invalidate(); } @@ -113,8 +115,8 @@ public class BotKeyboardView extends LinearLayout { TLRPC.KeyboardButton button = row.buttons.get(b); TextView textView = new TextView(getContext()); textView.setTag(button); - textView.setTextColor(Theme.getColor(Theme.key_chat_botKeyboardButtonText)); - textView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_chat_botKeyboardButtonBackground), Theme.getColor(Theme.key_chat_botKeyboardButtonBackgroundPressed))); + textView.setTextColor(getThemedColor(Theme.key_chat_botKeyboardButtonText)); + textView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_chat_botKeyboardButtonBackground), getThemedColor(Theme.key_chat_botKeyboardButtonBackgroundPressed))); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setGravity(Gravity.CENTER); @@ -134,4 +136,9 @@ public class BotKeyboardView extends LinearLayout { } return isFullSize ? panelHeight : botButtons.rows.size() * AndroidUtilities.dp(buttonHeight) + AndroidUtilities.dp(30) + (botButtons.rows.size() - 1) * AndroidUtilities.dp(10); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Bulletin.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Bulletin.java index 032039291..b366b97ca 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Bulletin.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Bulletin.java @@ -27,7 +27,6 @@ import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.CallSuper; -import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -64,6 +63,8 @@ public final class Bulletin { public static final int TYPE_BIO_CHANGED = 2; public static final int TYPE_NAME_CHANGED = 3; + public int tag; + public static Bulletin make(@NonNull FrameLayout containerLayout, @NonNull Layout contentLayout, int duration) { return new Bulletin(containerLayout, contentLayout, duration); } @@ -108,7 +109,7 @@ public final class Bulletin { private final ParentLayout parentLayout; private final FrameLayout containerLayout; private final Runnable hideRunnable = this::hide; - private final int duration; + private int duration; private boolean showing; private boolean canHide; @@ -140,6 +141,10 @@ public final class Bulletin { return visibleBulletin; } + public void setDuration(int duration) { + this.duration = duration; + } + public Bulletin show() { if (!showing && containerLayout != null) { showing = true; @@ -161,7 +166,7 @@ public final class Bulletin { if (showing) { layout.onShow(); currentDelegate = delegates.get(containerLayout); - currentBottomOffset = currentDelegate != null ? currentDelegate.getBottomOffset() : 0; + currentBottomOffset = currentDelegate != null ? currentDelegate.getBottomOffset(tag) : 0; if (currentDelegate != null) { currentDelegate.onShow(Bulletin.this); } @@ -303,7 +308,9 @@ public final class Bulletin { } public void updatePosition() { - layout.updatePosition(); + if (layout != null) { + layout.updatePosition(); + } } @Retention(SOURCE) @@ -464,7 +471,7 @@ public final class Bulletin { public interface Delegate { - default int getBottomOffset() { + default int getBottomOffset(int tag) { return 0; } @@ -488,27 +495,28 @@ public final class Bulletin { public float inOutOffset; protected Bulletin bulletin; + Drawable background; @WidthDef private int wideScreenWidth = ViewGroup.LayoutParams.WRAP_CONTENT; @GravityDef private int wideScreenGravity = Gravity.CENTER_HORIZONTAL; + private final Theme.ResourcesProvider resourcesProvider; - public Layout(@NonNull Context context) { - this(context, Theme.getColor(Theme.key_undo_background)); - } - - Drawable background; - - public Layout(@NonNull Context context, @ColorInt int backgroundColor) { + public Layout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setMinimumHeight(AndroidUtilities.dp(48)); - background = Theme.createRoundRectDrawable(AndroidUtilities.dp(6), backgroundColor); + setBackground(getThemedColor(Theme.key_undo_background)); updateSize(); setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); setWillNotDraw(false); } + protected void setBackground(int color) { + background = Theme.createRoundRectDrawable(AndroidUtilities.dp(6), color); + } + public final static FloatPropertyCompat IN_OUT_OFFSET_Y = new FloatPropertyCompat("offsetY") { @Override public float getValue(Layout object) { @@ -659,7 +667,7 @@ public final class Bulletin { public void updatePosition() { float tranlsation = 0; if (delegate != null) { - tranlsation += delegate.getBottomOffset() ; + tranlsation += delegate.getBottomOffset(bulletin != null ? bulletin.tag : 0) ; } setTranslationY(-tranlsation + inOutOffset); } @@ -822,7 +830,7 @@ public final class Bulletin { protected void dispatchDraw(Canvas canvas) { background.setBounds(AndroidUtilities.dp(8), AndroidUtilities.dp(8), getMeasuredWidth() - AndroidUtilities.dp(8), getMeasuredHeight() - AndroidUtilities.dp(8)); if (transitionRunning && delegate != null) { - int clipBottom = ((View)getParent()).getMeasuredHeight() - delegate.getBottomOffset(); + int clipBottom = ((View)getParent()).getMeasuredHeight() - delegate.getBottomOffset(bulletin.tag); int viewBottom = (int) (getY() + getMeasuredHeight()); canvas.save(); canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - (viewBottom - clipBottom)); @@ -836,6 +844,10 @@ public final class Bulletin { } } + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } //endregion } @@ -846,12 +858,8 @@ public final class Bulletin { private int childrenMeasuredWidth; - public ButtonLayout(@NonNull Context context) { - super(context); - } - - public ButtonLayout(@NonNull Context context, int backgroundColor) { - super(context, backgroundColor); + public ButtonLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); } @Override @@ -897,10 +905,10 @@ public final class Bulletin { public final ImageView imageView; public final TextView textView; - public SimpleLayout(@NonNull Context context) { - super(context); + public SimpleLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); - final int undoInfoColor = Theme.getColor(Theme.key_undo_infoColor); + final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); imageView = new ImageView(context); imageView.setColorFilter(new PorterDuffColorFilter(undoInfoColor, PorterDuff.Mode.MULTIPLY)); @@ -922,10 +930,10 @@ public final class Bulletin { public final TextView titleTextView; public final TextView subtitleTextView; - public TwoLineLayout(@NonNull Context context) { - super(context); + public TwoLineLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); - final int undoInfoColor = Theme.getColor(Theme.key_undo_infoColor); + final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); addView(imageView = new BackupImageView(context), LayoutHelper.createFrameRelatively(29, 29, Gravity.START | Gravity.CENTER_VERTICAL, 12, 12, 12, 12)); @@ -958,19 +966,16 @@ public final class Bulletin { private final int textColor; - public TwoLineLottieLayout(@NonNull Context context) { - this(context, Theme.getColor(Theme.key_undo_background), Theme.getColor(Theme.key_undo_infoColor)); - } - - public TwoLineLottieLayout(@NonNull Context context, @ColorInt int backgroundColor, @ColorInt int textColor) { - super(context, backgroundColor); - this.textColor = textColor; + public TwoLineLottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); + this.textColor = getThemedColor(Theme.key_undo_infoColor); + setBackground(getThemedColor(Theme.key_undo_background)); imageView = new RLottieImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); addView(imageView, LayoutHelper.createFrameRelatively(56, 48, Gravity.START | Gravity.CENTER_VERTICAL)); - final int undoInfoColor = Theme.getColor(Theme.key_undo_infoColor); + final int undoInfoColor = getThemedColor(Theme.key_undo_infoColor); final LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); @@ -1010,18 +1015,13 @@ public final class Bulletin { public static class LottieLayout extends ButtonLayout { - public final RLottieImageView imageView; - public final TextView textView; + public RLottieImageView imageView; + public TextView textView; - private final int textColor; + private int textColor; - public LottieLayout(@NonNull Context context) { - this(context, Theme.getColor(Theme.key_undo_background), Theme.getColor(Theme.key_undo_infoColor)); - } - - public LottieLayout(@NonNull Context context, @ColorInt int backgroundColor, @ColorInt int textColor) { - super(context, backgroundColor); - this.textColor = textColor; + public LottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); imageView = new RLottieImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); @@ -1029,12 +1029,25 @@ public final class Bulletin { textView = new TextView(context); textView.setSingleLine(); - textView.setTextColor(textColor); textView.setTypeface(Typeface.SANS_SERIF); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setPadding(0, AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); addView(textView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 56, 0, 16, 0)); + + setTextColor(getThemedColor(Theme.key_undo_infoColor)); + setBackground(getThemedColor(Theme.key_undo_background)); + } + + public LottieLayout(@NonNull Context context, Theme.ResourcesProvider resourcesProvider, int backgroundColor, int textColor) { + this(context, resourcesProvider); + setBackground(backgroundColor); + setTextColor(textColor); + } + + public void setTextColor(int textColor) { + this.textColor = textColor; + textView.setTextColor(textColor); } @Override @@ -1104,6 +1117,7 @@ public final class Bulletin { @SuppressLint("ViewConstructor") public static final class UndoButton extends Button { + private final Theme.ResourcesProvider resourcesProvider; private Runnable undoAction; private Runnable delayedAction; @@ -1111,9 +1125,14 @@ public final class Bulletin { private boolean isUndone; public UndoButton(@NonNull Context context, boolean text) { - super(context); + this(context, text, null); + } - final int undoCancelColor = Theme.getColor(Theme.key_undo_cancelColor); + public UndoButton(@NonNull Context context, boolean text, Theme.ResourcesProvider resourcesProvider) { + super(context); + this.resourcesProvider = resourcesProvider; + + final int undoCancelColor = getThemedColor(Theme.key_undo_cancelColor); if (text) { TextView undoTextView = new TextView(context); @@ -1171,6 +1190,11 @@ public final class Bulletin { this.delayedAction = delayedAction; return this; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } //endregion } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/BulletinFactory.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/BulletinFactory.java index d07641a57..3acef80f0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/BulletinFactory.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/BulletinFactory.java @@ -11,6 +11,7 @@ import org.telegram.messenger.NotificationsController; import org.telegram.messenger.R; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.BaseFragment; +import org.telegram.ui.ActionBar.Theme; public final class BulletinFactory { @@ -18,8 +19,8 @@ public final class BulletinFactory { return new BulletinFactory(fragment); } - public static BulletinFactory of(FrameLayout containerLayout) { - return new BulletinFactory(containerLayout); + public static BulletinFactory of(FrameLayout containerLayout, Theme.ResourcesProvider resourcesProvider) { + return new BulletinFactory(containerLayout, resourcesProvider); } public static boolean canShowBulletin(BaseFragment fragment) { @@ -101,19 +102,22 @@ public final class BulletinFactory { private final BaseFragment fragment; private final FrameLayout containerLayout; + private final Theme.ResourcesProvider resourcesProvider; private BulletinFactory(BaseFragment fragment) { this.fragment = fragment; this.containerLayout = null; + this.resourcesProvider = fragment == null ? null : fragment.getResourceProvider(); } - private BulletinFactory(FrameLayout containerLayout) { + private BulletinFactory(FrameLayout containerLayout, Theme.ResourcesProvider resourcesProvider) { this.containerLayout = containerLayout; this.fragment = null; + this.resourcesProvider = resourcesProvider; } public Bulletin createSimpleBulletin(int iconRawId, String text) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext(), resourcesProvider); layout.setAnimation(iconRawId, 36, 36); layout.textView.setText(text); layout.textView.setSingleLine(false); @@ -123,16 +127,21 @@ public final class BulletinFactory { @CheckResult public Bulletin createDownloadBulletin(FileType fileType) { - return createDownloadBulletin(fileType, 1); + return createDownloadBulletin(fileType, resourcesProvider); } @CheckResult - public Bulletin createDownloadBulletin(FileType fileType, int filesAmount) { - return createDownloadBulletin(fileType, filesAmount, 0, 0); + public Bulletin createDownloadBulletin(FileType fileType, Theme.ResourcesProvider resourcesProvider) { + return createDownloadBulletin(fileType, 1, resourcesProvider); } - public Bulletin createReportSent() { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext()); + @CheckResult + public Bulletin createDownloadBulletin(FileType fileType, int filesAmount, Theme.ResourcesProvider resourcesProvider) { + return createDownloadBulletin(fileType, filesAmount, 0, 0, resourcesProvider); + } + + public Bulletin createReportSent(Theme.ResourcesProvider resourcesProvider) { + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext(), resourcesProvider); layout.setAnimation(R.raw.chats_infotip); layout.textView.setText(LocaleController.getString("ReportChatSent", R.string.ReportChatSent)); return create(layout, Bulletin.DURATION_SHORT); @@ -140,11 +149,16 @@ public final class BulletinFactory { @CheckResult public Bulletin createDownloadBulletin(FileType fileType, int filesAmount, int backgroundColor, int textColor) { + return createDownloadBulletin(fileType, filesAmount, backgroundColor, textColor, null); + } + + @CheckResult + public Bulletin createDownloadBulletin(FileType fileType, int filesAmount, int backgroundColor, int textColor, Theme.ResourcesProvider resourcesProvider) { final Bulletin.LottieLayout layout; if (backgroundColor != 0 && textColor != 0) { - layout = new Bulletin.LottieLayout(getContext(), backgroundColor, textColor); + layout = new Bulletin.LottieLayout(getContext(), resourcesProvider, backgroundColor, textColor); } else { - layout = new Bulletin.LottieLayout(getContext()); + layout = new Bulletin.LottieLayout(getContext(), resourcesProvider); } layout.setAnimation(fileType.icon.resId, fileType.icon.layers); layout.textView.setText(fileType.getText(filesAmount)); @@ -154,9 +168,12 @@ public final class BulletinFactory { return create(layout, Bulletin.DURATION_SHORT); } + public Bulletin createErrorBulletin(CharSequence errorMessage) { + return createErrorBulletin(errorMessage, null); + } - public Bulletin createErrorBulletin(String errorMessage) { - Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext()); + public Bulletin createErrorBulletin(CharSequence errorMessage, Theme.ResourcesProvider resourcesProvider) { + Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext(), resourcesProvider); layout.setAnimation(R.raw.chats_infotip); layout.textView.setText(errorMessage); layout.textView.setSingleLine(false); @@ -166,27 +183,27 @@ public final class BulletinFactory { @CheckResult public Bulletin createCopyLinkBulletin() { - return createCopyLinkBulletin(false); + return createCopyLinkBulletin(false, resourcesProvider); } @CheckResult public Bulletin createCopyBulletin(String message) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext(), null); layout.setAnimation(R.raw.copy, 36, 36, "NULL ROTATION", "Back", "Front"); layout.textView.setText(message); return create(layout, Bulletin.DURATION_SHORT); } @CheckResult - public Bulletin createCopyLinkBulletin(boolean isPrivate) { + public Bulletin createCopyLinkBulletin(boolean isPrivate, Theme.ResourcesProvider resourcesProvider) { if (isPrivate) { - final Bulletin.TwoLineLottieLayout layout = new Bulletin.TwoLineLottieLayout(getContext()); + final Bulletin.TwoLineLottieLayout layout = new Bulletin.TwoLineLottieLayout(getContext(), resourcesProvider); layout.setAnimation(R.raw.voip_invite, 36, 36, "Wibe", "Circle"); layout.titleTextView.setText(LocaleController.getString("LinkCopied", R.string.LinkCopied)); layout.subtitleTextView.setText(LocaleController.getString("LinkCopiedPrivateInfo", R.string.LinkCopiedPrivateInfo)); return create(layout, Bulletin.DURATION_LONG); } else { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(getContext(), resourcesProvider); layout.setAnimation(R.raw.voip_invite, 36, 36, "Wibe", "Circle"); layout.textView.setText(LocaleController.getString("LinkCopied", R.string.LinkCopied)); return create(layout, Bulletin.DURATION_SHORT); @@ -209,7 +226,12 @@ public final class BulletinFactory { @CheckResult public static Bulletin createMuteBulletin(BaseFragment fragment, int setting) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + return createMuteBulletin(fragment, setting, null); + } + + @CheckResult + public static Bulletin createMuteBulletin(BaseFragment fragment, int setting, Theme.ResourcesProvider resourcesProvider) { + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), resourcesProvider); final String text; final boolean mute; @@ -250,20 +272,20 @@ public final class BulletinFactory { } @CheckResult - public static Bulletin createMuteBulletin(BaseFragment fragment, boolean muted) { - return createMuteBulletin(fragment, muted ? NotificationsController.SETTING_MUTE_FOREVER : NotificationsController.SETTING_MUTE_UNMUTE); + public static Bulletin createMuteBulletin(BaseFragment fragment, boolean muted, Theme.ResourcesProvider resourcesProvider) { + return createMuteBulletin(fragment, muted ? NotificationsController.SETTING_MUTE_FOREVER : NotificationsController.SETTING_MUTE_UNMUTE, resourcesProvider); } @CheckResult - public static Bulletin createDeleteMessagesBulletin(BaseFragment fragment, int count) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + public static Bulletin createDeleteMessagesBulletin(BaseFragment fragment, int count, Theme.ResourcesProvider resourcesProvider) { + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), resourcesProvider); layout.setAnimation(R.raw.ic_delete, "Envelope", "Cover", "Bucket"); layout.textView.setText(LocaleController.formatPluralString("MessagesDeletedHint", count)); return Bulletin.make(fragment, layout, Bulletin.DURATION_SHORT); } @CheckResult - public static Bulletin createUnpinAllMessagesBulletin(BaseFragment fragment, int count, boolean hide, Runnable undoAction, Runnable delayedAction) { + public static Bulletin createUnpinAllMessagesBulletin(BaseFragment fragment, int count, boolean hide, Runnable undoAction, Runnable delayedAction, Theme.ResourcesProvider resourcesProvider) { if (fragment.getParentActivity() == null) { if (delayedAction != null) { delayedAction.run(); @@ -272,34 +294,34 @@ public final class BulletinFactory { } Bulletin.ButtonLayout buttonLayout; if (hide) { - final Bulletin.TwoLineLottieLayout layout = new Bulletin.TwoLineLottieLayout(fragment.getParentActivity()); + final Bulletin.TwoLineLottieLayout layout = new Bulletin.TwoLineLottieLayout(fragment.getParentActivity(), resourcesProvider); layout.setAnimation(R.raw.ic_unpin, 28, 28, "Pin", "Line"); layout.titleTextView.setText(LocaleController.getString("PinnedMessagesHidden", R.string.PinnedMessagesHidden)); layout.subtitleTextView.setText(LocaleController.getString("PinnedMessagesHiddenInfo", R.string.PinnedMessagesHiddenInfo)); buttonLayout = layout; } else { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), resourcesProvider); layout.setAnimation(R.raw.ic_unpin, 28, 28, "Pin", "Line"); layout.textView.setText(LocaleController.formatPluralString("MessagesUnpinned", count)); buttonLayout = layout; } - buttonLayout.setButton(new Bulletin.UndoButton(fragment.getParentActivity(), true).setUndoAction(undoAction).setDelayedAction(delayedAction)); + buttonLayout.setButton(new Bulletin.UndoButton(fragment.getParentActivity(), true, resourcesProvider).setUndoAction(undoAction).setDelayedAction(delayedAction)); return Bulletin.make(fragment, buttonLayout, 5000); } @CheckResult - public static Bulletin createSaveToGalleryBulletin(BaseFragment fragment, boolean video) { - return of(fragment).createDownloadBulletin(video ? FileType.VIDEO : FileType.PHOTO); + public static Bulletin createSaveToGalleryBulletin(BaseFragment fragment, boolean video, Theme.ResourcesProvider resourcesProvider) { + return of(fragment).createDownloadBulletin(video ? FileType.VIDEO : FileType.PHOTO, resourcesProvider); } @CheckResult public static Bulletin createSaveToGalleryBulletin(FrameLayout containerLayout, boolean video, int backgroundColor, int textColor) { - return of(containerLayout).createDownloadBulletin(video ? FileType.VIDEO : FileType.PHOTO, 1, backgroundColor, textColor); + return of(containerLayout, null).createDownloadBulletin(video ? FileType.VIDEO : FileType.PHOTO, 1, backgroundColor, textColor); } @CheckResult public static Bulletin createPromoteToAdminBulletin(BaseFragment fragment, String userFirstName) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), null); layout.setAnimation(R.raw.ic_admin, "Shield"); layout.textView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("UserSetAsAdminHint", R.string.UserSetAsAdminHint, userFirstName))); return Bulletin.make(fragment, layout, Bulletin.DURATION_SHORT); @@ -307,7 +329,7 @@ public final class BulletinFactory { @CheckResult public static Bulletin createRemoveFromChatBulletin(BaseFragment fragment, TLRPC.User user, String chatName) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), null); layout.setAnimation(R.raw.ic_ban, "Hand"); String name; if (user.deleted) { @@ -321,7 +343,7 @@ public final class BulletinFactory { @CheckResult public static Bulletin createBanBulletin(BaseFragment fragment, boolean banned) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), null); final String text; if (banned) { layout.setAnimation(R.raw.ic_ban, "Hand"); @@ -341,26 +363,26 @@ public final class BulletinFactory { @CheckResult public static Bulletin createCopyLinkBulletin(FrameLayout containerView) { - return of(containerView).createCopyLinkBulletin(); + return of(containerView, null).createCopyLinkBulletin(); } @CheckResult - public static Bulletin createPinMessageBulletin(BaseFragment fragment) { - return createPinMessageBulletin(fragment, true, null, null); + public static Bulletin createPinMessageBulletin(BaseFragment fragment, Theme.ResourcesProvider resourcesProvider) { + return createPinMessageBulletin(fragment, true, null, null, resourcesProvider); } @CheckResult - public static Bulletin createUnpinMessageBulletin(BaseFragment fragment, Runnable undoAction, Runnable delayedAction) { - return createPinMessageBulletin(fragment, false, undoAction, delayedAction); + public static Bulletin createUnpinMessageBulletin(BaseFragment fragment, Runnable undoAction, Runnable delayedAction, Theme.ResourcesProvider resourcesProvider) { + return createPinMessageBulletin(fragment, false, undoAction, delayedAction, resourcesProvider); } @CheckResult - private static Bulletin createPinMessageBulletin(BaseFragment fragment, boolean pinned, Runnable undoAction, Runnable delayedAction) { - final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity()); + private static Bulletin createPinMessageBulletin(BaseFragment fragment, boolean pinned, Runnable undoAction, Runnable delayedAction, Theme.ResourcesProvider resourcesProvider) { + final Bulletin.LottieLayout layout = new Bulletin.LottieLayout(fragment.getParentActivity(), resourcesProvider); layout.setAnimation(pinned ? R.raw.ic_pin : R.raw.ic_unpin, 28, 28, "Pin", "Line"); layout.textView.setText(LocaleController.getString(pinned ? "MessagePinnedHint" : "MessageUnpinnedHint", pinned ? R.string.MessagePinnedHint : R.string.MessageUnpinnedHint)); if (!pinned) { - layout.setButton(new Bulletin.UndoButton(fragment.getParentActivity(), true).setUndoAction(undoAction).setDelayedAction(delayedAction)); + layout.setButton(new Bulletin.UndoButton(fragment.getParentActivity(), true, resourcesProvider).setUndoAction(undoAction).setDelayedAction(delayedAction)); } return Bulletin.make(fragment, layout, pinned ? Bulletin.DURATION_SHORT : 5000); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java index 6a846bbc1..8a0d7887c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatActivityEnterView.java @@ -53,7 +53,6 @@ import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ImageSpan; import android.util.Property; -import android.util.SparseArray; import android.util.TypedValue; import android.view.ActionMode; import android.view.Gravity; @@ -81,6 +80,7 @@ import android.widget.Toast; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.collection.LongSparseArray; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import androidx.core.os.BuildCompat; @@ -97,6 +97,7 @@ import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; @@ -296,7 +297,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); - seekBarWaveform.setColors(Theme.getColor(Theme.key_chat_recordedVoiceProgress), Theme.getColor(Theme.key_chat_recordedVoiceProgressInner), Theme.getColor(Theme.key_chat_recordedVoiceProgress)); + seekBarWaveform.setColors(getThemedColor(Theme.key_chat_recordedVoiceProgress), getThemedColor(Theme.key_chat_recordedVoiceProgressInner), getThemedColor(Theme.key_chat_recordedVoiceProgress)); seekBarWaveform.draw(canvas, this); } } @@ -671,8 +672,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } public void updateColors() { - int dotColor = Theme.getColor(Theme.key_chat_recordedVoiceDot); - int background = Theme.getColor(Theme.key_chat_messagePanelBackground); + int dotColor = getThemedColor(Theme.key_chat_recordedVoiceDot); + int background = getThemedColor(Theme.key_chat_messagePanelBackground); redDotPaint.setColor(dotColor); drawable.beginApplyLayerColors(); drawable.setLayerColor("Cup Red.**", dotColor); @@ -682,7 +683,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe drawable.setLayerColor("Line 3.**", background); drawable.commitApplyLayerColors(); if (playPauseDrawable != null) { - playPauseDrawable.setColor(Theme.getColor(Theme.key_chat_recordedVoicePlayPause)); + playPauseDrawable.setColor(getThemedColor(Theme.key_chat_recordedVoicePlayPause)); } } @@ -756,6 +757,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe private android.graphics.Rect rect = new Rect(); private Drawable lockShadowDrawable; + private final Theme.ResourcesProvider resourcesProvider; private Runnable runEmojiPanelAnimation = new Runnable() { @Override @@ -836,19 +838,19 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe public RecordCircle(Context context) { super(context); micDrawable = getResources().getDrawable(R.drawable.input_mic_pressed).mutate(); - micDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); + micDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); cameraDrawable = getResources().getDrawable(R.drawable.input_video_pressed).mutate(); - cameraDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); + cameraDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); sendDrawable = getResources().getDrawable(R.drawable.attach_send).mutate(); - sendDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); + sendDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); micOutline = getResources().getDrawable(R.drawable.input_mic).mutate(); - micOutline.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + micOutline.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); cameraOutline = getResources().getDrawable(R.drawable.input_video).mutate(); - cameraOutline.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + cameraOutline.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); virtualViewHelper = new VirtualViewHelper(this); ViewCompat.setAccessibilityDelegate(this, virtualViewHelper); @@ -867,8 +869,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe lockOutlinePaint.setStrokeWidth(AndroidUtilities.dpf2(1.7f)); lockShadowDrawable = getResources().getDrawable(R.drawable.lock_round_shadow); - lockShadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoiceLockShadow), PorterDuff.Mode.MULTIPLY)); - tooltipBackground = Theme.createRoundRectDrawable(AndroidUtilities.dp(5), Theme.getColor(Theme.key_chat_gifSaveHintBackground)); + lockShadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoiceLockShadow), PorterDuff.Mode.MULTIPLY)); + tooltipBackground = Theme.createRoundRectDrawable(AndroidUtilities.dp(5), getThemedColor(Theme.key_chat_gifSaveHintBackground)); tooltipPaint.setTextSize(AndroidUtilities.dp(14)); tooltipBackgroundArrow = ContextCompat.getDrawable(context, R.drawable.tooltip_arrow); @@ -1120,9 +1122,9 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } if (progressToSeekbarStep3 > 0) { - paint.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground), Theme.getColor(Theme.key_chat_recordedVoiceBackground), progressToSeekbarStep3)); + paint.setColor(ColorUtils.blendARGB(getThemedColor(Theme.key_chat_messagePanelVoiceBackground), getThemedColor(Theme.key_chat_recordedVoiceBackground), progressToSeekbarStep3)); } else { - paint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground)); + paint.setColor(getThemedColor(Theme.key_chat_messagePanelVoiceBackground)); } Drawable drawable; @@ -1521,16 +1523,16 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } public void updateColors() { - paint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground)); - tinyWaveDrawable.paint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground), (int) (255 * WaveDrawable.CIRCLE_ALPHA_2))); - bigWaveDrawable.paint.setColor(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground), (int) (255 * WaveDrawable.CIRCLE_ALPHA_1))); - tooltipPaint.setColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); - tooltipBackground = Theme.createRoundRectDrawable(AndroidUtilities.dp(5), Theme.getColor(Theme.key_chat_gifSaveHintBackground)); - tooltipBackgroundArrow.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); + paint.setColor(getThemedColor(Theme.key_chat_messagePanelVoiceBackground)); + tinyWaveDrawable.paint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messagePanelVoiceBackground), (int) (255 * WaveDrawable.CIRCLE_ALPHA_2))); + bigWaveDrawable.paint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_messagePanelVoiceBackground), (int) (255 * WaveDrawable.CIRCLE_ALPHA_1))); + tooltipPaint.setColor(getThemedColor(Theme.key_chat_gifSaveHintText)); + tooltipBackground = Theme.createRoundRectDrawable(AndroidUtilities.dp(5), getThemedColor(Theme.key_chat_gifSaveHintBackground)); + tooltipBackgroundArrow.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); - lockBackgroundPaint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceLockBackground)); - lockPaint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceLock)); - lockOutlinePaint.setColor(Theme.getColor(Theme.key_chat_messagePanelVoiceLock)); + lockBackgroundPaint.setColor(getThemedColor(Theme.key_chat_messagePanelVoiceLockBackground)); + lockPaint.setColor(getThemedColor(Theme.key_chat_messagePanelVoiceLock)); + lockOutlinePaint.setColor(getThemedColor(Theme.key_chat_messagePanelVoiceLock)); paintAlpha = paint.getAlpha(); } @@ -1639,13 +1641,18 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } } - @SuppressLint("ClickableViewAccessibility") public ChatActivityEnterView(Activity context, SizeNotifierFrameLayout parent, ChatActivity fragment, final boolean isChat) { + this(context, parent, fragment, isChat, null); + } + + @SuppressLint("ClickableViewAccessibility") + public ChatActivityEnterView(Activity context, SizeNotifierFrameLayout parent, ChatActivity fragment, final boolean isChat, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; smoothKeyboard = isChat && SharedConfig.smoothKeyboard && !AndroidUtilities.isInMultiwindow && (fragment == null || !fragment.isInBubbleMode()); dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending)); + dotPaint.setColor(getThemedColor(Theme.key_chat_emojiPanelNewTrending)); setFocusable(true); setFocusableInTouchMode(true); setWillNotDraw(false); @@ -1731,10 +1738,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } } }; - emojiButton[a].setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + emojiButton[a].setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); emojiButton[a].setScaleType(ImageView.ScaleType.CENTER_INSIDE); if (Build.VERSION.SDK_INT >= 21) { - emojiButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + emojiButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } frameLayout.addView(emojiButton[a], LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 3, 0, 0, 0)); emojiButton[a].setOnClickListener(view -> { @@ -1780,12 +1787,12 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe captionLimitView = new NumberTextView(context); captionLimitView.setVisibility(View.GONE); captionLimitView.setTextSize(15); - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); captionLimitView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); captionLimitView.setCenterAlign(true); addView(captionLimitView, LayoutHelper.createFrame(48, 20, Gravity.BOTTOM | Gravity.RIGHT, 3, 0, 0, 48)); - messageEditText = new EditTextCaption(context) { + messageEditText = new EditTextCaption(context, resourcesProvider) { private void send(InputContentInfoCompat inputContentInfo, boolean notify, int scheduleDate) { ClipDescription description = inputContentInfo.getDescription(); @@ -1815,7 +1822,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } if (inputContentInfo.getDescription().hasMimeType("image/gif") || SendMessagesHelper.shouldSendWebPAsSticker(null, inputContentInfo.getContentUri())) { if (isInScheduleMode()) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> send(inputContentInfo, notify, scheduleDate)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> send(inputContentInfo, notify, scheduleDate), resourcesProvider); } else { send(inputContentInfo, true, 0); } @@ -1938,7 +1945,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe ArrayList entries = new ArrayList<>(); entries.add(photoEntry); AndroidUtilities.runOnUIThread(() -> { - PhotoViewer.getInstance().setParentActivity(parentActivity); + PhotoViewer.getInstance().setParentActivity(parentActivity, resourcesProvider); PhotoViewer.getInstance().openPhotoForSelect(entries, 0, 2, false, new PhotoViewer.EmptyPhotoViewerProvider() { boolean sending; @Override @@ -1984,6 +1991,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } }); } + + @Override + protected Theme.ResourcesProvider getResourcesProvider() { + return resourcesProvider; + } }; messageEditText.setDelegate(() -> { if (delegate != null) { @@ -2007,10 +2019,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe messageEditText.setGravity(Gravity.BOTTOM); messageEditText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12)); messageEditText.setBackgroundDrawable(null); - messageEditText.setTextColor(Theme.getColor(Theme.key_chat_messagePanelText)); - messageEditText.setHintColor(Theme.getColor(Theme.key_chat_messagePanelHint)); - messageEditText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint)); - messageEditText.setCursorColor(Theme.getColor(Theme.key_chat_messagePanelCursor)); + messageEditText.setTextColor(getThemedColor(Theme.key_chat_messagePanelText)); + messageEditText.setHintColor(getThemedColor(Theme.key_chat_messagePanelHint)); + messageEditText.setHintTextColor(getThemedColor(Theme.key_chat_messagePanelHint)); + messageEditText.setCursorColor(getThemedColor(Theme.key_chat_messagePanelCursor)); frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM, 52, 0, isChat ? 50 : 2, 0)); messageEditText.setOnKeyListener(new OnKeyListener() { @@ -2171,9 +2183,9 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe captionLimitView.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(100).start(); if (beforeLimit < 0) { doneButtonEnabledLocal = false; - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText)); } else { - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); } } else { captionLimitView.animate().alpha(0).scaleX(0.5f).scaleY(0.5f).setDuration(100).setListener(new AnimatorListenerAdapter() { @@ -2191,7 +2203,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } doneButtonColorAnimator = ValueAnimator.ofFloat(doneButtonEnabled ? 0 : 1f, doneButtonEnabled ? 1f : 0); doneButtonColorAnimator.addUpdateListener(valueAnimator -> { - int color = Theme.getColor(Theme.key_chat_messagePanelVoicePressed); + int color = getThemedColor(Theme.key_chat_messagePanelVoicePressed); int defaultAlpha = Color.alpha(color); doneButtonEnabledProgress = (float) valueAnimator.getAnimatedValue(); doneCheckDrawable.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (defaultAlpha * (0.58f + 0.42f * doneButtonEnabledProgress))), PorterDuff.Mode.MULTIPLY)); @@ -2210,8 +2222,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (parentFragment != null) { Drawable drawable1 = context.getResources().getDrawable(R.drawable.input_calendar1).mutate(); Drawable drawable2 = context.getResources().getDrawable(R.drawable.input_calendar2).mutate(); - drawable1.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); - drawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_recordedVoiceDot), PorterDuff.Mode.MULTIPLY)); + drawable1.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + drawable2.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_recordedVoiceDot), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(drawable1, drawable2); scheduledButton = new ImageView(context); @@ -2220,7 +2232,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe scheduledButton.setContentDescription(LocaleController.getString("ScheduledMessages", R.string.ScheduledMessages)); scheduledButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { - scheduledButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + scheduledButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } frameLayout.addView(scheduledButton, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.RIGHT)); scheduledButton.setOnClickListener(v -> { @@ -2276,7 +2288,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe SendMessagesHelper.getInstance(currentAccount).sendMessage(command, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, notify, scheduleDate, null); setFieldText(""); botCommandsMenuContainer.dismiss(); - }); + }, resourcesProvider); } else { if (fragment != null && fragment.checkSlowMode(view)) { return; @@ -2308,11 +2320,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe botButton = new ImageView(context); botButton.setImageDrawable(botButtonDrawable = new ReplaceableIconDrawable(context)); - botButtonDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + botButtonDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); botButtonDrawable.setIcon(R.drawable.input_bot2, false); botButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { - botButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + botButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } botButton.setVisibility(GONE); attachLayout.addView(botButton, LayoutHelper.createLinear(48, 48)); @@ -2349,10 +2361,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe notifyButton.setImageDrawable(notifySilentDrawable); notifySilentDrawable.setCrossOut(silent, false); notifyButton.setContentDescription(silent ? LocaleController.getString("AccDescrChanSilentOn", R.string.AccDescrChanSilentOn) : LocaleController.getString("AccDescrChanSilentOff", R.string.AccDescrChanSilentOff)); - notifyButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + notifyButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); notifyButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { - notifyButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + notifyButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } notifyButton.setVisibility(canWriteToChannel && (delegate == null || !delegate.hasScheduledMessages()) ? VISIBLE : GONE); attachLayout.addView(notifyButton, LayoutHelper.createLinear(48, 48)); @@ -2384,11 +2396,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe }); attachButton = new ImageView(context); - attachButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + attachButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); attachButton.setImageResource(R.drawable.input_attach); attachButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { - attachButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + attachButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } attachLayout.addView(attachButton, LayoutHelper.createLinear(48, 48)); attachButton.setOnClickListener(v -> { @@ -2415,7 +2427,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe recordDeleteImageView.setContentDescription(LocaleController.getString("Delete", R.string.Delete)); if (Build.VERSION.SDK_INT >= 21) { - recordDeleteImageView.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + recordDeleteImageView.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } recordedAudioPanel.addView(recordDeleteImageView, LayoutHelper.createFrame(48, 48)); recordDeleteImageView.setOnClickListener(v -> { @@ -2439,7 +2451,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe }); videoTimelineView = new VideoTimelineView(context); - videoTimelineView.setColor(Theme.getColor(Theme.key_chat_messagePanelVideoFrame)); + videoTimelineView.setColor(getThemedColor(Theme.key_chat_messagePanelVideoFrame)); videoTimelineView.setRoundFrames(true); videoTimelineView.setDelegate(new VideoTimelineView.VideoTimelineViewDelegate() { @Override @@ -2476,7 +2488,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe sizeNotifierLayout.addView(videoTimeHintView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM, 0, 0, 0, 52)); recordedAudioBackground = new View(context); - recordedAudioBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(Theme.key_chat_recordedVoiceBackground))); + recordedAudioBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(Theme.key_chat_recordedVoiceBackground))); recordedAudioPanel.addView(recordedAudioBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL | Gravity.LEFT, 48, 0, 0, 0)); recordedAudioSeekBar = new SeekBarWaveformView(context); @@ -2509,7 +2521,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe }); recordedAudioTimeTextView = new TextView(context); - recordedAudioTimeTextView.setTextColor(Theme.getColor(Theme.key_chat_messagePanelVoiceDuration)); + recordedAudioTimeTextView.setTextColor(getThemedColor(Theme.key_chat_messagePanelVoiceDuration)); recordedAudioTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); waveFormTimerLayout.addView(recordedAudioSeekBar, LayoutHelper.createLinear(0, 32, 1f, Gravity.CENTER_VERTICAL, 0, 0, 4, 0)); waveFormTimerLayout.addView(recordedAudioTimeTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, 0f, Gravity.CENTER_VERTICAL)); @@ -2559,7 +2571,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe delegate.needStartRecordVideo(1, true, 0); } else { if (recordingAudioVideo && isInScheduleMode()) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> MediaController.getInstance().stopRecording(1, notify, scheduleDate), () -> MediaController.getInstance().stopRecording(0, false, 0)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> MediaController.getInstance().stopRecording(1, notify, scheduleDate), () -> MediaController.getInstance().stopRecording(0, false, 0), resourcesProvider); } MediaController.getInstance().stopRecording(isInScheduleMode() ? 3 : 1, true, 0); delegate.needStartRecordAudio(0); @@ -2639,7 +2651,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe delegate.needStartRecordVideo(1, true, 0); } else { if (recordingAudioVideo && isInScheduleMode()) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> MediaController.getInstance().stopRecording(1, notify, scheduleDate), () -> MediaController.getInstance().stopRecording(0, false, 0)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (notify, scheduleDate) -> MediaController.getInstance().stopRecording(1, notify, scheduleDate), () -> MediaController.getInstance().stopRecording(0, false, 0), resourcesProvider); } delegate.needStartRecordAudio(0); MediaController.getInstance().stopRecording(isInScheduleMode() ? 3 : 1, true, 0); @@ -2704,7 +2716,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe audioSendButton = new ImageView(context); audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); - audioSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + audioSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); audioSendButton.setImageResource(R.drawable.input_mic); audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0); audioSendButton.setContentDescription(LocaleController.getString("AccDescrVoiceMessage", R.string.AccDescrVoiceMessage)); @@ -2715,7 +2727,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (isChat) { videoSendButton = new ImageView(context); videoSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); - videoSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + videoSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); videoSendButton.setImageResource(R.drawable.input_video); videoSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0); videoSendButton.setContentDescription(LocaleController.getString("AccDescrVideoMessage", R.string.AccDescrVideoMessage)); @@ -2733,13 +2745,13 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe cancelBotButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); cancelBotButton.setImageDrawable(progressDrawable = new CloseProgressDrawable2()); cancelBotButton.setContentDescription(LocaleController.getString("Cancel", R.string.Cancel)); - progressDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelCancelInlineBot), PorterDuff.Mode.MULTIPLY)); + progressDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelCancelInlineBot), PorterDuff.Mode.MULTIPLY)); cancelBotButton.setSoundEffectsEnabled(false); cancelBotButton.setScaleX(0.1f); cancelBotButton.setScaleY(0.1f); cancelBotButton.setAlpha(0.0f); if (Build.VERSION.SDK_INT >= 21) { - cancelBotButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + cancelBotButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } sendButtonContainer.addView(cancelBotButton, LayoutHelper.createFrame(48, 48)); cancelBotButton.setOnClickListener(view -> { @@ -2784,10 +2796,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe boolean showingPopup; int colorType; if (showingPopup = (sendPopupWindow != null && sendPopupWindow.isShowing())) { - color = Theme.getColor(Theme.key_chat_messagePanelVoicePressed); + color = getThemedColor(Theme.key_chat_messagePanelVoicePressed); colorType = 1; } else { - color = Theme.getColor(Theme.key_chat_messagePanelSend); + color = getThemedColor(Theme.key_chat_messagePanelSend); colorType = 2; } if (color != drawableColor) { @@ -2804,10 +2816,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } prevColorType = colorType; drawableColor = color; - sendButtonDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelSend), PorterDuff.Mode.MULTIPLY)); - int c = Theme.getColor(Theme.key_chat_messagePanelIcons); + sendButtonDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelSend), PorterDuff.Mode.MULTIPLY)); + int c = getThemedColor(Theme.key_chat_messagePanelIcons); inactinveSendButtonDrawable.setColorFilter(new PorterDuffColorFilter(Color.argb(0xb4, Color.red(c), Color.green(c), Color.blue(c)), PorterDuff.Mode.MULTIPLY)); - sendButtonInverseDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); + sendButtonInverseDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); } if (animationProgress < 1.0f) { long newTime = SystemClock.elapsedRealtime(); @@ -2829,7 +2841,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } } if (showingPopup || animationProgress != 1.0f) { - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_chat_messagePanelSend)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(Theme.key_chat_messagePanelSend)); int rad = AndroidUtilities.dp(20); if (showingPopup) { sendButtonInverseDrawable.setAlpha(255); @@ -2868,7 +2880,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } }; sendButton.setVisibility(INVISIBLE); - int color = Theme.getColor(Theme.key_chat_messagePanelSend); + int color = getThemedColor(Theme.key_chat_messagePanelSend); sendButton.setContentDescription(LocaleController.getString("Send", R.string.Send)); sendButton.setSoundEffectsEnabled(false); sendButton.setScaleX(0.1f); @@ -2895,7 +2907,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe slowModeButton.setAlpha(0.0f); slowModeButton.setPadding(0, 0, AndroidUtilities.dp(13), 0); slowModeButton.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL); - slowModeButton.setTextColor(Theme.getColor(Theme.key_chat_messagePanelIcons)); + slowModeButton.setTextColor(getThemedColor(Theme.key_chat_messagePanelIcons)); sendButtonContainer.addView(slowModeButton, LayoutHelper.createFrame(64, 48, Gravity.RIGHT | Gravity.TOP)); slowModeButton.setOnClickListener(v -> { if (delegate != null) { @@ -2919,13 +2931,13 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } }; expandStickersButton.setScaleType(ImageView.ScaleType.CENTER); - expandStickersButton.setImageDrawable(stickersArrow = new AnimatedArrowDrawable(Theme.getColor(Theme.key_chat_messagePanelIcons), false)); + expandStickersButton.setImageDrawable(stickersArrow = new AnimatedArrowDrawable(getThemedColor(Theme.key_chat_messagePanelIcons), false)); expandStickersButton.setVisibility(GONE); expandStickersButton.setScaleX(0.1f); expandStickersButton.setScaleY(0.1f); expandStickersButton.setAlpha(0.0f); if (Build.VERSION.SDK_INT >= 21) { - expandStickersButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + expandStickersButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } sendButtonContainer.addView(expandStickersButton, LayoutHelper.createFrame(48, 48)); expandStickersButton.setOnClickListener(v -> { @@ -2959,9 +2971,9 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe textFieldContainer.addView(doneButtonContainer, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.RIGHT)); doneButtonContainer.setOnClickListener(view -> doneEditingMessage()); - Drawable doneCircleDrawable = Theme.createCircleDrawable(AndroidUtilities.dp(16), Theme.getColor(Theme.key_chat_messagePanelSend)); + Drawable doneCircleDrawable = Theme.createCircleDrawable(AndroidUtilities.dp(16), getThemedColor(Theme.key_chat_messagePanelSend)); doneCheckDrawable = context.getResources().getDrawable(R.drawable.input_done).mutate(); - doneCheckDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); + doneCheckDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelVoicePressed), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(doneCircleDrawable, doneCheckDrawable, 0, AndroidUtilities.dp(1)); combinedDrawable.setCustomSize(AndroidUtilities.dp(32), AndroidUtilities.dp(32)); @@ -3048,6 +3060,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe return result; } + Paint backgroundPaint = new Paint(); @Override protected void onDraw(Canvas canvas) { int top = animatedTop; @@ -3058,7 +3071,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe Theme.chat_composeShadowDrawable.setBounds(0, top, getMeasuredWidth(), bottom); Theme.chat_composeShadowDrawable.draw(canvas); - canvas.drawRect(0, bottom, getWidth(), getHeight(), Theme.chat_composeBackgroundPaint); + backgroundPaint.setColor(getThemedColor(Theme.key_chat_messagePanelBackground)); + canvas.drawRect(0, bottom, getWidth(), getHeight(), backgroundPaint); } @Override @@ -3074,7 +3088,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe TLRPC.User user = parentFragment.getCurrentUser(); if (sendPopupLayout == null) { - sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity); + sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity, resourcesProvider); sendPopupLayout.setAnimationEnabled(false); sendPopupLayout.setOnTouchListener(new OnTouchListener() { @@ -3105,7 +3119,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe continue; } int num = a; - ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), a == 0, a == 1); + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), a == 0, a == 1, resourcesProvider); if (num == 0) { if (UserObject.isUserSelf(user)) { cell.setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule); @@ -3122,13 +3136,13 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe sendPopupWindow.dismiss(); } if (num == 0) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), this::sendMessageInternal); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), this::sendMessageInternal, resourcesProvider); } else { sendMessageInternal(false, 0); } }); } - sendPopupLayout.setupRadialSelectors(Theme.getColor(Theme.key_dialogButtonSelector)); + sendPopupLayout.setupRadialSelectors(getThemedColor(Theme.key_dialogButtonSelector)); sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) { @Override @@ -3184,8 +3198,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (animated) { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); boolean isChannel = false; - if ((int) dialog_id < 0) { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialog_id)) { + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialog_id); isChannel = ChatObject.isChannel(chat) && !chat.megagroup; } preferences.edit().putBoolean(isChannel ? "currentModeVideoChannel" : "currentModeVideo", visible).commit(); @@ -3786,17 +3800,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe setRecordVideoButtonVisible(false, false); return; } - int lower_id = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); - if (lower_id == 0 && high_id != 0) { - TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(high_id); - hasRecordVideo = true; - } else { - hasRecordVideo = true; - } + hasRecordVideo = true; boolean isChannel = false; - if ((int) dialog_id < 0) { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialog_id)) { + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialog_id); isChannel = ChatObject.isChannel(chat) && !chat.megagroup; if (isChannel && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages)) { hasRecordVideo = false; @@ -3835,8 +3842,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } else { boolean isChannel = false; boolean anonymously = false; - if ((int) dialog_id < 0) { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialog_id)) { + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialog_id); isChannel = ChatObject.isChannel(chat) && !chat.megagroup; anonymously = ChatObject.shouldSendAnonymously(chat); } @@ -4084,7 +4091,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe private void sendMessage() { if (isInScheduleMode()) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), this::sendMessageInternal); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), this::sendMessageInternal, resourcesProvider); } else { sendMessageInternal(true, 0); } @@ -4134,10 +4141,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe TLRPC.Chat chat = parentFragment.getCurrentChat(); if (chat != null && chat.slowmode_enabled && !ChatObject.hasAdminRights(chat)) { if (message.length() > accountInstance.getMessagesController().maxMessageLength) { - AlertsCreator.showSimpleAlert(parentFragment, LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendErrorTooLong", R.string.SlowmodeSendErrorTooLong)); + AlertsCreator.showSimpleAlert(parentFragment, LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendErrorTooLong", R.string.SlowmodeSendErrorTooLong), resourcesProvider); return; } else if (forceShowSendButton && message.length() > 0) { - AlertsCreator.showSimpleAlert(parentFragment, LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendError", R.string.SlowmodeSendError)); + AlertsCreator.showSimpleAlert(parentFragment, LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendError", R.string.SlowmodeSendError), resourcesProvider); return; } } @@ -4448,9 +4455,9 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe boolean showSendButton = caption == null && (cancelBotButton.getVisibility() == VISIBLE || expandStickersButton.getVisibility() == VISIBLE); int color; if (slowModeTimer == Integer.MAX_VALUE && !isInScheduleMode()) { - color = Theme.getColor(Theme.key_chat_messagePanelIcons); + color = getThemedColor(Theme.key_chat_messagePanelIcons); } else { - color = Theme.getColor(Theme.key_chat_messagePanelSend); + color = getThemedColor(Theme.key_chat_messagePanelSend); } Theme.setSelectorDrawableColor(sendButton.getBackground(), Color.argb(24, Color.red(color), Color.green(color), Color.blue(color)), true); if (audioVideoButtonContainer.getVisibility() == VISIBLE || slowModeButton.getVisibility() == VISIBLE || showBotButton || showSendButton) { @@ -5698,7 +5705,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } if (longPress) { String text = messageEditText.getText().toString(); - TLRPC.User user = messageObject != null && (int) dialog_id < 0 ? accountInstance.getMessagesController().getUser(messageObject.messageOwner.from_id.user_id) : null; + TLRPC.User user = messageObject != null && DialogObject.isChatDialog(dialog_id) ? accountInstance.getMessagesController().getUser(messageObject.messageOwner.from_id.user_id) : null; if ((botCount != 1 || username) && user != null && user.bot && !command.contains("@")) { text = String.format(Locale.US, "%s@%s", command, user.username) + " " + text.replaceFirst("^/[a-zA-Z@\\d_]{1,255}(\\s|$)", ""); } else { @@ -5721,7 +5728,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } return; } - TLRPC.User user = messageObject != null && (int) dialog_id < 0 ? accountInstance.getMessagesController().getUser(messageObject.messageOwner.from_id.user_id) : null; + TLRPC.User user = messageObject != null && DialogObject.isChatDialog(dialog_id) ? accountInstance.getMessagesController().getUser(messageObject.messageOwner.from_id.user_id) : null; if ((botCount != 1 || username) && user != null && user.bot && !command.contains("@")) { SendMessagesHelper.getInstance(currentAccount).sendMessage(String.format(Locale.US, "%s@%s", command, user.username), dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, true, 0, null); } else { @@ -5950,11 +5957,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe final View view = sendPopupLayout.getChildAt(a); if (view instanceof ActionBarMenuSubItem) { final ActionBarMenuSubItem item = (ActionBarMenuSubItem) view; - item.setColors(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon)); - item.setSelectorColor(Theme.getColor(Theme.key_dialogButtonSelector)); + item.setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon)); + item.setSelectorColor(getThemedColor(Theme.key_dialogButtonSelector)); } } - sendPopupLayout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + sendPopupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); if (sendPopupWindow != null && sendPopupWindow.isShowing()) { sendPopupLayout.invalidate(); } @@ -5969,12 +5976,12 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (captionLimitView != null && messageEditText != null) { if (codePointCount - currentLimit < 0) { - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText)); } else { - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); } } - int color = Theme.getColor(Theme.key_chat_messagePanelVoicePressed); + int color = getThemedColor(Theme.key_chat_messagePanelVoicePressed); int defaultAlpha = Color.alpha(color); doneCheckDrawable.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (defaultAlpha * (0.58f + 0.42f * doneButtonEnabledProgress))), PorterDuff.Mode.MULTIPLY)); if (botCommandsMenuContainer != null) { @@ -5983,12 +5990,15 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (botKeyboardView != null) { botKeyboardView.updateColors(); } + for (int i = 0; i < 2; ++i) { + emojiButton[i].setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + } } private void updateRecordedDeleteIconColors() { - int dotColor = Theme.getColor(Theme.key_chat_recordedVoiceDot); - int background = Theme.getColor(Theme.key_chat_messagePanelBackground); - int greyColor = Theme.getColor(Theme.key_chat_messagePanelVoiceDelete); + int dotColor = getThemedColor(Theme.key_chat_recordedVoiceDot); + int background = getThemedColor(Theme.key_chat_messagePanelBackground); + int greyColor = getThemedColor(Theme.key_chat_messagePanelVoiceDelete); recordDeleteImageView.setLayerColor("Cup Red.**", dotColor); recordDeleteImageView.setLayerColor("Box Red.**", dotColor); @@ -6132,8 +6142,8 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe public void updateScheduleButton(boolean animated) { boolean notifyVisible = false; - if ((int) dialog_id < 0) { - TLRPC.Chat currentChat = accountInstance.getMessagesController().getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialog_id)) { + TLRPC.Chat currentChat = accountInstance.getMessagesController().getChat(-dialog_id); silent = MessagesController.getNotificationsSettings(currentAccount).getBoolean("silent_" + dialog_id, false); canWriteToChannel = ChatObject.isChannel(currentChat) && (currentChat.creator || currentChat.admin_rights != null && currentChat.admin_rights.post_messages) && !currentChat.megagroup; if (notifyButton != null) { @@ -6214,7 +6224,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } boolean canShowBotsMenu = hasBotCommands && dialog_id > 0; // if (canShowBotsMenu && ) { -// TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-(int) dialog_id); +// TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialog_id); // canShowBotsMenu = chat == null || !chat.megagroup; // } @@ -6280,7 +6290,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe return; } if (botKeyboardView == null) { - botKeyboardView = new BotKeyboardView(parentActivity) { + botKeyboardView = new BotKeyboardView(parentActivity, resourcesProvider) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); @@ -6292,7 +6302,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe botKeyboardView.setVisibility(GONE); botKeyboardViewVisible = false; botKeyboardView.setDelegate(button -> { - MessageObject object = replyingMessageObject != null ? replyingMessageObject : ((int) dialog_id < 0 ? botButtonsMessageObject : null); + MessageObject object = replyingMessageObject != null ? replyingMessageObject : (DialogObject.isChatDialog(dialog_id) ? botButtonsMessageObject : null); boolean open = didPressedBotButton(button, object, replyingMessageObject != null ? replyingMessageObject : botButtonsMessageObject); if (replyingMessageObject != null) { openKeyboardInternal(); @@ -6350,7 +6360,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (button instanceof TLRPC.TL_keyboardButton) { SendMessagesHelper.getInstance(currentAccount).sendMessage(button.text, dialog_id, replyMessageObject, getThreadMessage(), null, false, null, null, null, true, 0, null); } else if (button instanceof TLRPC.TL_keyboardButtonUrl) { - AlertsCreator.showOpenUrlAlert(parentFragment, button.url, false, true); + AlertsCreator.showOpenUrlAlert(parentFragment, button.url, false, true, resourcesProvider); } else if (button instanceof TLRPC.TL_keyboardButtonRequestPhone) { parentFragment.shareMyContact(2, messageObject); } else if (button instanceof TLRPC.TL_keyboardButtonRequestPoll) { @@ -6378,7 +6388,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe return true; } if (button.same_peer) { - int uid = messageObject.messageOwner.from_id.user_id; + long uid = messageObject.messageOwner.from_id.user_id; if (messageObject.messageOwner.via_bot_id != 0) { uid = messageObject.messageOwner.via_bot_id; } @@ -6393,7 +6403,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe args.putInt("dialogsType", 1); DialogsActivity fragment = new DialogsActivity(args); fragment.setDelegate((fragment1, dids, message, param) -> { - int uid = messageObject.messageOwner.from_id.user_id; + long uid = messageObject.messageOwner.from_id.user_id; if (messageObject.messageOwner.via_bot_id != 0) { uid = messageObject.messageOwner.via_bot_id; } @@ -6405,13 +6415,12 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe long did = dids.get(0); MediaDataController.getInstance(currentAccount).saveDraft(did, 0, "@" + user.username + " " + button.query, null, null, true); if (did != dialog_id) { - int lower_part = (int) did; - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(did)) { Bundle args1 = new Bundle(); - if (lower_part > 0) { - args1.putInt("user_id", lower_part); + if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); } else { - args1.putInt("chat_id", -lower_part); + args1.putLong("chat_id", -did); } if (!accountInstance.getMessagesController().checkCanOpenChat(args1, fragment1)) { return; @@ -6449,7 +6458,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (emojiView != null) { return; } - emojiView = new EmojiView(allowStickers, allowGifs, getContext(), true, info, sizeNotifierLayout) { + emojiView = new EmojiView(allowStickers, allowGifs, getContext(), true, info, sizeNotifierLayout, resourcesProvider) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); @@ -6511,7 +6520,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe setStickersExpanded(false, true, false); } ChatActivityEnterView.this.onStickerSelected(sticker, query, parent, sendAnimationData, false, notify, scheduleDate); - if ((int) dialog_id == 0 && MessageObject.isGifDocument(sticker)) { + if (DialogObject.isEncryptedDialog(dialog_id) && MessageObject.isGifDocument(sticker)) { accountInstance.getMessagesController().saveGif(parent, sticker); } } @@ -6526,7 +6535,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe @Override public void onGifSelected(View view, Object gif, String query, Object parent, boolean notify, int scheduleDate) { if (isInScheduleMode() && scheduleDate == 0) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (n, s) -> onGifSelected(view, gif, query, parent, n, s)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (n, s) -> onGifSelected(view, gif, query, parent, n, s), resourcesProvider); } else { if (slowModeTimer > 0 && !isInScheduleMode()) { if (delegate != null) { @@ -6544,7 +6553,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe TLRPC.Document document = (TLRPC.Document) gif; SendMessagesHelper.getInstance(currentAccount).sendSticker(document, query, dialog_id, replyingMessageObject, getThreadMessage(), parent, null, notify, scheduleDate); MediaDataController.getInstance(currentAccount).addRecentGif(document, (int) (System.currentTimeMillis() / 1000)); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { accountInstance.getMessagesController().saveGif(parent, document); } } else if (gif instanceof TLRPC.BotInlineResult) { @@ -6552,7 +6561,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (result.document != null) { MediaDataController.getInstance(currentAccount).addRecentGif(result.document, (int) (System.currentTimeMillis() / 1000)); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { accountInstance.getMessagesController().saveGif(parent, result.document); } } @@ -6589,7 +6598,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe if (parentFragment == null || parentActivity == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ClearRecentEmoji", R.string.ClearRecentEmoji)); builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> emojiView.clearRecentEmoji()); @@ -6611,7 +6620,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe inputStickerSet.access_hash = stickerSet.access_hash; inputStickerSet.id = stickerSet.id; } - parentFragment.showDialog(new StickersAlert(parentActivity, parentFragment, inputStickerSet, null, ChatActivityEnterView.this)); + parentFragment.showDialog(new StickersAlert(parentActivity, parentFragment, inputStickerSet, null, ChatActivityEnterView.this, resourcesProvider)); } @Override @@ -6625,7 +6634,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } @Override - public void onStickersGroupClick(int chatId) { + public void onStickersGroupClick(long chatId) { if (parentFragment != null) { if (AndroidUtilities.isTablet()) { hidePopup(false); @@ -6680,7 +6689,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe @Override public void showTrendingStickersAlert(TrendingStickersLayout layout) { if (parentActivity != null && parentFragment != null) { - trendingStickersAlert = new TrendingStickersAlert(parentActivity, parentFragment, layout) { + trendingStickersAlert = new TrendingStickersAlert(parentActivity, parentFragment, layout, resourcesProvider) { @Override public void dismiss() { super.dismiss(); @@ -6787,7 +6796,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe @Override public void onStickerSelected(TLRPC.Document sticker, String query, Object parent, MessageObject.SendAnimationData sendAnimationData, boolean clearsInputField, boolean notify, int scheduleDate) { if (isInScheduleMode() && scheduleDate == 0) { - AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (n, s) -> onStickerSelected(sticker, query, parent, sendAnimationData, clearsInputField, n, s)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, parentFragment.getDialogId(), (n, s) -> onStickerSelected(sticker, query, parent, sendAnimationData, clearsInputField, n, s), resourcesProvider); } else { if (slowModeTimer > 0 && !isInScheduleMode()) { if (delegate != null) { @@ -7186,7 +7195,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe searchAnimator.cancel(); } if (!animated) { - searchToOpenProgress = showSearchingNew ? 1f : 0f; + searchToOpenProgress = showSearchingNew ? 1f : 0f; if (emojiView != null) { emojiView.searchProgressChanged(); } @@ -7990,7 +7999,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe bluePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - arrowPaint.setColor(Theme.getColor(Theme.key_chat_messagePanelIcons)); + arrowPaint.setColor(getThemedColor(Theme.key_chat_messagePanelIcons)); arrowPaint.setStyle(Paint.Style.STROKE); arrowPaint.setStrokeWidth(AndroidUtilities.dpf2(smallSize ? 1f : 1.6f)); arrowPaint.setStrokeCap(Paint.Cap.ROUND); @@ -8007,11 +8016,11 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } public void updateColors() { - grayPaint.setColor(Theme.getColor(Theme.key_chat_recordTime)); - bluePaint.setColor(Theme.getColor(Theme.key_chat_recordVoiceCancel)); + grayPaint.setColor(getThemedColor(Theme.key_chat_recordTime)); + bluePaint.setColor(getThemedColor(Theme.key_chat_recordVoiceCancel)); slideToAlpha = grayPaint.getAlpha(); cancelAlpha = bluePaint.getAlpha(); - selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_chat_recordVoiceCancel), 26)); + selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_recordVoiceCancel), 26)); selectableBackground.setCallback(this); } @@ -8069,7 +8078,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } int w = cancelLayout.getWidth() + AndroidUtilities.dp(16); - grayPaint.setColor(Theme.getColor(Theme.key_chat_recordTime)); + grayPaint.setColor(getThemedColor(Theme.key_chat_recordTime)); grayPaint.setAlpha((int) (slideToAlpha * (1f - cancelToProgress) * slideProgress)); bluePaint.setAlpha((int) (cancelAlpha * cancelToProgress)); arrowPaint.setColor(grayPaint.getColor()); @@ -8364,7 +8373,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe } public void updateColors() { - textPaint.setColor(Theme.getColor(Theme.key_chat_recordTime)); + textPaint.setColor(getThemedColor(Theme.key_chat_recordTime)); } public float getLeftProperty() { @@ -8448,7 +8457,7 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe animationParamsX.put(messageEditText, messageEditText.getX()); } - public void setBotInfo(SparseArray botInfo) { + public void setBotInfo(LongSparseArray botInfo) { if (botCommandsAdapter != null) { botCommandsAdapter.setBotInfo(botInfo); } @@ -8480,6 +8489,10 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe runEmojiPanelAnimation.run(); } + public Drawable getStickersArrowDrawable() { + return stickersArrow; + } + @Override protected void dispatchDraw(Canvas canvas) { if (emojiView == null || emojiView.getVisibility() != View.VISIBLE || emojiView.getStickersExpandOffset() == 0) { @@ -8492,4 +8505,14 @@ public class ChatActivityEnterView extends FrameLayout implements NotificationCe canvas.restore(); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java index bb8601241..ba859d373 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java @@ -151,10 +151,12 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N public static class AttachAlertLayout extends FrameLayout { + protected final Theme.ResourcesProvider resourcesProvider; protected ChatAttachAlert parentAlert; - public AttachAlertLayout(ChatAttachAlert alert, Context context) { + public AttachAlertLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; parentAlert = alert; } @@ -297,6 +299,11 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N boolean onBackPressed() { return false; } + + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } protected BaseFragment baseFragment; @@ -425,7 +432,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N textView.setMaxLines(2); textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setEllipsize(TextUtils.TruncateAt.END); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); textView.setLineSpacing(-AndroidUtilities.dp(2), 1.0f); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 62, 0, 0)); @@ -459,7 +466,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N checkedState = state; imageView.setScaleX(1.0f - 0.06f * state); imageView.setScaleY(1.0f - 0.06f * state); - textView.setTextColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_dialogTextGray2), Theme.getColor(textKey), checkedState)); + textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(textKey), checkedState)); invalidate(); } @@ -485,7 +492,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N imageView.setAnimation(drawable); backgroundKey = background; textKey = textColor; - textView.setTextColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_dialogTextGray2), Theme.getColor(textKey), checkedState)); + textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(textKey), checkedState)); } @Override @@ -496,7 +503,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N float cx = imageView.getLeft() + imageView.getMeasuredWidth() / 2; float cy = imageView.getTop() + imageView.getMeasuredWidth() / 2; - attachButtonPaint.setColor(Theme.getColor(backgroundKey)); + attachButtonPaint.setColor(getThemedColor(backgroundKey)); attachButtonPaint.setStyle(Paint.Style.STROKE); attachButtonPaint.setStrokeWidth(AndroidUtilities.dp(3) * scale); attachButtonPaint.setAlpha(Math.round(255f * checkedState)); @@ -530,7 +537,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N if (Build.VERSION.SDK_INT >= 21) { View selector = new View(context); - selector.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), 1, AndroidUtilities.dp(23))); + selector.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 1, AndroidUtilities.dp(23))); addView(selector, LayoutHelper.createFrame(46, 46, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 9, 0, 0)); } @@ -552,7 +559,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N if (user == null) { return; } - nameTextView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + nameTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); currentUser = user; nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name)); avatarDrawable.setInfo(user); @@ -566,9 +573,13 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N float currentPanTranslationY; - @SuppressLint("ClickableViewAccessibility") public ChatAttachAlert(Context context, final BaseFragment parentFragment, boolean forceDarkTheme, boolean showingFromDialog) { - super(context, false); + this(context, parentFragment, forceDarkTheme, showingFromDialog, null); + } + + @SuppressLint("ClickableViewAccessibility") + public ChatAttachAlert(Context context, final BaseFragment parentFragment, boolean forceDarkTheme, boolean showingFromDialog, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); this.forceDarkTheme = forceDarkTheme; this.showingFromDialog = showingFromDialog; drawNavigationBar = true; @@ -902,7 +913,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N shadowDrawable.setAlpha(viewAlpha); shadowDrawable.setBounds(0, top, getMeasuredWidth(), height); shadowDrawable.draw(canvas); - int backgroundColor = Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); + int backgroundColor = getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); if (actionBarType == 2) { Theme.dialogs_onlineCirclePaint.setColor(backgroundColor); Theme.dialogs_onlineCirclePaint.setAlpha(viewAlpha); @@ -934,7 +945,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N color = 0x20000000; alphaProgress = rad; } else { - color = Theme.getColor(Theme.key_sheet_scrollUp); + color = getThemedColor(Theme.key_sheet_scrollUp); alphaProgress = selectedTextView == null ? 1.0f : 1.0f - selectedTextView.getAlpha(); } int alpha = Color.alpha(color); @@ -953,7 +964,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N if (inBubbleMode) { return; } - int color1 = Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); + int color1 = getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); int finalColor = Color.argb((int) (255 * actionBar.getAlpha()), (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); Theme.dialogs_onlineCirclePaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, currentPanTranslationY, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight + currentPanTranslationY, Theme.dialogs_onlineCirclePaint); @@ -1012,7 +1023,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N containerView.setClipChildren(false); containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0); - actionBar = new ActionBar(context) { + actionBar = new ActionBar(context, resourcesProvider) { @Override public void setAlpha(float alpha) { super.setAlpha(alpha); @@ -1033,11 +1044,11 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N } } }; - actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + actionBar.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false); - actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack)); + actionBar.setItemsColor(getThemedColor(Theme.key_dialogTextBlack), false); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_dialogButtonSelector), false); + actionBar.setTitleColor(getThemedColor(Theme.key_dialogTextBlack)); actionBar.setOccupyStatusBar(false); actionBar.setAlpha(0.0f); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @@ -1054,7 +1065,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N } }); - selectedMenuItem = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_dialogTextBlack)); + selectedMenuItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider); selectedMenuItem.setLongClickEnabled(false); selectedMenuItem.setIcon(R.drawable.ic_ab_other); selectedMenuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); @@ -1064,26 +1075,26 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N selectedMenuItem.setDelegate(id -> actionBar.getActionBarMenuOnItemClick().onItemClick(id)); selectedMenuItem.setAdditionalYOffset(AndroidUtilities.dp(72)); selectedMenuItem.setTranslationX(AndroidUtilities.dp(6)); - selectedMenuItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), 6)); + selectedMenuItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 6)); selectedMenuItem.setOnClickListener(v -> selectedMenuItem.toggleSubMenu()); - doneItem = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader), true); + doneItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader), true, resourcesProvider); doneItem.setLongClickEnabled(false); doneItem.setText(LocaleController.getString("Create", R.string.Create).toUpperCase()); doneItem.setVisibility(View.INVISIBLE); doneItem.setAlpha(0.0f); doneItem.setTranslationX(-AndroidUtilities.dp(12)); - doneItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), 3)); + doneItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 3)); doneItem.setOnClickListener(v -> currentAttachLayout.onMenuItemClick(40)); - searchItem = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_dialogTextBlack)); + searchItem = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), false, resourcesProvider); searchItem.setLongClickEnabled(false); searchItem.setIcon(R.drawable.ic_ab_search); searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search)); searchItem.setVisibility(View.INVISIBLE); searchItem.setAlpha(0.0f); searchItem.setTranslationX(-AndroidUtilities.dp(42)); - searchItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), 6)); + searchItem.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_dialogButtonSelector), 6)); searchItem.setOnClickListener(v -> { if (avatarPicker != 0) { delegate.openAvatarsSearch(); @@ -1166,14 +1177,14 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N super.setTranslationY(translationY); } }; - selectedTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + selectedTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); selectedTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); selectedTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); selectedTextView.setGravity(Gravity.LEFT | Gravity.TOP); selectedTextView.setVisibility(View.INVISIBLE); selectedTextView.setAlpha(0.0f); - layouts[0] = photoLayout = new ChatAttachAlertPhotoLayout(this, context, forceDarkTheme); + layouts[0] = photoLayout = new ChatAttachAlertPhotoLayout(this, context, forceDarkTheme, resourcesProvider); currentAttachLayout = photoLayout; selectedId = 1; containerView.addView(photoLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); @@ -1186,7 +1197,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N actionBarShadow = new View(context); actionBarShadow.setAlpha(0.0f); - actionBarShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + actionBarShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); containerView.addView(actionBarShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1)); shadow = new View(context); @@ -1207,8 +1218,8 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N buttonsRecyclerView.setHorizontalScrollBarEnabled(false); buttonsRecyclerView.setItemAnimator(null); buttonsRecyclerView.setLayoutAnimation(null); - buttonsRecyclerView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); - buttonsRecyclerView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + buttonsRecyclerView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); + buttonsRecyclerView.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); containerView.addView(buttonsRecyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 84, Gravity.BOTTOM | Gravity.LEFT)); buttonsRecyclerView.setOnItemClickListener((view, position) -> { if (baseFragment.getParentActivity() == null) { @@ -1243,13 +1254,13 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N return; } if (locationLayout == null) { - layouts[5] = locationLayout = new ChatAttachAlertLocationLayout(this, getContext()); + layouts[5] = locationLayout = new ChatAttachAlertLocationLayout(this, getContext(), resourcesProvider); locationLayout.setDelegate((location, live, notify, scheduleDate) -> ((ChatActivity) baseFragment).didSelectLocation(location, live, notify, scheduleDate)); } showLayout(locationLayout); } else if (num == 9) { if (pollLayout == null) { - layouts[1] = pollLayout = new ChatAttachAlertPollLayout(this, getContext()); + layouts[1] = pollLayout = new ChatAttachAlertPollLayout(this, getContext(), resourcesProvider); pollLayout.setDelegate((poll, params, notify, scheduleDate) -> ((ChatActivity) baseFragment).sendPoll(poll, params, notify, scheduleDate)); } showLayout(pollLayout); @@ -1320,7 +1331,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N float alphaOffset = (frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(84)) * (1f - getAlpha()); shadow.setTranslationY(-(frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(84)) + captionEditTextTopOffset + currentPanTranslationY + bottomPannelTranslation + alphaOffset); - int newColor = Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); + int newColor = getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground); if (color != newColor) { color = newColor; p.setColor(color); @@ -1346,14 +1357,14 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N captionLimitView = new NumberTextView(context); captionLimitView.setVisibility(View.GONE); captionLimitView.setTextSize(15); - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); captionLimitView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); captionLimitView.setCenterAlign(true); frameLayout2.addView(captionLimitView, LayoutHelper.createFrame(56, 20, Gravity.BOTTOM | Gravity.RIGHT, 3, 0, 14, 78)); currentLimit = MessagesController.getInstance(UserConfig.selectedAccount).maxCaptionLength; - commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG) { + commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG, resourcesProvider) { private boolean shouldAnimateEditTextWithBounds; private int messageEditTextPredrawHeigth; @@ -1466,9 +1477,9 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N captionLimitView.animate().alpha(1f).scaleX(1f).scaleY(1f).setDuration(100).start(); if (beforeLimit < 0) { sendButtonEnabledLocal = false; - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText)); } else { - captionLimitView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + captionLimitView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); } } else { captionLimitView.animate().alpha(0).scaleX(0.5f).scaleY(0.5f).setDuration(100).setListener(new AnimatorListenerAdapter() { @@ -1487,7 +1498,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N sendButtonColorAnimator = ValueAnimator.ofFloat(sendButtonEnabled ? 0 : 1f, sendButtonEnabled ? 1f : 0); sendButtonColorAnimator.addUpdateListener(valueAnimator -> { sendButtonEnabledProgress = (float) valueAnimator.getAnimatedValue(); - int color = Theme.getColor(Theme.key_dialogFloatingIcon); + int color = getThemedColor(Theme.key_dialogFloatingIcon); int defaultAlpha = Color.alpha(color); writeButton.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (defaultAlpha * (0.58f + 0.42f * sendButtonEnabledProgress))), PorterDuff.Mode.MULTIPLY)); selectedCountView.invalidate(); @@ -1526,7 +1537,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N containerView.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 6, 10)); writeButton = new ImageView(context); - writeButtonDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_dialogFloatingButton), Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); + writeButtonDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -1536,7 +1547,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N } writeButton.setBackgroundDrawable(writeButtonDrawable); writeButton.setImageResource(R.drawable.attach_send); - writeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); + writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); writeButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { @@ -1566,7 +1577,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N currentAttachLayout.sendSelectedItems(notify, scheduleDate); dismiss(); } - }); + }, resourcesProvider); } else { if (currentAttachLayout == photoLayout) { sendPressed(true, 0); @@ -1587,7 +1598,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N return false; } - sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext()); + sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext(), resourcesProvider); sendPopupLayout.setAnimationEnabled(false); sendPopupLayout.setOnTouchListener(new View.OnTouchListener() { @@ -1624,7 +1635,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N continue; } int num = a; - itemCells[a] = new ActionBarMenuSubItem(getContext(), a == 0, a == 1); + itemCells[a] = new ActionBarMenuSubItem(getContext(), a == 0, a == 1, resourcesProvider); if (num == 0) { if (UserObject.isUserSelf(user)) { itemCells[a].setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule); @@ -1649,7 +1660,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N currentAttachLayout.sendSelectedItems(notify, scheduleDate); dismiss(); } - }); + }, resourcesProvider); } else if (num == 1) { if (currentAttachLayout == photoLayout) { sendPressed(false, 0); @@ -1661,7 +1672,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N }); i++; } - sendPopupLayout.setupRadialSelectors(Theme.getColor(Theme.key_dialogButtonSelector)); + sendPopupLayout.setupRadialSelectors(getThemedColor(Theme.key_dialogButtonSelector)); sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT); sendPopupWindow.setAnimationEnabled(false); @@ -1694,13 +1705,13 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N int size = Math.max(AndroidUtilities.dp(16) + textSize, AndroidUtilities.dp(24)); int cx = getMeasuredWidth() / 2; - int color = Theme.getColor(Theme.key_dialogRoundCheckBoxCheck); + int color = getThemedColor(Theme.key_dialogRoundCheckBoxCheck); textPaint.setColor(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * (0.58 + 0.42 * sendButtonEnabledProgress)))); - paint.setColor(Theme.getColor(Theme.key_dialogBackground)); + paint.setColor(getThemedColor(Theme.key_dialogBackground)); rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(12), AndroidUtilities.dp(12), paint); - paint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBox)); + paint.setColor(getThemedColor(Theme.key_dialogRoundCheckBox)); rect.set(cx - size / 2 + AndroidUtilities.dp(2), AndroidUtilities.dp(2), cx + size / 2 - AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(2)); canvas.drawRoundRect(rect, AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint); @@ -1728,7 +1739,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N } openTransitionFinished = false; if (Build.VERSION.SDK_INT >= 30) { - int color = Theme.getColor(Theme.key_windowBackgroundGray); + int color = getThemedColor(Theme.key_windowBackgroundGray); if (AndroidUtilities.computePerceivedBrightness(color) < 0.721) { getWindow().setNavigationBarColor(color); } @@ -1880,7 +1891,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N private void openContactsLayout() { if (contactsLayout == null) { - layouts[2] = contactsLayout = new ChatAttachAlertContactsLayout(this, getContext()); + layouts[2] = contactsLayout = new ChatAttachAlertContactsLayout(this, getContext(), resourcesProvider); contactsLayout.setDelegate((user, notify, scheduleDate) -> ((ChatActivity) baseFragment).sendContact(user, notify, scheduleDate)); } showLayout(contactsLayout); @@ -1888,7 +1899,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N private void openAudioLayout(boolean show) { if (audioLayout == null) { - layouts[3] = audioLayout = new ChatAttachAlertAudioLayout(this, getContext()); + layouts[3] = audioLayout = new ChatAttachAlertAudioLayout(this, getContext(), resourcesProvider); audioLayout.setDelegate((audios, caption, notify, scheduleDate) -> ((ChatActivity) baseFragment).sendAudio(audios, caption, notify, scheduleDate)); } if (baseFragment instanceof ChatActivity) { @@ -1903,7 +1914,7 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N private void openDocumentsLayout(boolean show) { if (documentLayout == null) { - layouts[4] = documentLayout = new ChatAttachAlertDocumentLayout(this, getContext(), false); + layouts[4] = documentLayout = new ChatAttachAlertDocumentLayout(this, getContext(), false, resourcesProvider); documentLayout.setDelegate(new ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate() { @Override public void didSelectFiles(ArrayList files, String caption, ArrayList fmessages, boolean notify, int scheduleDate) { @@ -2134,10 +2145,10 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N private void applyAttachButtonColors(View view) { if (view instanceof AttachButton) { AttachButton button = (AttachButton) view; - button.textView.setTextColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_dialogTextGray2), Theme.getColor(button.textKey), button.checkedState)); + button.textView.setTextColor(ColorUtils.blendARGB(getThemedColor(Theme.key_dialogTextGray2), getThemedColor(button.textKey), button.checkedState)); } else if (view instanceof AttachBotButton) { AttachBotButton button = (AttachBotButton) view; - button.nameTextView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + button.nameTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); } } @@ -2164,53 +2175,53 @@ public class ChatAttachAlert extends BottomSheet implements NotificationCenter.N for (int a = 0; a < count; a++) { applyAttachButtonColors(buttonsRecyclerView.getChildAt(a)); } - selectedTextView.setTextColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItems) : Theme.getColor(Theme.key_dialogTextBlack)); + selectedTextView.setTextColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack)); - doneItem.getTextView().setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader)); + doneItem.getTextView().setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader)); - selectedMenuItem.setIconColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItems) : Theme.getColor(Theme.key_dialogTextBlack)); - Theme.setDrawableColor(selectedMenuItem.getBackground(), forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItemsSelector) : Theme.getColor(Theme.key_dialogButtonSelector)); - selectedMenuItem.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), false); - selectedMenuItem.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), true); - selectedMenuItem.redrawPopup(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + selectedMenuItem.setIconColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack)); + Theme.setDrawableColor(selectedMenuItem.getBackground(), forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector)); + selectedMenuItem.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false); + selectedMenuItem.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), true); + selectedMenuItem.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); - searchItem.setIconColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItems) : Theme.getColor(Theme.key_dialogTextBlack)); - Theme.setDrawableColor(searchItem.getBackground(), forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItemsSelector) : Theme.getColor(Theme.key_dialogButtonSelector)); + searchItem.setIconColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack)); + Theme.setDrawableColor(searchItem.getBackground(), forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector)); commentTextView.updateColors(); if (sendPopupLayout != null) { for (int a = 0; a < itemCells.length; a++) { if (itemCells[a] != null) { - itemCells[a].setColors(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon)); - itemCells[a].setSelectorColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItemsSelector) : Theme.getColor(Theme.key_dialogButtonSelector)); + itemCells[a].setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon)); + itemCells[a].setSelectorColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector)); } } - sendPopupLayout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + sendPopupLayout.setBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); if (sendPopupWindow != null && sendPopupWindow.isShowing()) { sendPopupLayout.invalidate(); } } - Theme.setSelectorDrawableColor(writeButtonDrawable, Theme.getColor(Theme.key_dialogFloatingButton), false); - Theme.setSelectorDrawableColor(writeButtonDrawable, Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton), true); - writeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); + Theme.setSelectorDrawableColor(writeButtonDrawable, getThemedColor(Theme.key_dialogFloatingButton), false); + Theme.setSelectorDrawableColor(writeButtonDrawable, getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton), true); + writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); - actionBarShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + actionBarShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); - buttonsRecyclerView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); - buttonsRecyclerView.setBackgroundColor(Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); + buttonsRecyclerView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); + buttonsRecyclerView.setBackgroundColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); - frameLayout2.setBackgroundColor(Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); + frameLayout2.setBackgroundColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); selectedCountView.invalidate(); - actionBar.setBackgroundColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBar) : Theme.getColor(Theme.key_dialogBackground)); - actionBar.setItemsColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItems) : Theme.getColor(Theme.key_dialogTextBlack), false); - actionBar.setItemsBackgroundColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItemsSelector) : Theme.getColor(Theme.key_dialogButtonSelector), false); - actionBar.setTitleColor(forceDarkTheme ? Theme.getColor(Theme.key_voipgroup_actionBarItems) : Theme.getColor(Theme.key_dialogTextBlack)); + actionBar.setBackgroundColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBar) : getThemedColor(Theme.key_dialogBackground)); + actionBar.setItemsColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack), false); + actionBar.setItemsBackgroundColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItemsSelector) : getThemedColor(Theme.key_dialogButtonSelector), false); + actionBar.setTitleColor(forceDarkTheme ? getThemedColor(Theme.key_voipgroup_actionBarItems) : getThemedColor(Theme.key_dialogTextBlack)); - Theme.setDrawableColor(shadowDrawable, Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); + Theme.setDrawableColor(shadowDrawable, getThemedColor(forceDarkTheme ? Theme.key_voipgroup_listViewBackground : Theme.key_dialogBackground)); containerView.invalidate(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertAudioLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertAudioLayout.java index 541a7878c..1089eea77 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertAudioLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertAudioLayout.java @@ -93,8 +93,8 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou void didSelectAudio(ArrayList audios, CharSequence caption, boolean notify, int scheduleDate); } - public ChatAttachAlertAudioLayout(ChatAttachAlert alert, Context context) { - super(alert, context); + public ChatAttachAlertAudioLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); NotificationCenter.getInstance(parentAlert.currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset); NotificationCenter.getInstance(parentAlert.currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart); @@ -102,9 +102,9 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou loadAudio(); frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + frameLayout.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); - searchField = new SearchField(context) { + searchField = new SearchField(context, false, resourcesProvider) { @Override public void onTextChange(String text) { if (text.length() == 0) { @@ -141,7 +141,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou searchField.setHint(LocaleController.getString("SearchMusic", R.string.SearchMusic)); frameLayout.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); - progressView = new EmptyTextProgressView(context); + progressView = new EmptyTextProgressView(context, null, resourcesProvider); progressView.showProgress(); addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); @@ -154,11 +154,11 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou emptyImageView = new ImageView(context); emptyImageView.setImageResource(R.drawable.music_empty); - emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); + emptyImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); emptyTitleTextView = new TextView(context); - emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptyTitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptyTitleTextView.setGravity(Gravity.CENTER); emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); @@ -166,13 +166,13 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0)); emptySubtitleTextView = new TextView(context); - emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptySubtitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptySubtitleTextView.setGravity(Gravity.CENTER); emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0); emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0)); - listView = new RecyclerListView(context) { + listView = new RecyclerListView(context, resourcesProvider) { @Override protected boolean allowSelectChildAtPosition(float x, float y) { return y >= parentAlert.scrollOffsetY[0] + AndroidUtilities.dp(30) + (Build.VERSION.SDK_INT >= 21 && !parentAlert.inBubbleMode ? AndroidUtilities.statusBarHeight : 0); @@ -203,7 +203,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou listView.setVerticalScrollBarEnabled(false); addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0)); listView.setAdapter(listAdapter = new ListAdapter(context)); - listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + listView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); listView.setOnItemClickListener((view, position) -> onItemClick(view)); listView.setOnItemLongClickListener((view, position) -> { onItemClick(view); @@ -222,7 +222,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT); frameLayoutParams.topMargin = AndroidUtilities.dp(58); shadow = new View(context); - shadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadow.setAlpha(0.0f); shadow.setTag(1); addView(shadow, frameLayoutParams); @@ -453,7 +453,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou } private void showErrorBox(String error) { - new AlertDialog.Builder(getContext()).setTitle(LocaleController.getString("AppName", R.string.AppName)).setMessage(error).setPositiveButton(LocaleController.getString("OK", R.string.OK), null).show(); + new AlertDialog.Builder(getContext(), resourcesProvider).setTitle(LocaleController.getString("AppName", R.string.AppName)).setMessage(error).setPositiveButton(LocaleController.getString("OK", R.string.OK), null).show(); } private void onItemClick(View view) { @@ -611,7 +611,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou View view; switch (viewType) { case 0: - SharedAudioCell sharedAudioCell = new SharedAudioCell(mContext) { + SharedAudioCell sharedAudioCell = new SharedAudioCell(mContext, resourcesProvider) { @Override public boolean needPlayMessage(MessageObject messageObject) { playingAudio = messageObject; @@ -778,7 +778,7 @@ public class ChatAttachAlertAudioLayout extends ChatAttachAlert.AttachAlertLayou View view; switch (viewType) { case 0: - SharedAudioCell sharedAudioCell = new SharedAudioCell(mContext) { + SharedAudioCell sharedAudioCell = new SharedAudioCell(mContext, resourcesProvider) { @Override public boolean needPlayMessage(MessageObject messageObject) { playingAudio = messageObject; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertContactsLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertContactsLayout.java index f2d6937da..a82af79c6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertContactsLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertContactsLayout.java @@ -16,7 +16,6 @@ import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.text.TextUtils; -import android.util.SparseBooleanArray; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; @@ -34,6 +33,7 @@ import org.telegram.messenger.R; import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.SimpleTextView; import org.telegram.ui.ActionBar.Theme; @@ -42,6 +42,7 @@ import org.telegram.ui.ActionBar.ThemeDescription; import java.util.ArrayList; import java.util.HashMap; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.RecyclerView; @@ -68,6 +69,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa public static class UserCell extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private BackupImageView avatarImageView; private SimpleTextView nameTextView; private SimpleTextView statusTextView; @@ -87,17 +89,18 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa private boolean needDivider; - public UserCell(Context context) { + public UserCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; - avatarDrawable = new AvatarDrawable(); + avatarDrawable = new AvatarDrawable(resourcesProvider); avatarImageView = new BackupImageView(context); avatarImageView.setRoundRadius(AndroidUtilities.dp(23)); addView(avatarImageView, LayoutHelper.createFrame(46, 46, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 14, 9, LocaleController.isRTL ? 14 : 0, 0)); nameTextView = new SimpleTextView(context); - nameTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + nameTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setTextSize(16); nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); @@ -105,7 +108,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa statusTextView = new SimpleTextView(context); statusTextView.setTextSize(13); - statusTextView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + statusTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); statusTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); addView(statusTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 28 : 72, 36, LocaleController.isRTL ? 72 : 28, 0)); } @@ -225,17 +228,22 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(70), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(70) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } - public ChatAttachAlertContactsLayout(ChatAttachAlert alert, Context context) { - super(alert, context); + public ChatAttachAlertContactsLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); searchAdapter = new ShareSearchAdapter(context); frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + frameLayout.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); - searchField = new SearchField(context) { + searchField = new SearchField(context, false, resourcesProvider) { @Override public void onTextChange(String text) { if (text.length() != 0) { @@ -281,12 +289,12 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa searchField.setHint(LocaleController.getString("SearchFriends", R.string.SearchFriends)); frameLayout.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); - emptyView = new EmptyTextProgressView(context); + emptyView = new EmptyTextProgressView(context, null, resourcesProvider); emptyView.showTextView(); emptyView.setText(LocaleController.getString("NoContacts", R.string.NoContacts)); addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 52, 0, 0)); - listView = new RecyclerListView(context) { + listView = new RecyclerListView(context, resourcesProvider) { @Override protected boolean allowSelectChildAtPosition(float x, float y) { return y >= parentAlert.scrollOffsetY[0] + AndroidUtilities.dp(30) + (Build.VERSION.SDK_INT >= 21 && !parentAlert.inBubbleMode ? AndroidUtilities.statusBarHeight : 0); @@ -317,7 +325,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa listView.setVerticalScrollBarEnabled(false); addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0)); listView.setAdapter(listAdapter = new ShareAdapter(context)); - listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + listView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); listView.setOnItemClickListener((view, position) -> { Object object; if (listView.getAdapter() == searchAdapter) { @@ -353,7 +361,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa contact.user = user; } - PhonebookShareAlert phonebookShareAlert = new PhonebookShareAlert(parentAlert.baseFragment, contact, null, null, null, firstName, lastName); + PhonebookShareAlert phonebookShareAlert = new PhonebookShareAlert(parentAlert.baseFragment, contact, null, null, null, firstName, lastName, resourcesProvider); phonebookShareAlert.setDelegate((user, notify, scheduleDate) -> { parentAlert.dismiss(); delegate.didSelectContact(user, notify, scheduleDate); @@ -372,7 +380,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT); frameLayoutParams.topMargin = AndroidUtilities.dp(58); shadow = new View(context); - shadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadow.setAlpha(0.0f); shadow.setTag(1); addView(shadow, frameLayoutParams); @@ -609,7 +617,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa View view; switch (viewType) { case 0: { - view = new UserCell(mContext); + view = new UserCell(mContext, resourcesProvider); break; } case 1: { @@ -728,7 +736,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa ArrayList resultArray = new ArrayList<>(); ArrayList resultArrayNames = new ArrayList<>(); - SparseBooleanArray foundUids = new SparseBooleanArray(); + LongSparseIntArray foundUids = new LongSparseIntArray(); for (int a = 0; a < contactsCopy.size(); a++) { ContactsController.Contact contact = contactsCopy.get(a); @@ -765,7 +773,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa resultArrayNames.add(AndroidUtilities.generateSearchName("@" + contact.user.username, null, "@" + q)); } if (contact.user != null) { - foundUids.put(contact.user.id, true); + foundUids.put(contact.user.id, 1); } resultArray.add(contact); break; @@ -842,7 +850,7 @@ public class ChatAttachAlertContactsLayout extends ChatAttachAlert.AttachAlertLa View view; switch (viewType) { case 0: - view = new UserCell(mContext); + view = new UserCell(mContext, resourcesProvider); break; case 1: view = new View(mContext); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertDocumentLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertDocumentLayout.java index 8cd61b723..521f6d5a4 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertDocumentLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertDocumentLayout.java @@ -167,8 +167,8 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa } }; - public ChatAttachAlertDocumentLayout(ChatAttachAlert alert, Context context, boolean music) { - super(alert, context); + public ChatAttachAlertDocumentLayout(ChatAttachAlert alert, Context context, boolean music, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); allowMusic = music; sortByName = SharedConfig.sortFilesByName; loadRecentFiles(); @@ -226,16 +226,16 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search)); searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search)); EditTextBoldCursor editText = searchItem.getSearchField(); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); - editText.setCursorColor(Theme.getColor(Theme.key_dialogTextBlack)); - editText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); + editText.setCursorColor(getThemedColor(Theme.key_dialogTextBlack)); + editText.setHintTextColor(getThemedColor(Theme.key_chat_messagePanelHint)); sortItem = menu.addItem(sort_button, sortByName ? R.drawable.contacts_sort_time : R.drawable.contacts_sort_name); sortItem.setContentDescription(LocaleController.getString("AccDescrContactSorting", R.string.AccDescrContactSorting)); - addView(loadingView = new FlickerLoadingView(context)); + addView(loadingView = new FlickerLoadingView(context, resourcesProvider)); - emptyView = new StickerEmptyView(context, loadingView, StickerEmptyView.STICKER_TYPE_SEARCH) { + emptyView = new StickerEmptyView(context, loadingView, StickerEmptyView.STICKER_TYPE_SEARCH, resourcesProvider) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY + additionalTranslationY); @@ -250,7 +250,7 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa emptyView.setVisibility(View.GONE); emptyView.setOnTouchListener((v, event) -> true); - listView = new RecyclerListView(context); + listView = new RecyclerListView(context, resourcesProvider); listView.setSectionsType(2); listView.setVerticalScrollBarEnabled(false); listView.setLayoutManager(layoutManager = new FillLastLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false, AndroidUtilities.dp(56), listView) { @@ -417,12 +417,12 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa return onItemClick(view, object); }); - filtersView = new FiltersView(context); + filtersView = new FiltersView(context, resourcesProvider); filtersView.setOnItemClickListener((view, position) -> { filtersView.cancelClickRunnables(true); searchAdapter.addSearchFilter(filtersView.getFilterAt(position)); }); - filtersView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + filtersView.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); addView(filtersView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP)); filtersView.setTranslationY(-AndroidUtilities.dp(44)); filtersView.setVisibility(INVISIBLE); @@ -932,7 +932,7 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa } private void showErrorBox(String error) { - new AlertDialog.Builder(getContext()).setTitle(LocaleController.getString("AppName", R.string.AppName)).setMessage(error).setPositiveButton(LocaleController.getString("OK", R.string.OK), null).show(); + new AlertDialog.Builder(getContext(), resourcesProvider).setTitle(LocaleController.getString("AppName", R.string.AppName)).setMessage(error).setPositiveButton(LocaleController.getString("OK", R.string.OK), null).show(); } @SuppressLint("NewApi") @@ -1134,15 +1134,15 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa View view; switch (viewType) { case 0: - view = new HeaderCell(mContext); + view = new HeaderCell(mContext, resourcesProvider); break; case 1: - view = new SharedDocumentCell(mContext, SharedDocumentCell.VIEW_TYPE_PICKER); + view = new SharedDocumentCell(mContext, SharedDocumentCell.VIEW_TYPE_PICKER, resourcesProvider); break; case 2: view = new ShadowSectionCell(mContext); Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); view.setBackgroundDrawable(combinedDrawable); break; @@ -1309,7 +1309,7 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa } if (!canSelectOnlyImageFiles && history.isEmpty()) { - int dialogId = 0; + long dialogId = 0; long minDate = 0; long maxDate = 0; for (int i = 0; i < currentSearchFilters.size(); i++) { @@ -1487,7 +1487,7 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa req.q = query; req.limit = 20; req.filter = currentSearchFilter.filter; - req.peer = accountInstance.getMessagesController().getInputPeer((int) dialogId); + req.peer = accountInstance.getMessagesController().getInputPeer(dialogId); if (minDate > 0) { req.min_date = (int) (minDate / 1000); } @@ -1523,7 +1523,7 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa MessageObject lastMessage = messages.get(messages.size() - 1); req.offset_id = lastMessage.getId(); req.offset_rate = nextSearchRate; - int id; + long id; if (lastMessage.messageOwner.peer_id.channel_id != 0) { id = -lastMessage.messageOwner.peer_id.channel_id; } else if (lastMessage.messageOwner.peer_id.chat_id != 0) { @@ -1778,8 +1778,8 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa public View getSectionHeaderView(int section, View view) { GraySectionCell sectionCell = (GraySectionCell) view; if (sectionCell == null) { - sectionCell = new GraySectionCell(mContext); - sectionCell.setBackgroundColor(Theme.getColor(Theme.key_graySection) & 0xf2ffffff); + sectionCell = new GraySectionCell(mContext, resourcesProvider); + sectionCell.setBackgroundColor(getThemedColor(Theme.key_graySection) & 0xf2ffffff); } if (section == 0 || section == 1 && searchResult.isEmpty()) { sectionCell.setAlpha(0f); @@ -1809,16 +1809,16 @@ public class ChatAttachAlertDocumentLayout extends ChatAttachAlert.AttachAlertLa View view; switch (viewType) { case 0: - view = new GraySectionCell(mContext); + view = new GraySectionCell(mContext, resourcesProvider); break; case 1: case 4: - SharedDocumentCell documentCell = new SharedDocumentCell(mContext, viewType == 1 ? SharedDocumentCell.VIEW_TYPE_PICKER : SharedDocumentCell.VIEW_TYPE_GLOBAL_SEARCH); + SharedDocumentCell documentCell = new SharedDocumentCell(mContext, viewType == 1 ? SharedDocumentCell.VIEW_TYPE_PICKER : SharedDocumentCell.VIEW_TYPE_GLOBAL_SEARCH, resourcesProvider); documentCell.setDrawDownloadIcon(false); view = documentCell; break; case 2: - FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext); + FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext, resourcesProvider); flickerLoadingView.setViewType(FlickerLoadingView.FILES_TYPE); flickerLoadingView.setIsSingleCell(true); view = flickerLoadingView; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertLocationLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertLocationLayout.java index d17c102d6..4a702c617 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertLocationLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertLocationLayout.java @@ -61,6 +61,7 @@ import com.google.android.gms.maps.model.MarkerOptions; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocationController; @@ -255,7 +256,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa lastPressedMarkerView = new FrameLayout(context); lastPressedMarkerView.setBackgroundResource(R.drawable.venue_tooltip); - lastPressedMarkerView.getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + lastPressedMarkerView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); frameLayout.addView(lastPressedMarkerView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 71)); lastPressedMarkerView.setAlpha(0.0f); lastPressedMarkerView.setOnClickListener(v -> { @@ -264,7 +265,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(location.venue, locationType, notify, scheduleDate); parentAlert.dismiss(); - }); + }, resourcesProvider); } else { delegate.didSelectLocation(location.venue, locationType, true, 0); parentAlert.dismiss(); @@ -276,7 +277,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa nameTextView.setMaxLines(1); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setSingleLine(true); - nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + nameTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); lastPressedMarkerView.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), 18, 10, 18, 0)); @@ -286,7 +287,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa addressTextView.setMaxLines(1); addressTextView.setEllipsize(TextUtils.TruncateAt.END); addressTextView.setSingleLine(true); - addressTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); + addressTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText3)); addressTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); lastPressedMarkerView.addView(addressTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), 18, 32, 18, 0)); @@ -370,8 +371,8 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa void didSelectLocation(TLRPC.MessageMedia location, int live, boolean notify, int scheduleDate); } - public ChatAttachAlertLocationLayout(ChatAttachAlert alert, Context context) { - super(alert, context); + public ChatAttachAlertLocationLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); AndroidUtilities.fixGoogleMapsBug(); ChatActivity chatActivity = (ChatActivity) parentAlert.baseFragment; dialogId = chatActivity.getDialogId(); @@ -449,9 +450,9 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search)); searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search)); EditTextBoldCursor editText = searchItem.getSearchField(); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); - editText.setCursorColor(Theme.getColor(Theme.key_dialogTextBlack)); - editText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); + editText.setCursorColor(getThemedColor(Theme.key_dialogTextBlack)); + editText.setHintTextColor(getThemedColor(Theme.key_chat_messagePanelHint)); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(21)); layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM; @@ -476,7 +477,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa @Override protected void onDraw(Canvas canvas) { - backgroundPaint.setColor(Theme.getColor(Theme.key_dialogBackground)); + backgroundPaint.setColor(getThemedColor(Theme.key_dialogBackground)); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - clipSize, backgroundPaint); } @@ -504,7 +505,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa searchAreaButton = new SearchButton(context); searchAreaButton.setTranslationX(-AndroidUtilities.dp(80)); searchAreaButton.setVisibility(INVISIBLE); - Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground)); + Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.places_btn).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -525,7 +526,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa }); } searchAreaButton.setBackgroundDrawable(drawable); - searchAreaButton.setTextColor(Theme.getColor(Theme.key_location_actionActiveIcon)); + searchAreaButton.setTextColor(getThemedColor(Theme.key_location_actionActiveIcon)); searchAreaButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); searchAreaButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); searchAreaButton.setText(LocaleController.getString("PlacesInThisArea", R.string.PlacesInThisArea)); @@ -539,16 +540,16 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa showResults(); }); - mapTypeButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_location_actionIcon)); + mapTypeButton = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_location_actionIcon), resourcesProvider); mapTypeButton.setClickable(true); mapTypeButton.setSubMenuOpenSide(2); mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10)); mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10)); - mapTypeButton.addSubItem(map_list_menu_map, R.drawable.msg_map, LocaleController.getString("Map", R.string.Map)); - mapTypeButton.addSubItem(map_list_menu_satellite, R.drawable.msg_satellite, LocaleController.getString("Satellite", R.string.Satellite)); - mapTypeButton.addSubItem(map_list_menu_hybrid, R.drawable.msg_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid)); + mapTypeButton.addSubItem(map_list_menu_map, R.drawable.msg_map, LocaleController.getString("Map", R.string.Map), resourcesProvider); + mapTypeButton.addSubItem(map_list_menu_satellite, R.drawable.msg_satellite, LocaleController.getString("Satellite", R.string.Satellite), resourcesProvider); + mapTypeButton.addSubItem(map_list_menu_hybrid, R.drawable.msg_hybrid, LocaleController.getString("Hybrid", R.string.Hybrid), resourcesProvider); mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions)); - drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground)); + drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -586,7 +587,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa }); locationButton = new ImageView(context); - drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground)); + drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), getThemedColor(Theme.key_location_actionBackground), getThemedColor(Theme.key_location_actionPressedBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -609,7 +610,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa locationButton.setBackgroundDrawable(drawable); locationButton.setImageResource(R.drawable.location_current); locationButton.setScaleType(ImageView.ScaleType.CENTER); - locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); + locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionActiveIcon); locationButton.setContentDescription(LocaleController.getString("AccDescrMyLocation", R.string.AccDescrMyLocation)); FrameLayout.LayoutParams layoutParams1 = LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 12); @@ -625,7 +626,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa } } if (myLocation != null && googleMap != null) { - locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); + locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionActiveIcon); adapter.setCustomLocation(null); userLocationMoved = false; @@ -652,11 +653,11 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa emptyImageView = new ImageView(context); emptyImageView.setImageResource(R.drawable.location_empty); - emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); + emptyImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY)); emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); emptyTitleTextView = new TextView(context); - emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptyTitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptyTitleTextView.setGravity(Gravity.CENTER); emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); @@ -664,13 +665,13 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0)); emptySubtitleTextView = new TextView(context); - emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText)); + emptySubtitleTextView.setTextColor(getThemedColor(Theme.key_dialogEmptyText)); emptySubtitleTextView.setGravity(Gravity.CENTER); emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0); emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0)); - listView = new RecyclerListView(context) { + listView = new RecyclerListView(context, resourcesProvider) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); @@ -678,7 +679,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa } }; listView.setClipToPadding(false); - listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, true)); + listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, true, resourcesProvider)); adapter.setUpdateRunnable(this::updateClipView); listView.setVerticalScrollBarEnabled(false); listView.setLayoutManager(layoutManager = new FillLastLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false, 0, listView) { @@ -747,7 +748,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(location, locationType, notify, scheduleDate); parentAlert.dismiss(); - }); + }, resourcesProvider); } else { delegate.didSelectLocation(location, locationType, true, 0); parentAlert.dismiss(); @@ -768,7 +769,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, notify, scheduleDate); parentAlert.dismiss(); - }); + }, resourcesProvider); } else { delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, true, 0); parentAlert.dismiss(); @@ -823,7 +824,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa } if (ev.getAction() == MotionEvent.ACTION_MOVE) { if (!userLocationMoved) { - locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); + locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionIcon); userLocationMoved = true; } @@ -878,7 +879,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa markerImageView.setImageResource(R.drawable.map_pin2); mapViewClip.addView(markerImageView, LayoutHelper.createFrame(28, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL)); - searchListView = new RecyclerListView(context); + searchListView = new RecyclerListView(context, resourcesProvider); searchListView.setVisibility(GONE); searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); searchAdapter = new LocationActivitySearchAdapter(context) { @@ -913,7 +914,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectLocation(object, locationType, notify, scheduleDate); parentAlert.dismiss(); - }); + }, resourcesProvider); } else { delegate.didSelectLocation(object, locationType, true, 0); parentAlert.dismiss(); @@ -1001,9 +1002,6 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa if (holder != null) { int top = (int) holder.itemView.getY() - nonClipSize; newOffset = Math.max(top, 0); - if (top >= 0) { - newOffset = top; - } } return newOffset + AndroidUtilities.dp(56); } @@ -1084,7 +1082,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa if (info.isDark()) { return true; } - int color = Theme.getColor(Theme.key_windowBackgroundWhite); + int color = getThemedColor(Theme.key_windowBackgroundWhite); return AndroidUtilities.computePerceivedBrightness(color) < 0.721f; } @@ -1132,14 +1130,14 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa int lastTime = preferences.getInt("backgroundloc", 0); if (Math.abs(System.currentTimeMillis() / 1000 - lastTime) > 24 * 60 * 60 && activity.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { preferences.edit().putInt("backgroundloc", (int) (System.currentTimeMillis() / 1000)).commit(); - AlertsCreator.createBackgroundLocationPermissionDialog(activity, getMessagesController().getUser(getUserConfig().getClientUserId()), this::openShareLiveLocation).show(); + AlertsCreator.createBackgroundLocationPermissionDialog(activity, getMessagesController().getUser(getUserConfig().getClientUserId()), this::openShareLiveLocation, resourcesProvider).show(); return; } } } TLRPC.User user = null; - if ((int) dialogId > 0) { - user = parentAlert.baseFragment.getMessagesController().getUser((int) dialogId); + if (DialogObject.isUserDialog(dialogId)) { + user = parentAlert.baseFragment.getMessagesController().getUser(dialogId); } AlertsCreator.createLocationUpdateDialog(getParentActivity(), user, param -> { TLRPC.TL_messageMediaGeoLive location = new TLRPC.TL_messageMediaGeoLive(); @@ -1149,7 +1147,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa location.period = param; delegate.didSelectLocation(location, locationType, true, 0); parentAlert.dismiss(); - }).show(); + }, resourcesProvider).show(); } private Bitmap[] bitmapCache = new Bitmap[7]; @@ -1270,7 +1268,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa } markerImageView.setVisibility(INVISIBLE); if (!userLocationMoved) { - locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); + locationButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY)); locationButton.setTag(Theme.key_location_actionIcon); userLocationMoved = true; } @@ -1297,7 +1295,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa try { LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("GpsDisabledAlertTitle", R.string.GpsDisabledAlertTitle)); builder.setMessage(LocaleController.getString("GpsDisabledAlertText", R.string.GpsDisabledAlertText)); builder.setPositiveButton(LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable), (dialog, id) -> { @@ -1334,7 +1332,7 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa if (getParentActivity() == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (byButton) { builder.setMessage(LocaleController.getString("PermissionNoLocationPosition", R.string.PermissionNoLocationPosition)); @@ -1605,10 +1603,10 @@ public class ChatAttachAlertLocationLayout extends ChatAttachAlert.AttachAlertLa ArrayList themeDescriptions = new ArrayList<>(); ThemeDescription.ThemeDescriptionDelegate cellDelegate = () -> { - mapTypeButton.setIconColor(Theme.getColor(Theme.key_location_actionIcon)); - mapTypeButton.redrawPopup(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); - mapTypeButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon), true); - mapTypeButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), false); + mapTypeButton.setIconColor(getThemedColor(Theme.key_location_actionIcon)); + mapTypeButton.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); + mapTypeButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon), true); + mapTypeButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false); if (googleMap != null) { if (isActiveThemeDark()) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPhotoLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPhotoLayout.java index bb3dbff80..64ffd26c5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPhotoLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPhotoLayout.java @@ -441,8 +441,8 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou return arrayList; } - public ChatAttachAlertPhotoLayout(ChatAttachAlert alert, Context context, boolean forceDarkTheme) { - super(alert, context); + public ChatAttachAlertPhotoLayout(ChatAttachAlert alert, Context context, boolean forceDarkTheme, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); this.forceDarkTheme = forceDarkTheme; NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.albumsDidLoad); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.cameraInitied); @@ -451,7 +451,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou cameraDrawable = context.getResources().getDrawable(R.drawable.instant_camera).mutate(); ActionBarMenu menu = parentAlert.actionBar.createMenu(); - dropDownContainer = new ActionBarMenuItem(context, menu, 0, 0) { + dropDownContainer = new ActionBarMenuItem(context, menu, 0, 0, resourcesProvider) { @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); @@ -469,11 +469,11 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou dropDown.setLines(1); dropDown.setMaxLines(1); dropDown.setEllipsize(TextUtils.TruncateAt.END); - dropDown.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + dropDown.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); dropDown.setText(LocaleController.getString("ChatGallery", R.string.ChatGallery)); dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); dropDownDrawable = context.getResources().getDrawable(R.drawable.ic_arrow_drop_down).mutate(); - dropDownDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY)); + dropDownDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogTextBlack), PorterDuff.Mode.MULTIPLY)); dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4)); dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0); dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 0)); @@ -484,7 +484,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou parentAlert.selectedMenuItem.addSubItem(compress, LocaleController.getString("SendWithoutCompression", R.string.SendWithoutCompression)); parentAlert.selectedMenuItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp)); - gridView = new RecyclerListView(context) { + gridView = new RecyclerListView(context, resourcesProvider) { @Override public boolean onTouchEvent(MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN && e.getY() < parentAlert.scrollOffsetY[0] - AndroidUtilities.dp(80)) { @@ -513,7 +513,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou gridView.setItemAnimator(null); gridView.setLayoutAnimation(null); gridView.setVerticalScrollBarEnabled(false); - gridView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + gridView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); gridView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override @@ -606,7 +606,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou if (position < 0 || position >= arrayList.size()) { return; } - PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity()); + PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity(), resourcesProvider); PhotoViewer.getInstance().setParentAlert(parentAlert); PhotoViewer.getInstance().setMaxSelectedPhotos(parentAlert.maxSelectedPhotos, parentAlert.allowOrder); ChatActivity chatActivity; @@ -682,7 +682,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou }); gridView.addOnItemTouchListener(itemRangeSelector); - progressView = new EmptyTextProgressView(context); + progressView = new EmptyTextProgressView(context, null, resourcesProvider); progressView.setText(LocaleController.getString("NoPhotos", R.string.NoPhotos)); progressView.setOnTouchListener(null); progressView.setTextSize(20); @@ -1025,7 +1025,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou tooltipTextView.setPadding(AndroidUtilities.dp(6), 0, AndroidUtilities.dp(6), 0); cameraPanel.addView(tooltipTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, 16)); - cameraPhotoRecyclerView = new RecyclerListView(context) { + cameraPhotoRecyclerView = new RecyclerListView(context, resourcesProvider) { @Override public void requestLayout() { if (cameraPhotoRecyclerViewIgnoreLayout) { @@ -1304,7 +1304,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou return; } cancelTakingPhotos = true; - PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity()); + PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity(), resourcesProvider); PhotoViewer.getInstance().setParentAlert(parentAlert); PhotoViewer.getInstance().setMaxSelectedPhotos(parentAlert.maxSelectedPhotos, parentAlert.allowOrder); @@ -1911,7 +1911,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou } mediaFromExternalCamera = true; if (requestCode == 0) { - PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity()); + PhotoViewer.getInstance().setParentActivity(parentAlert.baseFragment.getParentActivity(), resourcesProvider); PhotoViewer.getInstance().setMaxSelectedPhotos(parentAlert.maxSelectedPhotos, parentAlert.allowOrder); final ArrayList arrayList = new ArrayList<>(); int orientation = 0; @@ -2395,7 +2395,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou ChatActivity chatActivity = (ChatActivity) parentAlert.baseFragment; TLRPC.Chat chat = chatActivity.getCurrentChat(); if (chat != null && !ChatObject.hasAdminRights(chat) && chat.slowmode_enabled) { - AlertsCreator.createSimpleAlert(getContext(), LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendError", R.string.SlowmodeSendError)).show(); + AlertsCreator.createSimpleAlert(getContext(), LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendError", R.string.SlowmodeSendError), resourcesProvider).show(); return; } } @@ -2405,7 +2405,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou AlertsCreator.createScheduleDatePickerDialog(getContext(), ((ChatActivity) parentAlert.baseFragment).getDialogId(), (notify, scheduleDate) -> { parentAlert.applyCaption(); parentAlert.delegate.didPressedButton(7, false, notify, scheduleDate, false); - }); + }, resourcesProvider); } else { parentAlert.applyCaption(); parentAlert.delegate.didPressedButton(7, false, true, 0, false); @@ -2415,7 +2415,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou AlertsCreator.createScheduleDatePickerDialog(getContext(), ((ChatActivity) parentAlert.baseFragment).getDialogId(), (notify, scheduleDate) -> { parentAlert.applyCaption(); parentAlert.delegate.didPressedButton(4, true, notify, scheduleDate, false); - }); + }, resourcesProvider); } else { parentAlert.applyCaption(); parentAlert.delegate.didPressedButton(4, true, true, 0, false); @@ -2571,19 +2571,19 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou cameraIcon.invalidate(); } String textColor = forceDarkTheme ? Theme.key_voipgroup_actionBarItems : Theme.key_dialogTextBlack; - Theme.setDrawableColor(cameraDrawable, Theme.getColor(Theme.key_dialogCameraIcon)); - progressView.setTextColor(Theme.getColor(Theme.key_emptyListPlaceholder)); - gridView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + Theme.setDrawableColor(cameraDrawable, getThemedColor(Theme.key_dialogCameraIcon)); + progressView.setTextColor(getThemedColor(Theme.key_emptyListPlaceholder)); + gridView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); RecyclerView.ViewHolder holder = gridView.findViewHolderForAdapterPosition(0); if (holder != null && holder.itemView instanceof PhotoAttachCameraCell) { - ((PhotoAttachCameraCell) holder.itemView).getImageView().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogCameraIcon), PorterDuff.Mode.MULTIPLY)); + ((PhotoAttachCameraCell) holder.itemView).getImageView().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogCameraIcon), PorterDuff.Mode.MULTIPLY)); } - dropDown.setTextColor(Theme.getColor(textColor)); - dropDownContainer.setPopupItemsColor(Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_actionBarItems : Theme.key_actionBarDefaultSubmenuItem), false); - dropDownContainer.setPopupItemsColor(Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_actionBarItems :Theme.key_actionBarDefaultSubmenuItem), true); - dropDownContainer.redrawPopup(Theme.getColor(forceDarkTheme ? Theme.key_voipgroup_actionBarUnscrolled : Theme.key_actionBarDefaultSubmenuBackground)); - Theme.setDrawableColor(dropDownDrawable, Theme.getColor(textColor)); + dropDown.setTextColor(getThemedColor(textColor)); + dropDownContainer.setPopupItemsColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_actionBarItems : Theme.key_actionBarDefaultSubmenuItem), false); + dropDownContainer.setPopupItemsColor(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_actionBarItems :Theme.key_actionBarDefaultSubmenuItem), true); + dropDownContainer.redrawPopup(getThemedColor(forceDarkTheme ? Theme.key_voipgroup_actionBarUnscrolled : Theme.key_actionBarDefaultSubmenuBackground)); + Theme.setDrawableColor(dropDownDrawable, getThemedColor(textColor)); } @Override @@ -3074,7 +3074,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou } public RecyclerListView.Holder createHolder() { - PhotoAttachPhotoCell cell = new PhotoAttachPhotoCell(mContext); + PhotoAttachPhotoCell cell = new PhotoAttachPhotoCell(mContext, resourcesProvider); if (Build.VERSION.SDK_INT >= 21 && this == adapter) { cell.setOutlineProvider(new ViewOutlineProvider() { @Override @@ -3110,7 +3110,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou TLRPC.Chat chat = chatActivity.getCurrentChat(); if (chat != null && !ChatObject.hasAdminRights(chat) && chat.slowmode_enabled) { if (alertOnlyOnce != 2) { - AlertsCreator.createSimpleAlert(getContext(), LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSelectSendError", R.string.SlowmodeSelectSendError)).show(); + AlertsCreator.createSimpleAlert(getContext(), LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSelectSendError", R.string.SlowmodeSelectSendError), resourcesProvider).show(); if (alertOnlyOnce == 1) { alertOnlyOnce = 2; } @@ -3212,7 +3212,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou } break; case 1: - PhotoAttachCameraCell cameraCell = new PhotoAttachCameraCell(mContext); + PhotoAttachCameraCell cameraCell = new PhotoAttachCameraCell(mContext, resourcesProvider); if (Build.VERSION.SDK_INT >= 21) { cameraCell.setOutlineProvider(new ViewOutlineProvider() { @Override @@ -3235,7 +3235,7 @@ public class ChatAttachAlertPhotoLayout extends ChatAttachAlert.AttachAlertLayou break; case 3: default: - holder = new RecyclerListView.Holder(new PhotoAttachPermissionCell(mContext)); + holder = new RecyclerListView.Holder(new PhotoAttachPermissionCell(mContext, resourcesProvider)); break; } return holder; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPollLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPollLayout.java index 3fa3c9a12..33e4c3f0b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPollLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlertPollLayout.java @@ -149,7 +149,7 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout listView.setItemAnimator(itemAnimator); listView.cancelClickRunnables(false); viewHolder.itemView.setPressed(true); - viewHolder.itemView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + viewHolder.itemView.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); } super.onSelectedChanged(viewHolder, actionState); } @@ -167,8 +167,8 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout } } - public ChatAttachAlertPollLayout(ChatAttachAlert alert, Context context) { - super(alert, context); + public ChatAttachAlertPollLayout(ChatAttachAlert alert, Context context, Theme.ResourcesProvider resourcesProvider) { + super(alert, context, resourcesProvider); updateRows(); /*if (quiz != null) { @@ -710,7 +710,7 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout textCell.setText2(String.format("%d", left)); SimpleTextView textView = textCell.getTextView2(); String key = left < 0 ? Theme.key_windowBackgroundWhiteRedText5 : Theme.key_windowBackgroundWhiteGrayText3; - textView.setTextColor(Theme.getColor(key)); + textView.setTextColor(getThemedColor(key)); textView.setTag(key); } else { textCell.setText2(""); @@ -769,7 +769,7 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout case 2: { TextInfoPrivacyCell cell = (TextInfoPrivacyCell) holder.itemView; Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); cell.setBackgroundDrawable(combinedDrawable); if (position == solutionInfoRow) { @@ -792,8 +792,8 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout textCell.setColors(null, Theme.key_windowBackgroundWhiteBlueText4); Drawable drawable1 = mContext.getResources().getDrawable(R.drawable.poll_add_circle); Drawable drawable2 = mContext.getResources().getDrawable(R.drawable.poll_add_plus); - drawable1.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_switchTrackChecked), PorterDuff.Mode.MULTIPLY)); - drawable2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_checkboxCheck), PorterDuff.Mode.MULTIPLY)); + drawable1.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_switchTrackChecked), PorterDuff.Mode.MULTIPLY)); + drawable2.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_checkboxCheck), PorterDuff.Mode.MULTIPLY)); CombinedDrawable combinedDrawable = new CombinedDrawable(drawable1, drawable2); textCell.setTextAndIcon(LocaleController.getString("AddAnOption", R.string.AddAnOption), combinedDrawable, false); break; @@ -874,7 +874,7 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout case 1: view = new ShadowSectionCell(mContext); Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); view.setBackgroundDrawable(combinedDrawable); break; @@ -970,7 +970,7 @@ public class ChatAttachAlertPollLayout extends ChatAttachAlert.AttachAlertLayout } case 8: { view = new EmptyView(mContext); - view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray)); + view.setBackgroundColor(getThemedColor(Theme.key_windowBackgroundGray)); break; } case 9: { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAvatarContainer.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAvatarContainer.java index e65337709..b75a58585 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAvatarContainer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAvatarContainer.java @@ -27,6 +27,7 @@ import android.widget.ImageView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageReceiver; @@ -59,6 +60,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent private int currentAccount = UserConfig.selectedAccount; private boolean occupyStatusBar = true; private int leftPadding = AndroidUtilities.dp(8); + StatusDrawable currentTypingDrawable; private AnimatorSet titleAnimation; @@ -72,9 +74,15 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent private String lastSubtitleColorKey; private SharedMediaLayout.SharedMediaPreloader sharedMediaPreloader; + private Theme.ResourcesProvider resourcesProvider; public ChatAvatarContainer(Context context, ChatActivity chatActivity, boolean needTime) { + this(context, chatActivity, needTime, null); + } + + public ChatAvatarContainer(Context context, ChatActivity chatActivity, boolean needTime, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; parentFragment = chatActivity; final boolean avatarClickable = parentFragment != null && parentFragment.getChatMode() == 0 && !UserObject.isReplyUser(parentFragment.getCurrentUser()); @@ -106,7 +114,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent } titleTextView = new SimpleTextView(context); - titleTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle)); + titleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultTitle)); titleTextView.setTextSize(18); titleTextView.setGravity(Gravity.LEFT); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -114,7 +122,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent addView(titleTextView); subtitleTextView = new SimpleTextView(context); - subtitleTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle)); + subtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle)); subtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle); subtitleTextView.setTextSize(14); subtitleTextView.setGravity(Gravity.LEFT); @@ -134,7 +142,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent timeItem.setOnClickListener(v -> { if (secretChatTimer) { - parentFragment.showDialog(AlertsCreator.createTTLAlert(getContext(), parentFragment.getCurrentEncryptedChat()).create()); + parentFragment.showDialog(AlertsCreator.createTTLAlert(getContext(), parentFragment.getCurrentEncryptedChat(), resourcesProvider).create()); } else { openSetTimer(); } @@ -152,12 +160,12 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent } TLRPC.Chat chat = parentFragment.getCurrentChat(); - statusDrawables[0] = new TypingDotsDrawable(false); - statusDrawables[1] = new RecordStatusDrawable(false); - statusDrawables[2] = new SendingFileDrawable(false); - statusDrawables[3] = new PlayingGameDrawable(false); - statusDrawables[4] = new RoundStatusDrawable(false); - statusDrawables[5] = new ChoosingStickerStatusDrawable(false); + statusDrawables[0] = new TypingDotsDrawable(true); + statusDrawables[1] = new RecordStatusDrawable(true); + statusDrawables[2] = new SendingFileDrawable(true); + statusDrawables[3] = new PlayingGameDrawable(false, resourcesProvider); + statusDrawables[4] = new RoundStatusDrawable(true); + statusDrawables[5] = new ChoosingStickerStatusDrawable(true); for (int a = 0; a < statusDrawables.length; a++) { statusDrawables[a].setIsChat(chat != null); } @@ -175,7 +183,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent } return false; } - ClearHistoryAlert alert = new ClearHistoryAlert(parentFragment.getParentActivity(), parentFragment.getCurrentUser(), parentFragment.getCurrentChat(), false); + ClearHistoryAlert alert = new ClearHistoryAlert(parentFragment.getParentActivity(), parentFragment.getCurrentUser(), parentFragment.getCurrentChat(), false, null); alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() { @Override public void onAutoDeleteHistory(int ttl, int action) { @@ -217,11 +225,12 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent fragment.setChatInfo(parentFragment.getCurrentChatInfo()); parentFragment.presentFragment(fragment); } else { - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); args.putBoolean("reportSpam", parentFragment.hasReportSpam()); if (timeItem != null) { args.putLong("dialog_id", parentFragment.getDialogId()); } + args.putInt("actionBarColor", getThemedColor(Theme.key_actionBarDefault)); ProfileActivity fragment = new ProfileActivity(args, sharedMediaPreloader); fragment.setUserInfo(parentFragment.getCurrentUserInfo()); fragment.setPlayProfileAnimation(byAvatar ? 2 : 1); @@ -229,7 +238,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent } } else if (chat != null) { Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); ProfileActivity fragment = new ProfileActivity(args, sharedMediaPreloader); fragment.setChatInfo(parentFragment.getCurrentChatInfo()); fragment.setPlayProfileAnimation(byAvatar ? 2 : 1); @@ -345,7 +354,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent if (scam || fake) { if (!(titleTextView.getRightDrawable() instanceof ScamDrawable)) { ScamDrawable drawable = new ScamDrawable(11, scam ? 0 : 1); - drawable.setColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle)); + drawable.setColor(getThemedColor(Theme.key_actionBarDefaultSubtitle)); titleTextView.setRightDrawable(drawable); } } else if (titleTextView.getRightDrawable() instanceof ScamDrawable) { @@ -385,11 +394,14 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent int type = MessagesController.getInstance(currentAccount).getPrintingStringType(parentFragment.getDialogId(), parentFragment.getThreadId()); if (type == 5) { subtitleTextView.replaceTextWithDrawable(statusDrawables[type], "**oo**"); + statusDrawables[type].setColor(getThemedColor(Theme.key_chat_status)); subtitleTextView.setLeftDrawable(null); } else { subtitleTextView.replaceTextWithDrawable(null, null); + statusDrawables[type].setColor(getThemedColor(Theme.key_chat_status)); subtitleTextView.setLeftDrawable(statusDrawables[type]); } + currentTypingDrawable = statusDrawables[type]; for (int a = 0; a < statusDrawables.length; a++) { if (a == type) { statusDrawables[a].start(); @@ -401,6 +413,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent FileLog.e(e); } } else { + currentTypingDrawable = null; subtitleTextView.setLeftDrawable(null); subtitleTextView.replaceTextWithDrawable(null, null); for (int a = 0; a < statusDrawables.length; a++) { @@ -581,13 +594,16 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent } } newSubtitle = printString; + if (MessagesController.getInstance(currentAccount).getPrintingStringType(parentFragment.getDialogId(), parentFragment.getThreadId()) == 5) { + newSubtitle = Emoji.replaceEmoji(newSubtitle, subtitleTextView.getTextPaint().getFontMetricsInt(), AndroidUtilities.dp(15), false); + } useOnlineColor = true; setTypingAnimation(true); } lastSubtitleColorKey = useOnlineColor ? Theme.key_chat_status : Theme.key_actionBarDefaultSubtitle; if (lastSubtitle == null) { subtitleTextView.setText(newSubtitle); - subtitleTextView.setTextColor(Theme.getColor(lastSubtitleColorKey)); + subtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey)); subtitleTextView.setTag(lastSubtitleColorKey); } else { lastSubtitle = newSubtitle; @@ -729,7 +745,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent subtitleTextView.setText(lastSubtitle); lastSubtitle = null; if (lastSubtitleColorKey != null) { - subtitleTextView.setTextColor(Theme.getColor(lastSubtitleColorKey)); + subtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey)); subtitleTextView.setTag(lastSubtitleColorKey); } } @@ -738,7 +754,7 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent lastSubtitle = subtitleTextView.getText(); } subtitleTextView.setText(title); - subtitleTextView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubtitle)); + subtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle)); subtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle); } } @@ -758,4 +774,15 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent public BackupImageView getAvatarImageView() { return avatarImageView; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + public void updateColors() { + if (currentTypingDrawable != null) { + currentTypingDrawable.setColor(getThemedColor(Theme.key_chat_status)); + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatBigEmptyView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatBigEmptyView.java index 0a702d7a8..92ce094e0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatBigEmptyView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatBigEmptyView.java @@ -9,6 +9,7 @@ package org.telegram.ui.Components; import android.content.Context; +import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.util.TypedValue; @@ -27,6 +28,7 @@ import java.util.ArrayList; public class ChatBigEmptyView extends LinearLayout { + private final Theme.ResourcesProvider resourcesProvider; private TextView statusTextView; private ArrayList textViews = new ArrayList<>(); private ArrayList imageViews = new ArrayList<>(); @@ -35,17 +37,18 @@ public class ChatBigEmptyView extends LinearLayout { public final static int EMPTY_VIEW_TYPE_GROUP = 1; public final static int EMPTY_VIEW_TYPE_SAVED = 2; - public ChatBigEmptyView(Context context, View parent, int type) { + public ChatBigEmptyView(Context context, View parent, int type, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; - setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), this, parent)); + setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), this, parent, getThemedPaint(Theme.key_paint_chatActionBackground))); setPadding(AndroidUtilities.dp(16), AndroidUtilities.dp(12), AndroidUtilities.dp(16), AndroidUtilities.dp(12)); setOrientation(LinearLayout.VERTICAL); if (type == EMPTY_VIEW_TYPE_SECRET) { statusTextView = new TextView(context); statusTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - statusTextView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); + statusTextView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); statusTextView.setGravity(Gravity.CENTER_HORIZONTAL); statusTextView.setMaxWidth(AndroidUtilities.dp(210)); textViews.add(statusTextView); @@ -53,7 +56,7 @@ public class ChatBigEmptyView extends LinearLayout { } else if (type == EMPTY_VIEW_TYPE_GROUP) { statusTextView = new TextView(context); statusTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - statusTextView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); + statusTextView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); statusTextView.setGravity(Gravity.CENTER_HORIZONTAL); statusTextView.setMaxWidth(AndroidUtilities.dp(210)); textViews.add(statusTextView); @@ -77,7 +80,7 @@ public class ChatBigEmptyView extends LinearLayout { textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setGravity(Gravity.CENTER_HORIZONTAL); } - textView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); + textView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); textViews.add(textView); textView.setMaxWidth(AndroidUtilities.dp(260)); addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (type != EMPTY_VIEW_TYPE_SAVED ? (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) : Gravity.CENTER_HORIZONTAL) | Gravity.TOP, 0, 8, 0, type != EMPTY_VIEW_TYPE_SAVED ? 0 : 8)); @@ -88,7 +91,7 @@ public class ChatBigEmptyView extends LinearLayout { addView(linearLayout, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 0, 8, 0, 0)); ImageView imageView = new ImageView(context); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_serviceText), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_serviceText), PorterDuff.Mode.MULTIPLY)); if (type == EMPTY_VIEW_TYPE_SECRET) { imageView.setImageResource(R.drawable.ic_lock_white); } else if (type == EMPTY_VIEW_TYPE_SAVED) { @@ -100,7 +103,7 @@ public class ChatBigEmptyView extends LinearLayout { textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); + textView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); textViews.add(textView); textView.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); textView.setMaxWidth(AndroidUtilities.dp(260)); @@ -171,11 +174,21 @@ public class ChatBigEmptyView extends LinearLayout { textViews.get(a).setTextColor(color); } for (int a = 0; a < imageViews.size(); a++) { - imageViews.get(a).setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_serviceText), PorterDuff.Mode.MULTIPLY)); + imageViews.get(a).setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_serviceText), PorterDuff.Mode.MULTIPLY)); } } public void setStatusText(CharSequence text) { statusTextView.setText(text); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + private Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatGreetingsView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatGreetingsView.java index 3c61a4e11..31d47d45b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatGreetingsView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatGreetingsView.java @@ -32,12 +32,13 @@ public class ChatGreetingsView extends LinearLayout { private final int currentAccount; public BackupImageView stickerToSendView; + private final Theme.ResourcesProvider resourcesProvider; - - public ChatGreetingsView(Context context, TLRPC.User user, int distance, int currentAccount, TLRPC.Document sticker) { + public ChatGreetingsView(Context context, TLRPC.User user, int distance, int currentAccount, TLRPC.Document sticker, Theme.ResourcesProvider resourcesProvider) { super(context); setOrientation(VERTICAL); this.currentAccount = currentAccount; + this.resourcesProvider = resourcesProvider; titleView = new TextView(context); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); @@ -129,8 +130,8 @@ public class ChatGreetingsView extends LinearLayout { } private void updateColors() { - titleView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); - descriptionView.setTextColor(Theme.getColor(Theme.key_chat_serviceText)); + titleView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); + descriptionView.setTextColor(getThemedColor(Theme.key_chat_serviceText)); } public void setListener(Listener listener) { @@ -185,4 +186,9 @@ public class ChatGreetingsView extends LinearLayout { setSticker(preloadedGreetingsSticker); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatThemeBottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatThemeBottomSheet.java new file mode 100644 index 000000000..9776caeb2 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatThemeBottomSheet.java @@ -0,0 +1,1063 @@ +package org.telegram.ui.Components; + +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.animation.ValueAnimator; +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapShader; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.LinearGradient; +import android.graphics.Paint; +import android.graphics.Path; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.RectF; +import android.graphics.Shader; +import android.graphics.Typeface; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.text.Layout; +import android.text.StaticLayout; +import android.text.TextPaint; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.OvershootInterpolator; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.LinearSmoothScroller; +import androidx.recyclerview.widget.RecyclerView; + +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.ChatThemeController; +import org.telegram.messenger.Emoji; +import org.telegram.messenger.ImageLocation; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.MediaDataController; +import org.telegram.messenger.MessagesController; +import org.telegram.messenger.NotificationCenter; +import org.telegram.messenger.R; +import org.telegram.messenger.SharedConfig; +import org.telegram.tgnet.ResultCallback; +import org.telegram.tgnet.TLRPC; +import org.telegram.ui.ActionBar.AlertDialog; +import org.telegram.ui.ActionBar.BottomSheet; +import org.telegram.ui.ActionBar.ChatTheme; +import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.ActionBar.ThemeDescription; +import org.telegram.ui.ChatActivity; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class ChatThemeBottomSheet extends BottomSheet implements NotificationCenter.NotificationCenterDelegate { + + private final Adapter adapter; + private final ChatActivity.ThemeDelegate themeDelegate; + private final ChatTheme originalTheme; + private final boolean originalIsDark; + private final ChatActivity chatActivity; + private final RecyclerListView recyclerView; + private final LinearLayoutManager layoutManager; + private final FlickerLoadingView progressView; + private final TextView titleView; + private final RLottieDrawable darkThemeDrawable; + private final RLottieImageView darkThemeView; + private final LinearSmoothScroller scroller; + private final View applyButton; + private TextView applyTextView; + private TextView resetTextView; + private ChatThemeItem selectedItem; + private boolean forceDark; + private boolean isApplyClicked; + private boolean isLightDarkChangeAnimation; + private int prevSelectedPosition = -1; + private View changeDayNightView; + private float changeDayNightViewProgress; + private ValueAnimator changeDayNightViewAnimator; + HintView hintView; + + public ChatThemeBottomSheet(final ChatActivity chatActivity, ChatActivity.ThemeDelegate themeDelegate) { + super(chatActivity.getParentActivity(), true, themeDelegate); + this.chatActivity = chatActivity; + this.themeDelegate = themeDelegate; + this.originalTheme = themeDelegate.getCurrentTheme(); + this.originalIsDark = Theme.getActiveTheme().isDark(); + adapter = new Adapter(themeDelegate); + setDimBehind(false); + setCanDismissWithSwipe(false); + setApplyBottomPadding(false); + + FrameLayout rootLayout = new FrameLayout(getContext()); + setCustomView(rootLayout); + + titleView = new TextView(getContext()); + titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE); + titleView.setLines(1); + titleView.setSingleLine(true); + titleView.setText(LocaleController.getString("SelectTheme", R.string.SelectTheme)); + titleView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); + titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8)); + rootLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.START, 0, 0, 62, 0)); + + int drawableColor = getThemedColor(Theme.key_featuredStickers_addButton); + int drawableSize = AndroidUtilities.dp(28); + darkThemeDrawable = new RLottieDrawable(R.raw.sun_outline, "" + R.raw.sun_outline, drawableSize, drawableSize, true, null); + darkThemeDrawable.setPlayInDirectionOfCustomEndFrame(true); + darkThemeDrawable.beginApplyLayerColors(); + setDarkButtonColor(drawableColor); + darkThemeDrawable.commitApplyLayerColors(); + + darkThemeView = new RLottieImageView(getContext()); + darkThemeView.setAnimation(darkThemeDrawable); + darkThemeView.setScaleType(ImageView.ScaleType.CENTER); + darkThemeView.setOnClickListener(view -> { + if (changeDayNightViewAnimator != null) { + return; + } + setupLightDarkTheme(!forceDark); + }); + rootLayout.addView(darkThemeView, LayoutHelper.createFrame(44, 44, Gravity.TOP | Gravity.END, 0, 0, 7, 0)); + forceDark = !Theme.getActiveTheme().isDark(); + setForceDark(Theme.getActiveTheme().isDark(), false); + + scroller = new LinearSmoothScroller(getContext()) { + @Override + protected int calculateTimeForScrolling(int dx) { + return super.calculateTimeForScrolling(dx) * 6; + } + }; + recyclerView = new RecyclerListView(getContext()); + recyclerView.setAdapter(adapter); + recyclerView.setClipChildren(false); + recyclerView.setClipToPadding(false); + recyclerView.setHasFixedSize(true); + recyclerView.setItemAnimator(null); + recyclerView.setNestedScrollingEnabled(false); + recyclerView.setLayoutManager(layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false)); + recyclerView.setPadding(AndroidUtilities.dp(12), 0, AndroidUtilities.dp(12), 0); + recyclerView.setOnItemClickListener((view, position) -> { + if (adapter.items.get(position) == selectedItem) { + return; + } + selectedItem = adapter.items.get(position); + isLightDarkChangeAnimation = false; + if (selectedItem.chatTheme == null || selectedItem.chatTheme.isDefault) { + applyTextView.animate().alpha(0f).setDuration(300).start(); + resetTextView.animate().alpha(1f).setDuration(300).start(); + } else { + resetTextView.animate().alpha(0f).setDuration(300).start(); + applyTextView.animate().alpha(1f).setDuration(300).start(); + } + if (selectedItem.chatTheme.isDefault) { + themeDelegate.setCurrentTheme(null, true, forceDark); + } else { + themeDelegate.setCurrentTheme(selectedItem.chatTheme, true, forceDark); + } + adapter.setSelectedItem(position); + containerView.postDelayed(new Runnable() { + @Override + public void run() { + RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); + if (layoutManager != null) { + final int targetPosition = position > prevSelectedPosition + ? Math.min(position + 1, adapter.items.size() - 1) + : Math.max(position - 1, 0); + scroller.setTargetPosition(targetPosition); + layoutManager.startSmoothScroll(scroller); + } + prevSelectedPosition = position; + } + }, 100); + for (int i = 0; i < recyclerView.getChildCount(); i++) { + Adapter.ChatThemeView child = (Adapter.ChatThemeView) recyclerView.getChildAt(i); + if (child != view) { + child.cancelAnimation(); + } + } + if (!adapter.items.get(position).chatTheme.isDefault) { + ((Adapter.ChatThemeView) view).playEmojiAnimation(); + } + }); + + progressView = new FlickerLoadingView(getContext(), resourcesProvider); + progressView.setViewType(FlickerLoadingView.CHAT_THEMES_TYPE); + progressView.setVisibility(View.VISIBLE); + rootLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 104, Gravity.START, 0, 44, 0, 0)); + + rootLayout.addView(recyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 104, Gravity.START, 0, 44, 0, 0)); + + applyButton = new View(getContext()); + applyButton.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(6), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); + applyButton.setEnabled(false); + applyButton.setOnClickListener((view) -> applySelectedTheme()); + rootLayout.addView(applyButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.START, 16, 162, 16, 16)); + + resetTextView = new TextView(getContext()); + resetTextView.setAlpha(0f); + resetTextView.setEllipsize(TextUtils.TruncateAt.END); + resetTextView.setGravity(Gravity.CENTER); + resetTextView.setLines(1); + resetTextView.setSingleLine(true); + resetTextView.setText(themeDelegate.getCurrentTheme() == null ? LocaleController.getString("DoNoSetTheme", R.string.DoNoSetTheme) : LocaleController.getString("ChatResetTheme", R.string.ChatResetTheme)); + resetTextView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); + resetTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + resetTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + resetTextView.setVisibility(View.INVISIBLE); + rootLayout.addView(resetTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.START, 16, 162, 16, 16)); + + applyTextView = new TextView(getContext()); + applyTextView.setEllipsize(TextUtils.TruncateAt.END); + applyTextView.setGravity(Gravity.CENTER); + applyTextView.setLines(1); + applyTextView.setSingleLine(true); + applyTextView.setText(LocaleController.getString("ChatApplyTheme", R.string.ChatApplyTheme)); + applyTextView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); + applyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); + applyTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + applyTextView.setVisibility(View.INVISIBLE); + rootLayout.addView(applyTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.START, 16, 162, 16, 16)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + ChatThemeController.preloadAllWallpaperThumbs(true); + ChatThemeController.preloadAllWallpaperThumbs(false); + ChatThemeController.preloadAllWallpaperImages(true); + ChatThemeController.preloadAllWallpaperImages(false); + NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); + + isApplyClicked = false; + List cachedThemes = themeDelegate.getCachedThemes(); + if (cachedThemes == null || cachedThemes.isEmpty()) { + ChatThemeController.requestAllChatThemes(new ResultCallback>() { + @Override + public void onComplete(List result) { + if (result != null && !result.isEmpty()) { + themeDelegate.setCachedThemes(result); + } + onDataLoaded(result); + } + + @Override + public void onError(TLRPC.TL_error error) { + Toast.makeText(getContext(), error.text, Toast.LENGTH_SHORT).show(); + } + }, true); + } else { + onDataLoaded(cachedThemes); + } + + + if (chatActivity.getCurrentUser() != null && SharedConfig.dayNightThemeSwitchHintCount > 0) { + SharedConfig.updateDayNightThemeSwitchHintCount(SharedConfig.dayNightThemeSwitchHintCount - 1); + hintView = new HintView(getContext(), 9, chatActivity.getResourceProvider()); + hintView.setVisibility(View.INVISIBLE); + hintView.setShowingDuration(5000); + hintView.setBottomOffset(-AndroidUtilities.dp(8)); + hintView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("ChatThemeDayNightSwitchTooltip", R.string.ChatThemeDayNightSwitchTooltip, chatActivity.getCurrentUser().first_name))); + AndroidUtilities.runOnUIThread(() -> { + hintView.showForView(darkThemeView, true); + }, 1500); + + container.addView(hintView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0)); + } + } + + @Override + public void onContainerTranslationYChanged(float y) { + if (hintView != null) { + hintView.hide(); + } + } + @Override + public void onBackPressed() { + close(); + } + + @Override + public void dismiss() { + NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded); + super.dismiss(); + if (!isApplyClicked) { + themeDelegate.setCurrentTheme(originalTheme, true, originalIsDark); + } + } + + public void close() { + if (hasChanges()) { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), resourcesProvider); + builder.setTitle(LocaleController.getString("ChatThemeSaveDialogTitle", R.string.ChatThemeSaveDialogTitle)); + builder.setSubtitle(LocaleController.getString("ChatThemeSaveDialogText", R.string.ChatThemeSaveDialogText)); + builder.setPositiveButton(LocaleController.getString("ChatThemeSaveDialogApply", R.string.ChatThemeSaveDialogApply), (dialogInterface, i) -> applySelectedTheme()); + builder.setNegativeButton(LocaleController.getString("ChatThemeSaveDialogDiscard", R.string.ChatThemeSaveDialogDiscard), (dialogInterface, i) -> dismiss()); + builder.show(); + } else { + dismiss(); + } + } + + @SuppressLint("NotifyDataSetChanged") + @Override + public void didReceivedNotification(int id, int account, Object... args) { + if (id == NotificationCenter.emojiLoaded) { + adapter.notifyDataSetChanged(); + } + } + + @Override + public ArrayList getThemeDescriptions() { + ThemeDescription.ThemeDescriptionDelegate descriptionDelegate = new ThemeDescription.ThemeDescriptionDelegate() { + private boolean isAnimationStarted = false; + + @Override + public void onAnimationProgress(float progress) { + if (progress == 0f && !isAnimationStarted) { + onAnimationStart(); + isAnimationStarted = true; + } + setDarkButtonColor(getThemedColor(Theme.key_featuredStickers_addButton)); + setOverlayNavBarColor(getThemedColor(Theme.key_dialogBackground)); + if (isLightDarkChangeAnimation) { + setItemsAnimationProgress(progress); + } + if (progress == 1f && isAnimationStarted) { + isLightDarkChangeAnimation = false; + onAnimationEnd(); + isAnimationStarted = false; + } + } + + @Override + public void didSetColor() { + } + }; + ArrayList themeDescriptions = new ArrayList<>(); + themeDescriptions.add(new ThemeDescription(null, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, new Drawable[]{shadowDrawable}, descriptionDelegate, Theme.key_dialogBackground)); + themeDescriptions.add(new ThemeDescription(titleView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_dialogTextBlack)); + themeDescriptions.add(new ThemeDescription(recyclerView, ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{Adapter.ChatThemeView.class}, null, null, null, Theme.key_dialogBackgroundGray)); + themeDescriptions.add(new ThemeDescription(applyButton, ThemeDescription.FLAG_BACKGROUNDFILTER, null, null, null, null, Theme.key_featuredStickers_addButton)); + themeDescriptions.add(new ThemeDescription(applyButton, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_DRAWABLESELECTEDSTATE, null, null, null, null, Theme.key_featuredStickers_addButtonPressed)); + for (ThemeDescription description : themeDescriptions) { + description.resourcesProvider = themeDelegate; + } + return themeDescriptions; + } + + @SuppressLint("NotifyDataSetChanged") + public void setupLightDarkTheme(boolean isDark) { + if (changeDayNightViewAnimator != null) { + changeDayNightViewAnimator.cancel(); + } + FrameLayout decorView1 = (FrameLayout) chatActivity.getParentActivity().getWindow().getDecorView(); + FrameLayout decorView2 = (FrameLayout) getWindow().getDecorView(); + Bitmap bitmap = Bitmap.createBitmap(decorView2.getWidth(), decorView2.getHeight(), Bitmap.Config.ARGB_8888); + Canvas bitmapCanvas = new Canvas(bitmap); + darkThemeView.setAlpha(0f); + decorView1.draw(bitmapCanvas); + decorView2.draw(bitmapCanvas); + darkThemeView.setAlpha(1f); + + Paint xRefPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + xRefPaint.setColor(0xff000000); + xRefPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); + + Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + bitmapPaint.setFilterBitmap(true); + int[] position = new int[2]; + darkThemeView.getLocationInWindow(position); + float x = position[0]; + float y = position[1]; + float cx = x + darkThemeView.getMeasuredWidth() / 2f; + float cy = y + darkThemeView.getMeasuredHeight() / 2f; + + float r = Math.max(bitmap.getHeight(), bitmap.getWidth()) * 0.9f; + + Shader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + bitmapPaint.setShader(bitmapShader); + changeDayNightView = new View(getContext()) { + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + if (isDark) { + if (changeDayNightViewProgress > 0f) { + bitmapCanvas.drawCircle(cx, cy, r * changeDayNightViewProgress, xRefPaint); + } + canvas.drawBitmap(bitmap, 0, 0, bitmapPaint); + } else { + canvas.drawCircle(cx, cy, r * (1f - changeDayNightViewProgress), bitmapPaint); + } + canvas.save(); + canvas.translate(x, y); + darkThemeView.draw(canvas); + canvas.restore(); + } + }; + changeDayNightViewProgress = 0f; + changeDayNightViewAnimator = ValueAnimator.ofFloat(0, 1f); + changeDayNightViewAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { + @Override + public void onAnimationUpdate(ValueAnimator valueAnimator) { + changeDayNightViewProgress = (float) valueAnimator.getAnimatedValue(); + changeDayNightView.invalidate(); + } + }); + changeDayNightViewAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + if (changeDayNightView != null) { + if (changeDayNightView.getParent() != null) { + ((ViewGroup) changeDayNightView.getParent()).removeView(changeDayNightView); + } + changeDayNightView = null; + } + changeDayNightViewAnimator = null; + super.onAnimationEnd(animation); + } + }); + changeDayNightViewAnimator.setDuration(400); + changeDayNightViewAnimator.setInterpolator(Easings.easeInOutQuad); + changeDayNightViewAnimator.start(); + + decorView2.addView(changeDayNightView, new ViewGroup.LayoutParams(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); + + AndroidUtilities.runOnUIThread(() -> { + if (adapter == null || adapter.items == null) { + return; + } + setForceDark(isDark, true); + if (selectedItem != null) { + isLightDarkChangeAnimation = true; + if (selectedItem.chatTheme.isDefault) { + themeDelegate.setCurrentTheme(null, false, isDark); + } else { + themeDelegate.setCurrentTheme(selectedItem.chatTheme, false, isDark); + } + } + if (adapter != null && adapter.items != null) { + for (int i = 0; i < adapter.items.size(); i++) { + adapter.items.get(i).isDark = isDark; + } + adapter.notifyDataSetChanged(); + } + }); + } + + @Override + protected boolean onContainerTouchEvent(MotionEvent event) { + if (event == null || !hasChanges()) { + return false; + } + int x = (int) event.getX(); + int y = (int) event.getY(); + boolean touchInsideContainer = y >= containerView.getTop() + && x >= containerView.getLeft() + && x <= containerView.getRight(); + if (touchInsideContainer) { + return false; + } else { + chatActivity.getFragmentView().dispatchTouchEvent(event); + return true; + } + } + + private void onDataLoaded(List result) { + if (result == null || result.isEmpty()) { + return; + } + + ChatThemeItem noThemeItem = new ChatThemeItem(result.get(0)); + List items = new ArrayList<>(result.size()); + ChatTheme currentTheme = themeDelegate.getCurrentTheme(); + + items.add(0, noThemeItem); + selectedItem = noThemeItem; + + for (int i = 1; i < result.size(); ++i) { + ChatTheme chatTheme = result.get(i); + ChatThemeItem item = new ChatThemeItem(chatTheme); + + HashMap colorsMap = chatTheme.getCurrentColors(chatActivity.getCurrentAccount(), true); + Integer color = colorsMap.get(Theme.key_chat_inBubble); + if (color == null) { + color = getThemedColor(Theme.key_chat_inBubble); + } + item.inBubbleColorDark = color; + color = colorsMap.get(Theme.key_chat_outBubble); + if (color == null) { + color = getThemedColor(Theme.key_chat_outBubble); + } + item.outBubbleColorDark = color; + color = colorsMap.get(Theme.key_featuredStickers_addButton); + item.strokeColorLight = color != null ? color : 0; + + colorsMap = chatTheme.getCurrentColors(chatActivity.getCurrentAccount(), false); + color = colorsMap.get(Theme.key_chat_inBubble); + if (color == null) { + color = getThemedColor(Theme.key_chat_inBubble); + } + item.inBubbleColorLight = color; + color = colorsMap.get(Theme.key_chat_outBubble); + if (color == null) { + color = getThemedColor(Theme.key_chat_outBubble); + } + item.outBubbleColorLight = color; + color = colorsMap.get(Theme.key_featuredStickers_addButton); + item.strokeColorDark = color != null ? color : 0; + + item.isDark = forceDark; + items.add(item); + } + adapter.setItems(items); + applyButton.setEnabled(true); + applyTextView.setAlpha(0f); + resetTextView.setAlpha(0f); + recyclerView.setAlpha(0f); + + applyTextView.setVisibility(View.VISIBLE); + resetTextView.setVisibility(View.VISIBLE); + darkThemeView.setVisibility(View.VISIBLE); + + boolean showRestText = false; + if (currentTheme != null) { + int selectedPosition = -1; + for (int i = 0; i != items.size(); ++i) { + if (items.get(i).chatTheme.getEmoticon().equals(currentTheme.getEmoticon())) { + selectedItem = items.get(i); + selectedPosition = i; + break; + } + } + if (selectedPosition != -1) { + prevSelectedPosition = selectedPosition; + adapter.setSelectedItem(selectedPosition); + int finalSelectedPosition = Math.min(selectedPosition, adapter.items.size() - 1); + layoutManager.scrollToPositionWithOffset(finalSelectedPosition, 0); + } + } else { + showRestText = true; + adapter.setSelectedItem(0); + layoutManager.scrollToPositionWithOffset(0, 0); + } + + recyclerView.animate().alpha(1f).setDuration(150).start(); + resetTextView.animate().alpha(showRestText ? 1f : 0).setDuration(150).start(); + applyTextView.animate().alpha(showRestText ? 0f : 1).setDuration(150).start(); + progressView.animate().alpha(0f).setListener(new HideViewAfterAnimation(progressView)).setDuration(150).start(); + } + + private void onAnimationStart() { + if (adapter != null) { + for (ChatThemeItem item : adapter.items) { + item.isDark = forceDark; + } + } + if (!isLightDarkChangeAnimation) { + setItemsAnimationProgress(1.0f); + } + } + + private void onAnimationEnd() { + isLightDarkChangeAnimation = false; + } + + private void setDarkButtonColor(int color) { + darkThemeDrawable.setLayerColor("Sunny.**", color); + darkThemeDrawable.setLayerColor("Path.**", color); + darkThemeDrawable.setLayerColor("Path 10.**", color); + darkThemeDrawable.setLayerColor("Path 11.**", color); + } + + private void setForceDark(boolean isDark, boolean playAnimation) { + useLightNavBar = isDark; + useLightStatusBar = isDark; + if (forceDark == isDark) { + return; + } + forceDark = isDark; + if (playAnimation) { + darkThemeDrawable.setCustomEndFrame(isDark ? darkThemeDrawable.getFramesCount() : 0); + darkThemeView.playAnimation(); + } else { + darkThemeDrawable.setCurrentFrame(isDark ? darkThemeDrawable.getFramesCount() - 1 : 0, false, true); + darkThemeView.invalidate(); + } + } + + private void setItemsAnimationProgress(float progress) { + for (int i = 0; i < adapter.getItemCount(); ++i) { + adapter.items.get(i).animationProgress = progress; + } + } + + private void applySelectedTheme() { + Bulletin bulletin = null; + ChatTheme newTheme = selectedItem.chatTheme; + if (newTheme.isDefault) { + newTheme = null; + } + if (selectedItem != null && newTheme != originalTheme) { + ChatTheme chatTheme = selectedItem.chatTheme; + String emoticon = (chatTheme != null && !chatTheme.isDefault) ? chatTheme.getEmoticon() : null; + ChatThemeController.getInstance(currentAccount).setDialogTheme(chatActivity.getDialogId(), emoticon, true); + if (chatTheme != null && !chatTheme.isDefault) { + themeDelegate.setCurrentTheme(chatTheme, true, originalIsDark); + } else { + themeDelegate.setCurrentTheme(null, true, originalIsDark); + } + isApplyClicked = true; + + TLRPC.User user = chatActivity.getCurrentUser(); + if (user != null && !user.self) { + boolean themeDisabled = false; + if (TextUtils.isEmpty(emoticon)) { + themeDisabled = true; + emoticon = "❌"; + } + TLRPC.Document document = emoticon != null ? MediaDataController.getInstance(currentAccount).getEmojiAnimatedSticker(emoticon) : null; + StickerSetBulletinLayout layout = new StickerSetBulletinLayout(getContext(), null, StickerSetBulletinLayout.TYPE_EMPTY, document, chatActivity.getResourceProvider()); + layout.subtitleTextView.setVisibility(View.GONE); + if (themeDisabled) { + layout.titleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("ThemeAlsoDisabledForHint", R.string.ThemeAlsoDisabledForHint, user.first_name))); + } else { + layout.titleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("ThemeAlsoAppliedForHint", R.string.ThemeAlsoAppliedForHint, user.first_name))); + } + layout.titleTextView.setTypeface(null); + bulletin = Bulletin.make(chatActivity, layout, Bulletin.DURATION_LONG); + } + } + dismiss(); + if (bulletin != null) { + bulletin.show(); + } + } + + private boolean hasChanges() { + if (selectedItem == null) { + return false; + } else { + String oldEmoticon = originalTheme != null ? originalTheme.getEmoticon() : null; + if (TextUtils.isEmpty(oldEmoticon)) { + oldEmoticon = "❌"; + } + String newEmoticon = selectedItem.chatTheme != null ? selectedItem.chatTheme.getEmoticon() : null; + if (TextUtils.isEmpty(newEmoticon)) { + newEmoticon = "❌"; + } + return !Objects.equals(oldEmoticon, newEmoticon); + } + } + + @SuppressLint("NotifyDataSetChanged") + private class Adapter extends RecyclerView.Adapter { + + private final Theme.ResourcesProvider resourcesProvider; + + private List items; + private WeakReference selectedViewRef; + private int selectedItemPosition = -1; + + public Adapter(Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; + } + + @NonNull + @Override + public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + return new RecyclerListView.Holder(new ChatThemeView(parent.getContext(), resourcesProvider)); + } + + @Override + public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { + ChatThemeView view = (ChatThemeView) holder.itemView; + view.setItem(items.get(position)); + view.setSelected(position == selectedItemPosition); + if (position == selectedItemPosition) { + selectedViewRef = new WeakReference<>(view); + } + } + + @Override + public int getItemCount() { + return items == null ? 0 : items.size(); + } + + public void setItems(List newItems) { + items = newItems; + notifyDataSetChanged(); + } + + public void setSelectedItem(int position) { + if (selectedItemPosition == position) { + return; + } + if (selectedItemPosition >= 0) { + notifyItemChanged(selectedItemPosition); + ChatThemeView view = selectedViewRef.get(); + if (view != null) { + view.setSelected(false); + } + } + selectedItemPosition = position; + notifyItemChanged(selectedItemPosition); + } + + + private class ChatThemeView extends FrameLayout implements Animator.AnimatorListener, ValueAnimator.AnimatorUpdateListener { + + private final float STROKE_RADIUS = AndroidUtilities.dp(8); + private final float INNER_RADIUS = AndroidUtilities.dp(6); + private final float INNER_RECT_SPACE = AndroidUtilities.dp(4); + private final float BUBBLE_HEIGHT = AndroidUtilities.dp(21); + private final float BUBBLE_WIDTH = AndroidUtilities.dp(41); + + private final Paint backgroundFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint outBubblePaintFirst = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint outBubblePaintSecond = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint inBubblePaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final RectF rectF = new RectF(); + private final Path clipPath = new Path(); + private final Theme.ResourcesProvider resourcesProvider; + + private ValueAnimator strokeAlphaAnimator; + private TextPaint noThemeTextPaint; + private StaticLayout textLayout; + private ChatThemeItem chatThemeItem; + private BackupImageView backupImageView; + private boolean isDark; + private boolean hasAnimatedEmoji; + Runnable animationCancelRunnable; + + public ChatThemeView(Context context, Theme.ResourcesProvider resourcesProvider) { + super(context); + this.resourcesProvider = resourcesProvider; + strokePaint.setStyle(Paint.Style.STROKE); + strokePaint.setStrokeWidth(AndroidUtilities.dp(2)); + setBackgroundColor(getThemedColor(Theme.key_dialogBackgroundGray)); + backupImageView = new BackupImageView(context); + backupImageView.getImageReceiver().setCrossfadeWithOldImage(true); + backupImageView.getImageReceiver().setAllowStartLottieAnimation(false); + backupImageView.getImageReceiver().setAutoRepeat(0); + addView(backupImageView, LayoutHelper.createFrame(28, 28, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 0, 12)); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int height = MeasureSpec.getSize(heightMeasureSpec); + int width = AndroidUtilities.dp(77); + super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + if (w == oldw && h == oldh) { + return; + } + rectF.set(INNER_RECT_SPACE, INNER_RECT_SPACE, w - INNER_RECT_SPACE, h - INNER_RECT_SPACE); + clipPath.reset(); + clipPath.addRoundRect(rectF, INNER_RADIUS, INNER_RADIUS, Path.Direction.CW); + } + + @Override + protected void dispatchDraw(Canvas canvas) { + if (chatThemeItem == null) { + super.dispatchDraw(canvas); + return; + } + if (chatThemeItem.isSelected || strokeAlphaAnimator != null) { + float rectSpace = strokePaint.getStrokeWidth() * 0.5f; + rectF.set(rectSpace, rectSpace, getWidth() - rectSpace, getHeight() - rectSpace); + canvas.drawRoundRect(rectF, STROKE_RADIUS, STROKE_RADIUS, strokePaint); + } + rectF.set(INNER_RECT_SPACE, INNER_RECT_SPACE, getWidth() - INNER_RECT_SPACE, getHeight() - INNER_RECT_SPACE); + if (chatThemeItem.chatTheme == null || chatThemeItem.chatTheme.isDefault) { + canvas.drawRoundRect(rectF, INNER_RADIUS, INNER_RADIUS, backgroundFillPaint); + canvas.save(); + StaticLayout textLayout = getNoThemeStaticLayout(); + canvas.translate((getWidth() - textLayout.getWidth()) * 0.5f, AndroidUtilities.dp(18)); + textLayout.draw(canvas); + canvas.restore(); + } else { + if (chatThemeItem.previewDrawable != null) { + canvas.save(); + canvas.clipPath(clipPath); + chatThemeItem.previewDrawable.setBounds(0, 0, getWidth(), getHeight()); + chatThemeItem.previewDrawable.draw(canvas); + canvas.restore(); + } else { + canvas.drawRoundRect(rectF, INNER_RADIUS, INNER_RADIUS, backgroundFillPaint); + } + float bubbleTop = INNER_RECT_SPACE + AndroidUtilities.dp(8); + float bubbleLeft = INNER_RECT_SPACE + AndroidUtilities.dp(22); + rectF.set(bubbleLeft, bubbleTop, bubbleLeft + BUBBLE_WIDTH, bubbleTop + BUBBLE_HEIGHT); + canvas.drawRoundRect(rectF, rectF.height() * 0.5f, rectF.height() * 0.5f, outBubblePaintFirst); + canvas.drawRoundRect(rectF, rectF.height() * 0.5f, rectF.height() * 0.5f, outBubblePaintSecond); + bubbleLeft = INNER_RECT_SPACE + AndroidUtilities.dp(5); + bubbleTop += BUBBLE_HEIGHT + AndroidUtilities.dp(4); + rectF.set(bubbleLeft, bubbleTop, bubbleLeft + BUBBLE_WIDTH, bubbleTop + BUBBLE_HEIGHT); + canvas.drawRoundRect(rectF, rectF.height() * 0.5f, rectF.height() * 0.5f, inBubblePaint); + } + super.dispatchDraw(canvas); + } + + + public void setItem(ChatThemeItem item) { + boolean itemChanged = chatThemeItem != item; + boolean darkModeChanged = isDark != item.isDark; + isDark = item.isDark; + this.chatThemeItem = item; + hasAnimatedEmoji = false; + TLRPC.Document document = null; + if (item.chatTheme.getEmoticon() != null) { + document = MediaDataController.getInstance(currentAccount).getEmojiAnimatedSticker(item.chatTheme.getEmoticon()); + } + if (itemChanged) { + if (animationCancelRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(animationCancelRunnable); + animationCancelRunnable = null; + } + backupImageView.animate().cancel(); + backupImageView.setScaleX(1f); + backupImageView.setScaleY(1f); + } + + backupImageView.setImage(ImageLocation.getForDocument(document), "50_50", Emoji.getEmojiDrawable(item.chatTheme == null ? "❌" : item.chatTheme.getEmoticon()), null); + + if (item.chatTheme != null && !item.chatTheme.isDefault) { + updatePreviewBackground(); + if (itemChanged || darkModeChanged) { + final long themeId = item.chatTheme.getTlTheme(isDark).id; + final int intensity = item.chatTheme.getWallpaper(isDark).settings.intensity; + item.chatTheme.loadWallpaperThumb(isDark, result -> { + if (result != null && result.first == themeId) { + MotionBackgroundDrawable drawable = getPreviewDrawable(); + if (drawable != null) { + drawable.setPatternBitmap(intensity >= 0 ? 100 : -100, result.second); + drawable.setPatternColorFilter(drawable.getPatternColor()); + } + } + }); + } + } + setBackgroundColor(0); + } + + @Override + public void setSelected(boolean selected) { + super.setSelected(selected); + if (chatThemeItem.isSelected != selected) { + if (strokeAlphaAnimator != null) { + strokeAlphaAnimator.cancel(); + } + if (selected) { + strokePaint.setAlpha(0); + } + strokeAlphaAnimator = ValueAnimator.ofInt(selected ? 0 : 255, selected ? 255 : 0); + strokeAlphaAnimator.addUpdateListener(this); + strokeAlphaAnimator.addListener(this); + strokeAlphaAnimator.setDuration(350); + strokeAlphaAnimator.start(); + } + chatThemeItem.isSelected = selected; + } + + @Override + public void setBackgroundColor(int color) { + backgroundFillPaint.setColor(getThemedColor(Theme.key_dialogBackgroundGray)); + if (noThemeTextPaint != null) { + noThemeTextPaint.setColor(getThemedColor(Theme.key_chat_emojiPanelTrendingDescription)); + } + invalidate(); + } + + private void fillOutBubblePaint(Paint paint, List messageColors) { + if (messageColors.size() > 1) { + int[] colors = new int[messageColors.size()]; + for (int i = 0; i != messageColors.size(); ++i) { + colors[i] = messageColors.get(i); + } + float top = INNER_RECT_SPACE + AndroidUtilities.dp(8); + paint.setShader(new LinearGradient(0f, top, 0f, top + BUBBLE_HEIGHT, colors, null, Shader.TileMode.CLAMP)); + } else { + paint.setShader(null); + } + } + + public void updatePreviewBackground() { + if (chatThemeItem == null || chatThemeItem.chatTheme == null || chatThemeItem.chatTheme.isDefault) { + return; + } + int color = chatThemeItem.isDark ? chatThemeItem.inBubbleColorDark : chatThemeItem.inBubbleColorLight; + inBubblePaint.setColor(color); + color = chatThemeItem.isDark ? chatThemeItem.outBubbleColorDark : chatThemeItem.outBubbleColorLight; + outBubblePaintSecond.setColor(color); + + TLRPC.TL_theme firstTlTheme = chatThemeItem.chatTheme.getTlTheme(!chatThemeItem.isDark); + fillOutBubblePaint(outBubblePaintFirst, firstTlTheme.settings.message_colors); + TLRPC.TL_theme secondTlTheme = chatThemeItem.chatTheme.getTlTheme(chatThemeItem.isDark); + fillOutBubblePaint(outBubblePaintSecond, secondTlTheme.settings.message_colors); + outBubblePaintSecond.setAlpha(255); + + MotionBackgroundDrawable drawable = getPreviewDrawable(); + if (drawable != null) { + TLRPC.WallPaperSettings secondSettings = secondTlTheme.settings.wallpaper.settings; + int color1 = 0xff000000 | secondSettings.background_color; + if (color1 == 0xff000000) { + color1 = Color.TRANSPARENT; + } + int color2 = 0xff000000 | secondSettings.second_background_color; + if (color2 == 0xff000000) { + color2 = Color.TRANSPARENT; + } + int color3 = 0xff000000 | secondSettings.third_background_color; + if (color3 == 0xff000000) { + color3 = Color.TRANSPARENT; + } + int color4 = 0xff000000 | secondSettings.fourth_background_color; + if (color4 == 0xff000000) { + color4 = Color.TRANSPARENT; + } + drawable.setPatternBitmap(secondSettings.intensity >= 0 ? 100 : -100); + drawable.setColors(color1, color2, color3, color4, false); + drawable.setPatternColorFilter(drawable.getPatternColor()); + } + invalidate(); + } + + private MotionBackgroundDrawable getPreviewDrawable() { + if (chatThemeItem == null) { + return null; + } + MotionBackgroundDrawable drawable = chatThemeItem.previewDrawable; + if (drawable == null) { + drawable = new MotionBackgroundDrawable(); + chatThemeItem.previewDrawable = drawable; + } + return drawable; + } + + private StaticLayout getNoThemeStaticLayout() { + if (textLayout != null) { + return textLayout; + } + noThemeTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG + TextPaint.SUBPIXEL_TEXT_FLAG); + noThemeTextPaint.setColor(getThemedColor(Theme.key_chat_emojiPanelTrendingDescription)); + noThemeTextPaint.setTextSize(AndroidUtilities.dp(14)); + noThemeTextPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + textLayout = StaticLayoutEx.createStaticLayout2( + LocaleController.getString("NoTheme", R.string.ChatNoTheme), + noThemeTextPaint, + AndroidUtilities.dp(52), + Layout.Alignment.ALIGN_CENTER, + 1f, 0f, true, + TextUtils.TruncateAt.END, AndroidUtilities.dp(52), 3 + ); + return textLayout; + } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + @Override + public void onAnimationUpdate(ValueAnimator valueAnimator) { + int strokeColor = chatThemeItem.chatTheme.isDefault + ? getThemedColor(Theme.key_featuredStickers_addButton) + : chatThemeItem.isDark ? chatThemeItem.strokeColorDark : chatThemeItem.strokeColorLight; + strokePaint.setColor(strokeColor); + strokePaint.setAlpha((int) valueAnimator.getAnimatedValue()); + invalidate(); + } + + @Override + public void onAnimationEnd(Animator animator) { + strokeAlphaAnimator = null; + invalidate(); + } + + @Override + public void onAnimationCancel(Animator animator) { + strokeAlphaAnimator = null; + invalidate(); + } + + @Override + public void onAnimationStart(Animator animator) { + } + + @Override + public void onAnimationRepeat(Animator animator) { + } + + public void playEmojiAnimation() { + if (backupImageView.getImageReceiver().getLottieAnimation() != null) { + AndroidUtilities.cancelRunOnUIThread(animationCancelRunnable); + backupImageView.setVisibility(View.VISIBLE); + backupImageView.getImageReceiver().getLottieAnimation().setCurrentFrame(0, false); + backupImageView.getImageReceiver().getLottieAnimation().start(); + backupImageView.setPivotY(AndroidUtilities.dp(24)); + backupImageView.setPivotX(AndroidUtilities.dp(12)); + backupImageView.animate().scaleX(2f).scaleY(2f).setDuration(300).setInterpolator(AndroidUtilities.overshootInterpolator).start(); + + AndroidUtilities.runOnUIThread(animationCancelRunnable = () -> { + animationCancelRunnable = null; + backupImageView.animate().scaleX(1f).scaleY(1f).setDuration(150).setInterpolator(CubicBezierInterpolator.DEFAULT).start(); + }, 2500); + } + } + + public void cancelAnimation() { + if (animationCancelRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(animationCancelRunnable); + animationCancelRunnable.run(); + } + } + } + } + + private static class ChatThemeItem { + + public final ChatTheme chatTheme; + public MotionBackgroundDrawable previewDrawable; + public boolean isDark; + public boolean isSelected; + public float animationProgress = 1f; + public int inBubbleColorLight; + public int inBubbleColorDark; + public int outBubbleColorLight; + public int outBubbleColorDark; + public int strokeColorDark; + public int strokeColorLight; + + public ChatThemeItem(ChatTheme chatTheme) { + this.chatTheme = chatTheme; + } + } + + @Override + public void show() { + super.show(); + resetTextView.setText(themeDelegate.getCurrentTheme() == null ? LocaleController.getString("DoNoSetTheme", R.string.DoNoSetTheme) : LocaleController.getString("ChatResetTheme", R.string.ChatResetTheme)); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBox2.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBox2.java index 5cfc7d680..d2e824e95 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBox2.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBox2.java @@ -6,14 +6,19 @@ import android.view.View; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.CheckBox; +import org.telegram.ui.ActionBar.Theme; + public class CheckBox2 extends View { private CheckBoxBase checkBoxBase; public CheckBox2(Context context, int sz) { - super(context); + this(context, sz, null); + } - checkBoxBase = new CheckBoxBase(this, sz); + public CheckBox2(Context context, int sz, Theme.ResourcesProvider resourcesProvider) { + super(context); + checkBoxBase = new CheckBoxBase(this, sz, resourcesProvider); } public void setProgressDelegate(CheckBoxBase.ProgressDelegate delegate) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxBase.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxBase.java index 401326002..fbc0dd657 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxBase.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxBase.java @@ -66,16 +66,14 @@ public class CheckBoxBase { private ProgressDelegate progressDelegate; private Theme.MessageDrawable messageDrawable; + private final Theme.ResourcesProvider resourcesProvider; public interface ProgressDelegate { void setProgress(float progress); } - public CheckBoxBase(View parent) { - this(parent, 21); - } - - public CheckBoxBase(View parent, int sz) { + public CheckBoxBase(View parent, int sz, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; parentView = parent; size = sz; if (paint == null) { @@ -269,35 +267,35 @@ public class CheckBoxBase { if (backgroundColorKey != null) { if (drawUnchecked) { if (backgroundType == 12 || backgroundType == 13) { - paint.setColor(Theme.getColor(backgroundColorKey)); + paint.setColor(getThemedColor(backgroundColorKey)); paint.setAlpha((int) (255 * backgroundAlpha)); - backgroundPaint.setColor(Theme.getColor(checkColorKey)); + backgroundPaint.setColor(getThemedColor(checkColorKey)); } else if (backgroundType == 6 || backgroundType == 7) { - paint.setColor(Theme.getColor(background2ColorKey)); - backgroundPaint.setColor(Theme.getColor(checkColorKey)); + paint.setColor(getThemedColor(background2ColorKey)); + backgroundPaint.setColor(getThemedColor(checkColorKey)); } else if (backgroundType == 10) { - backgroundPaint.setColor(Theme.getColor(background2ColorKey)); + backgroundPaint.setColor(getThemedColor(background2ColorKey)); } else { paint.setColor((Theme.getServiceMessageColor() & 0x00ffffff) | 0x28000000); - backgroundPaint.setColor(Theme.getColor(checkColorKey)); + backgroundPaint.setColor(getThemedColor(checkColorKey)); } } else { - backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0x00ffffff, Theme.getColor(background2ColorKey != null ? background2ColorKey : checkColorKey), progress, backgroundAlpha)); + backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0x00ffffff, getThemedColor(background2ColorKey != null ? background2ColorKey : checkColorKey), progress, backgroundAlpha)); } } else { if (drawUnchecked) { paint.setColor(Color.argb((int) (25 * backgroundAlpha), 0, 0, 0)); if (backgroundType == 8) { - backgroundPaint.setColor(Theme.getColor(background2ColorKey)); + backgroundPaint.setColor(getThemedColor(background2ColorKey)); } else { - backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0xffffffff, Theme.getColor(checkColorKey), progress, backgroundAlpha)); + backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0xffffffff, getThemedColor(checkColorKey), progress, backgroundAlpha)); } } else { - backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0x00ffffff, Theme.getColor(background2ColorKey != null ? background2ColorKey : checkColorKey), progress, backgroundAlpha)); + backgroundPaint.setColor(AndroidUtilities.getOffsetColor(0x00ffffff, getThemedColor(background2ColorKey != null ? background2ColorKey : checkColorKey), progress, backgroundAlpha)); } } - if (drawUnchecked) { + if (drawUnchecked && backgroundType >= 0) { if (backgroundType == 12 || backgroundType == 13) { //draw nothing } else if (backgroundType == 8 || backgroundType == 10) { @@ -309,8 +307,8 @@ public class CheckBoxBase { canvas.drawCircle(cx, cy, rad, paint); } } - paint.setColor(Theme.getColor(checkColorKey)); - if (backgroundType != 7 && backgroundType != 8 && backgroundType != 9 && backgroundType != 10) { + paint.setColor(getThemedColor(checkColorKey)); + if (backgroundType != -1 && backgroundType != 7 && backgroundType != 8 && backgroundType != 9 && backgroundType != 10) { if (backgroundType == 12 || backgroundType == 13) { backgroundPaint.setStyle(Paint.Style.FILL); if (messageDrawable != null && messageDrawable.hasGradient()) { @@ -344,12 +342,12 @@ public class CheckBoxBase { } if (backgroundType == 6) { - int color = Theme.getColor(Theme.key_dialogBackground); + int color = getThemedColor(Theme.key_dialogBackground); int alpha = Color.alpha(color); backgroundPaint.setColor(color); backgroundPaint.setAlpha((int) (alpha * progress)); canvas.drawArc(rect, startAngle, sweepAngle, false, backgroundPaint); - color = Theme.getColor(Theme.key_chat_attachPhotoBackground); + color = getThemedColor(Theme.key_chat_attachPhotoBackground); alpha = Color.alpha(color); backgroundPaint.setColor(color); backgroundPaint.setAlpha((int) (alpha * progress)); @@ -362,28 +360,29 @@ public class CheckBoxBase { float checkProgress = progress < 0.5f ? 0.0f : (progress - 0.5f) / 0.5f; if (backgroundType == 9) { - paint.setColor(Theme.getColor(background2ColorKey)); + paint.setColor(getThemedColor(background2ColorKey)); } else if (backgroundType == 11 || backgroundType == 6 || backgroundType == 7 || backgroundType == 10 || !drawUnchecked && backgroundColorKey != null) { - paint.setColor(Theme.getColor(backgroundColorKey)); + paint.setColor(getThemedColor(backgroundColorKey)); } else { - paint.setColor(Theme.getColor(enabled ? Theme.key_checkbox : Theme.key_checkboxDisabled)); + paint.setColor(getThemedColor(enabled ? Theme.key_checkbox : Theme.key_checkboxDisabled)); } if (!useDefaultCheck && checkColorKey != null) { - checkPaint.setColor(Theme.getColor(checkColorKey)); + checkPaint.setColor(getThemedColor(checkColorKey)); } else { - checkPaint.setColor(Theme.getColor(Theme.key_checkboxCheck)); + checkPaint.setColor(getThemedColor(Theme.key_checkboxCheck)); } - if (backgroundType == 12 || backgroundType == 13) { - paint.setAlpha((int) (255 * roundProgress)); - bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad * roundProgress, paint); - } else { - rad -= AndroidUtilities.dp(0.5f); - bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad, paint); - bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad * (1.0f - roundProgress), eraser); + if (backgroundType != -1) { + if (backgroundType == 12 || backgroundType == 13) { + paint.setAlpha((int) (255 * roundProgress)); + bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad * roundProgress, paint); + } else { + rad -= AndroidUtilities.dp(0.5f); + bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad, paint); + bitmapCanvas.drawCircle(drawBitmap.getWidth() / 2, drawBitmap.getHeight() / 2, rad * (1.0f - roundProgress), eraser); + } + canvas.drawBitmap(drawBitmap, cx - drawBitmap.getWidth() / 2, cy - drawBitmap.getHeight() / 2, null); } - canvas.drawBitmap(drawBitmap, cx - drawBitmap.getWidth() / 2, cy - drawBitmap.getHeight() / 2, null); - if (checkProgress != 0) { if (checkedText != null) { if (textPaint == null) { @@ -407,15 +406,19 @@ public class CheckBoxBase { y = 15.75f; } textPaint.setTextSize(AndroidUtilities.dp(textSize)); - textPaint.setColor(Theme.getColor(checkColorKey)); + textPaint.setColor(getThemedColor(checkColorKey)); canvas.save(); canvas.scale(checkProgress, 1.0f, cx, cy); canvas.drawText(checkedText, cx - textPaint.measureText(checkedText) / 2f, AndroidUtilities.dp(y), textPaint); canvas.restore(); } else { path.reset(); - - float scale = backgroundType == 5 ? 0.8f : 1.0f; + float scale = 1f; + if (backgroundType == -1) { + scale = 1.4f; + } else if (backgroundType == 5) { + scale = 0.8f; + } float checkSide = AndroidUtilities.dp(9 * scale) * checkProgress; float smallCheckSide = AndroidUtilities.dp(4 * scale) * checkProgress; int x = cx - AndroidUtilities.dp(1.5f); @@ -430,4 +433,9 @@ public class CheckBoxBase { } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxSquare.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxSquare.java index a8758e1b7..5e8286673 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxSquare.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/CheckBoxSquare.java @@ -40,9 +40,15 @@ public class CheckBoxSquare extends View { private String key1; private String key2; private String key3; + private final Theme.ResourcesProvider resourcesProvider; public CheckBoxSquare(Context context, boolean alert) { + this(context, alert, null); + } + + public CheckBoxSquare(Context context, boolean alert, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; if (Theme.checkboxSquare_backgroundPaint == null) { Theme.createCommonResources(context); } @@ -136,8 +142,8 @@ public class CheckBoxSquare extends View { float checkProgress; float bounceProgress; - int uncheckedColor = Theme.getColor(key1); - int color = Theme.getColor(key2); + int uncheckedColor = getThemedColor(key1); + int color = getThemedColor(key2); if (progress <= 0.5f) { bounceProgress = checkProgress = progress / 0.5f; int rD = (int) ((Color.red(color) - Color.red(uncheckedColor)) * checkProgress); @@ -151,7 +157,7 @@ public class CheckBoxSquare extends View { Theme.checkboxSquare_backgroundPaint.setColor(color); } if (isDisabled) { - Theme.checkboxSquare_backgroundPaint.setColor(Theme.getColor(isAlert ? Theme.key_dialogCheckboxSquareDisabled : Theme.key_checkboxSquareDisabled)); + Theme.checkboxSquare_backgroundPaint.setColor(getThemedColor(isAlert ? Theme.key_dialogCheckboxSquareDisabled : Theme.key_checkboxSquareDisabled)); } float bounce = AndroidUtilities.dp(1) * bounceProgress; rectF.set(bounce, bounce, AndroidUtilities.dp(18) - bounce, AndroidUtilities.dp(18) - bounce); @@ -166,7 +172,7 @@ public class CheckBoxSquare extends View { } if (progress > 0.5f) { - Theme.checkboxSquare_checkPaint.setColor(Theme.getColor(key3)); + Theme.checkboxSquare_checkPaint.setColor(getThemedColor(key3)); int endX = (int) (AndroidUtilities.dp(7) - AndroidUtilities.dp(3) * (1.0f - bounceProgress)); int endY = (int) (AndroidUtilities.dpf2(13) - AndroidUtilities.dp(3) * (1.0f - bounceProgress)); @@ -178,4 +184,9 @@ public class CheckBoxSquare extends View { } canvas.drawBitmap(drawBitmap, 0, 0, null); } + + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChecksHintView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChecksHintView.java index c7c2d7e8f..aa71a4101 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChecksHintView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChecksHintView.java @@ -35,12 +35,14 @@ public class ChecksHintView extends FrameLayout { private float translationY; private long showingDuration = 2000; + private final Theme.ResourcesProvider resourcesProvider; - public ChecksHintView(Context context) { + public ChecksHintView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; FrameLayout backgroundView = new FrameLayout(context); - backgroundView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_chat_gifSaveHintBackground))); + backgroundView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(6), getThemedColor(Theme.key_chat_gifSaveHintBackground))); backgroundView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8)); addView(backgroundView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 6)); @@ -50,7 +52,7 @@ public class ChecksHintView extends FrameLayout { backgroundView.addView(imageView[a], LayoutHelper.createFrame(24, 24, Gravity.LEFT | Gravity.TOP, 0, a == 0 ? 0 : 24, 0, 0)); textView[a] = new TextView(context); - textView[a].setTextColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); + textView[a].setTextColor(getThemedColor(Theme.key_chat_gifSaveHintText)); textView[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView[a].setMaxLines(1); textView[a].setSingleLine(true); @@ -71,7 +73,7 @@ public class ChecksHintView extends FrameLayout { arrowImageView = new ImageView(context); arrowImageView.setImageResource(R.drawable.tooltip_arrow); - arrowImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); + arrowImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); addView(arrowImageView, LayoutHelper.createFrame(14, 6, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 0)); } @@ -206,4 +208,9 @@ public class ChecksHintView extends FrameLayout { animatorSet.setDuration(180); animatorSet.start(); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChoosingStickerStatusDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChoosingStickerStatusDrawable.java index 3353f3b18..8b6c9db10 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChoosingStickerStatusDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChoosingStickerStatusDrawable.java @@ -20,6 +20,7 @@ public class ChoosingStickerStatusDrawable extends StatusDrawable { private boolean started = false; float progress; boolean increment = true; + int color; public ChoosingStickerStatusDrawable(boolean createPaint) { if (createPaint) { @@ -49,8 +50,11 @@ public class ChoosingStickerStatusDrawable extends StatusDrawable { @Override public void setColor(int color) { - fillPaint.setColor(color); - strokePaint.setColor(color); + if (this.color != color) { + fillPaint.setColor(color); + strokePaint.setColor(color); + } + this.color = color; } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ClearHistoryAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ClearHistoryAlert.java index b5045fc2c..c062a4e8e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ClearHistoryAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ClearHistoryAlert.java @@ -75,12 +75,14 @@ public class ClearHistoryAlert extends BottomSheet { private View background; private TextView textView; private LinearLayout linearLayout; + private final Theme.ResourcesProvider resourcesProvider; - public BottomSheetCell(Context context) { + public BottomSheetCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; background = new View(context); - background.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + background.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); addView(background, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 16, 16, 16, 16)); textView = new TextView(context); @@ -89,7 +91,7 @@ public class ClearHistoryAlert extends BottomSheet { textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setGravity(Gravity.CENTER); - textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + textView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); @@ -103,10 +105,15 @@ public class ClearHistoryAlert extends BottomSheet { public void setText(CharSequence text) { textView.setText(text); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } - public ClearHistoryAlert(final Context context, TLRPC.User user, TLRPC.Chat chat, boolean full) { - super(context, false); + public ClearHistoryAlert(final Context context, TLRPC.User user, TLRPC.Chat chat, boolean full, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); autoDeleteOnly = !full; setApplyBottomPadding(false); @@ -129,7 +136,7 @@ public class ClearHistoryAlert extends BottomSheet { } shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); NestedScrollView scrollView = new NestedScrollView(context) { @@ -222,7 +229,7 @@ public class ClearHistoryAlert extends BottomSheet { scrollView.addView(linearLayout, LayoutHelper.createScroll(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM)); setCustomView(linearLayout); - int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); boolean canRevokeInbox = user != null && !user.bot && user.id != selfUserId && MessagesController.getInstance(currentAccount).canRevokePmInbox; int revokeTimeLimit; @@ -239,17 +246,17 @@ public class ClearHistoryAlert extends BottomSheet { TextView textView = new TextView(context); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setText(LocaleController.getString("ClearHistory", R.string.ClearHistory)); textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 23, 20, 23, 0)); TextView messageTextView = new TextView(getContext()); - messageTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + messageTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); messageTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); - messageTextView.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink)); + messageTextView.setLinkTextColor(getThemedColor(Theme.key_dialogTextLink)); messageTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); linearLayout.addView(messageTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 23, 16, 23, 5)); if (user != null) { @@ -265,7 +272,7 @@ public class ClearHistoryAlert extends BottomSheet { } if (canDeleteInbox && !UserObject.isDeleted(user)) { - cell = new CheckBoxCell(context, 1); + cell = new CheckBoxCell(context, 1, resourcesProvider); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); cell.setText(LocaleController.formatString("ClearHistoryOptionAlso", R.string.ClearHistoryOptionAlso, UserObject.getFirstName(user)), "", false, false); cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(5), 0, LocaleController.isRTL ? AndroidUtilities.dp(5) : AndroidUtilities.dp(16), 0); @@ -277,7 +284,7 @@ public class ClearHistoryAlert extends BottomSheet { }); } - BottomSheetCell clearButton = new BottomSheetCell(context); + BottomSheetCell clearButton = new BottomSheetCell(context, resourcesProvider); clearButton.setBackground(null); clearButton.setText(LocaleController.getString("AlertClearHistory", R.string.AlertClearHistory)); clearButton.background.setOnClickListener(v -> { @@ -291,12 +298,12 @@ public class ClearHistoryAlert extends BottomSheet { ShadowSectionCell shadowSectionCell = new ShadowSectionCell(context); Drawable drawable = Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); shadowSectionCell.setBackgroundDrawable(combinedDrawable); linearLayout.addView(shadowSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - HeaderCell headerCell = new HeaderCell(context); + HeaderCell headerCell = new HeaderCell(context, resourcesProvider); headerCell.setText(LocaleController.getString("AutoDeleteHeader", R.string.AutoDeleteHeader)); linearLayout.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 1, autoDeleteOnly ? 20 : 0, 1, 0)); } else { @@ -310,13 +317,13 @@ public class ClearHistoryAlert extends BottomSheet { TextView percentTextView = new TextView(context); percentTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); percentTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24); - percentTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + percentTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); percentTextView.setText(LocaleController.getString("AutoDeleteAlertTitle", R.string.AutoDeleteAlertTitle)); linearLayout.addView(percentTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 17, 18, 17, 0)); TextView infoTextView = new TextView(context); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - infoTextView.setTextColor(Theme.getColor(Theme.key_dialogTextGray3)); + infoTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray3)); infoTextView.setGravity(Gravity.CENTER_HORIZONTAL); if (user != null) { infoTextView.setText(LocaleController.formatString("AutoDeleteAlertUserInfo", R.string.AutoDeleteAlertUserInfo, UserObject.getFirstName(user))); @@ -330,7 +337,7 @@ public class ClearHistoryAlert extends BottomSheet { linearLayout.addView(infoTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 30, 22, 30, 20)); } - SlideChooseView slideChooseView = new SlideChooseView(context); + SlideChooseView slideChooseView = new SlideChooseView(context, resourcesProvider); slideChooseView.setCallback(new SlideChooseView.Callback() { @Override public void onOptionSelected(int index) { @@ -354,18 +361,18 @@ public class ClearHistoryAlert extends BottomSheet { FrameLayout buttonContainer = new FrameLayout(context); Drawable drawable = Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow); - CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable); + CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable); combinedDrawable.setFullsize(true); buttonContainer.setBackgroundDrawable(combinedDrawable); linearLayout.addView(buttonContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); + TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context, resourcesProvider); infoCell.setText(LocaleController.getString("AutoDeleteInfo", R.string.AutoDeleteInfo)); buttonContainer.addView(infoCell); - setTimerButton = new BottomSheetCell(context); - setTimerButton.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + setTimerButton = new BottomSheetCell(context, resourcesProvider); + setTimerButton.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); if (autoDeleteOnly) { setTimerButton.setText(LocaleController.getString("AutoDeleteSet", R.string.AutoDeleteSet)); } else if (full && currentTimer == 0) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ColorPicker.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ColorPicker.java index b5b18f6b5..976f85180 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ColorPicker.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ColorPicker.java @@ -82,6 +82,7 @@ public class ColorPicker extends FrameLayout { private int currentResetType; private int colorsCount = 1; + private int maxColorsCount = 1; private int colorWheelWidth; @@ -407,12 +408,6 @@ public class ColorPicker extends FrameLayout { } delegate.setColor(radioButton[1].getColor(), 1, true); colorsCount = 2; - clearButton.setVisibility(VISIBLE); - animators = new ArrayList<>(); - animators.add(ObjectAnimator.ofFloat(clearButton, View.ALPHA, 1.0f)); - animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_X, 1.0f)); - animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_Y, 1.0f)); - animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) + AndroidUtilities.dp(13))); } else if (colorsCount == 2) { colorsCount = 3; if (radioButton[2].getColor() == 0) { @@ -426,8 +421,6 @@ public class ColorPicker extends FrameLayout { } radioButton[2].setColor(Color.HSVToColor(255, hsv)); } - animators = new ArrayList<>(); - animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) * 2 + AndroidUtilities.dp(13) * 2)); delegate.setColor(radioButton[2].getColor(), 2, true); } else if (colorsCount == 3) { colorsCount = 4; @@ -435,14 +428,35 @@ public class ColorPicker extends FrameLayout { radioButton[3].setColor(generateGradientColors(radioButton[2].getColor())); } delegate.setColor(radioButton[3].getColor(), 3, true); - animators = new ArrayList<>(); - animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) * 3 + AndroidUtilities.dp(13) * 3)); - animators.add(ObjectAnimator.ofFloat(addButton, View.ALPHA, 0.0f)); - animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_X, 0.0f)); - animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_Y, 0.0f)); } else { return; } + + animators = new ArrayList<>(); + if (colorsCount < maxColorsCount) { + animators.add(ObjectAnimator.ofFloat(addButton, View.ALPHA, 1.0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_X, 1.0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_Y, 1.0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) * (colorsCount - 1) + AndroidUtilities.dp(13) * (colorsCount - 1))); + } else { + animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) * (colorsCount - 1) + AndroidUtilities.dp(13) * (colorsCount - 1))); + animators.add(ObjectAnimator.ofFloat(addButton, View.ALPHA, 0.0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_X, 0.0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_Y, 0.0f)); + } + + if (colorsCount > 1) { + if (clearButton.getVisibility() != View.VISIBLE) { + clearButton.setScaleX(0f); + clearButton.setScaleY(0f); + } + clearButton.setVisibility(VISIBLE); + + animators.add(ObjectAnimator.ofFloat(clearButton, View.ALPHA, 1.0f)); + animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_X, 1.0f)); + animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_Y, 1.0f)); + } + radioButton[colorsCount - 1].callOnClick(); colorsAnimator = new AnimatorSet(); updateColorsPosition(animators, 0, false, getMeasuredWidth()); @@ -452,7 +466,7 @@ public class ColorPicker extends FrameLayout { colorsAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - if (colorsCount == 4) { + if (colorsCount == maxColorsCount) { addButton.setVisibility(INVISIBLE); } colorsAnimator = null; @@ -482,28 +496,31 @@ public class ColorPicker extends FrameLayout { if (colorsAnimator != null) { return; } - ArrayList animators; + ArrayList animators = new ArrayList<>(); if (colorsCount == 2) { colorsCount = 1; - animators = new ArrayList<>(); animators.add(ObjectAnimator.ofFloat(clearButton, View.ALPHA, 0.0f)); animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_X, 0.0f)); animators.add(ObjectAnimator.ofFloat(clearButton, View.SCALE_Y, 0.0f)); animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, 0)); } else if (colorsCount == 3) { colorsCount = 2; - animators = new ArrayList<>(); animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) + AndroidUtilities.dp(13))); } else if (colorsCount == 4) { colorsCount = 3; - addButton.setVisibility(VISIBLE); - animators = new ArrayList<>(); animators.add(ObjectAnimator.ofFloat(addButton, View.TRANSLATION_X, AndroidUtilities.dp(30) * 2 + AndroidUtilities.dp(13) * 2)); + } else { + return; + } + if (colorsCount < maxColorsCount) { + addButton.setVisibility(VISIBLE); animators.add(ObjectAnimator.ofFloat(addButton, View.ALPHA, 1.0f)); animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_X, 1.0f)); animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_Y, 1.0f)); } else { - return; + animators.add(ObjectAnimator.ofFloat(addButton, View.ALPHA, 0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_X, 0f)); + animators.add(ObjectAnimator.ofFloat(addButton, View.SCALE_Y, 0f)); } if (selectedColor != 3) { RadioButton button = radioButton[selectedColor]; @@ -888,7 +905,14 @@ public class ColorPicker extends FrameLayout { animatorSet.start(); } - public void setType(int resetType, boolean hasChanges, boolean fewColors, int newColorsCount, boolean myMessages, int angle, boolean animated) { + public void setType(int resetType, boolean hasChanges, int maxColorsCount, int newColorsCount, boolean myMessages, int angle, boolean animated) { + if (resetType != currentResetType) { + selectedColor = 0; + for (int i = 0; i < 4; i++) { + radioButton[i].setChecked(i == selectedColor, true); + } + } + this.maxColorsCount = maxColorsCount; currentResetType = resetType; myMessagesColor = myMessages; colorsCount = newColorsCount; @@ -906,17 +930,16 @@ public class ColorPicker extends FrameLayout { if (menuItem != null) { if (resetType == 1) { menuItem.setVisibility(VISIBLE); - clearButton.setTranslationX(-AndroidUtilities.dp(40)); } else { menuItem.setVisibility(GONE); clearButton.setTranslationX(0); } } - if (!fewColors) { + if (maxColorsCount <= 1) { addButton.setVisibility(GONE); clearButton.setVisibility(GONE); } else { - if (newColorsCount < 4) { + if (newColorsCount < maxColorsCount) { addButton.setVisibility(VISIBLE); addButton.setScaleX(1.0f); addButton.setScaleY(1.0f); @@ -950,7 +973,7 @@ public class ColorPicker extends FrameLayout { animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - if (!fewColors) { + if (maxColorsCount <= 1) { clearButton.setVisibility(GONE); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ContactsEmptyView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ContactsEmptyView.java index e52f6b7f8..6e9467e4a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ContactsEmptyView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ContactsEmptyView.java @@ -39,7 +39,7 @@ public class ContactsEmptyView extends LinearLayout implements NotificationCente private int currentAccount = UserConfig.selectedAccount; - private static final String stickerSetName = "tg_placeholders"; + private static final String stickerSetName = AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME; public static final String svg = "m418 282.6c13.4-21.1 20.2-44.9 20.2-70.8 0-88.3-79.8-175.3-178.9-175.3-100.1 0-178.9 88-178.9 175.3 0 46.6 16.9 73.1 29.1 86.1-19.3 23.4-30.9 52.3-34.6 86.1-2.5 22.7 3.2 41.4 17.4 57.3 14.3 16 51.7 35 148.1 35 41.2 0 119.9-5.3 156.7-18.3 49.5-17.4 59.2-41.1 59.2-76.2 0-41.5-12.9-74.8-38.3-99.2z"; public ContactsEmptyView(Context context) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/CounterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/CounterView.java index f917f5a30..c82fcf826 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/CounterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/CounterView.java @@ -23,11 +23,14 @@ import org.telegram.ui.ActionBar.Theme; public class CounterView extends View { - public CounterDrawable counterDrawable = new CounterDrawable(this); + public CounterDrawable counterDrawable; + private final Theme.ResourcesProvider resourcesProvider; - public CounterView(Context context) { + public CounterView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setVisibility(View.GONE); + counterDrawable = new CounterDrawable(this, resourcesProvider); counterDrawable.updateVisibility = true; } @@ -61,6 +64,11 @@ public class CounterView extends View { counterDrawable.setCount(count, animated); } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + public static class CounterDrawable { private final static int ANIMATION_TYPE_IN = 0; @@ -72,6 +80,7 @@ public class CounterView extends View { public Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); public TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); public RectF rectF = new RectF(); + public boolean addServiceGradient; int currentCount; private boolean countAnimationIncrement; @@ -107,9 +116,11 @@ public class CounterView extends View { public final static int TYPE_CHAT_PULLING_DOWN = 1; int type = TYPE_DEFAULT; + private final Theme.ResourcesProvider resourcesProvider; - public CounterDrawable(View parent) { + public CounterDrawable(View parent, Theme.ResourcesProvider resourcesProvider) { this.parent = parent; + this.resourcesProvider = resourcesProvider; circlePaint.setColor(Color.BLACK); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textPaint.setTextSize(AndroidUtilities.dp(13)); @@ -131,7 +142,7 @@ public class CounterView extends View { updateX(countWidth); rectF.set(x, countTop, x + countWidth + AndroidUtilities.dp(11), countTop + AndroidUtilities.dp(23)); canvas.drawRoundRect(rectF, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, circlePaint); - if (Theme.hasGradientService()) { + if (addServiceGradient && Theme.hasGradientService()) { canvas.drawRoundRect(rectF, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, Theme.chat_actionBackgroundGradientDarkenPaint); } if (countLayout != null) { @@ -254,8 +265,8 @@ public class CounterView extends View { public void draw(Canvas canvas) { if (type != TYPE_CHAT_PULLING_DOWN) { - int textColor = Theme.getColor(textColorKey); - int circleColor = Theme.getColor(circleColorKey); + int textColor = getThemedColor(textColorKey); + int circleColor = getThemedColor(circleColorKey); if (this.textColor != textColor) { this.textColor = textColor; textPaint.setColor(textColor); @@ -303,7 +314,7 @@ public class CounterView extends View { canvas.save(); canvas.scale(scale, scale, rectF.centerX(), rectF.centerY()); canvas.drawRoundRect(rectF, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, circlePaint); - if (Theme.hasGradientService()) { + if (addServiceGradient && Theme.hasGradientService()) { canvas.drawRoundRect(rectF, 11.5f * AndroidUtilities.density, 11.5f * AndroidUtilities.density, Theme.chat_actionBackgroundGradientDarkenPaint); } canvas.clipRect(rectF); @@ -402,5 +413,10 @@ public class CounterView extends View { public void setParent(View parent) { this.parent = parent; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextBoldCursor.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextBoldCursor.java index e778e5600..45166cf92 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextBoldCursor.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextBoldCursor.java @@ -49,6 +49,7 @@ import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.FloatingActionMode; import org.telegram.ui.ActionBar.FloatingToolbar; +import org.telegram.ui.ActionBar.Theme; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -747,7 +748,7 @@ public class EditTextBoldCursor extends EditText { linePaint.setColor(lineColor); h = AndroidUtilities.dp(1); } - canvas.drawRect(getScrollX(), (int) lineY, getScrollX() + getMeasuredWidth(), lineY + h, linePaint); + // canvas.drawRect(getScrollX(), (int) lineY, getScrollX() + getMeasuredWidth(), lineY + h, linePaint); } /*if (errorLayout != null) { canvas.save(); @@ -849,7 +850,7 @@ public class EditTextBoldCursor extends EditText { floatingActionMode.finish(); } cleanupFloatingActionModeViews(); - floatingToolbar = new FloatingToolbar(getContext(), windowView != null ? windowView : attachedToWindow, getActionModeStyle()); + floatingToolbar = new FloatingToolbar(getContext(), windowView != null ? windowView : attachedToWindow, getActionModeStyle(), getResourcesProvider()); floatingActionMode = new FloatingActionMode(getContext(), new ActionModeCallback2Wrapper(callback), this, floatingToolbar); floatingToolbarPreDrawListener = () -> { if (floatingActionMode != null) { @@ -915,4 +916,8 @@ public class EditTextBoldCursor extends EditText { AccessibilityNodeInfoCompat.wrap(info).setHintText(hintLayout.getText()); } } + + protected Theme.ResourcesProvider getResourcesProvider() { + return null; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextCaption.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextCaption.java index 6b6eed16c..48385ece8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextCaption.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextCaption.java @@ -65,13 +65,15 @@ public class EditTextCaption extends EditTextBoldCursor { private float offsetY; private int lineCount; private boolean isInitLineCount; + private final Theme.ResourcesProvider resourcesProvider; public interface EditTextCaptionDelegate { void onSpansChanged(); } - public EditTextCaption(Context context) { + public EditTextCaption(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { @@ -149,7 +151,7 @@ public class EditTextCaption extends EditTextBoldCursor { } public void makeSelectedUrl() { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), resourcesProvider); builder.setTitle(LocaleController.getString("CreateLink", R.string.CreateLink)); final EditTextBoldCursor editText = new EditTextBoldCursor(getContext()) { @@ -160,13 +162,13 @@ public class EditTextCaption extends EditTextBoldCursor { }; editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); editText.setText("http://"); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); editText.setHintText(LocaleController.getString("URL", R.string.URL)); - editText.setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader)); + editText.setHeaderHintColor(getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader)); editText.setSingleLine(true); editText.setFocusable(true); editText.setTransformHintToHeader(true); - editText.setLineColors(Theme.getColor(Theme.key_windowBackgroundWhiteInputField), Theme.getColor(Theme.key_windowBackgroundWhiteInputFieldActivated), Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)); + editText.setLineColors(getThemedColor(Theme.key_windowBackgroundWhiteInputField), getThemedColor(Theme.key_windowBackgroundWhiteInputFieldActivated), getThemedColor(Theme.key_windowBackgroundWhiteRedText3)); editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setBackgroundDrawable(null); editText.requestFocus(); @@ -487,4 +489,9 @@ public class EditTextCaption extends EditTextBoldCursor { public boolean performAccessibilityAction(int action, Bundle arguments) { return performMenuAction(action) || super.performAccessibilityAction(action, arguments); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextEmoji.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextEmoji.java index c73dccd1b..fcc503f4f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextEmoji.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextEmoji.java @@ -57,6 +57,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not private EditTextEmojiDelegate delegate; private int currentStyle; + private final Theme.ResourcesProvider resourcesProvider; public static final int STYLE_FRAGMENT = 0; public static final int STYLE_DIALOG = 1; @@ -96,7 +97,12 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not } public EditTextEmoji(Context context, SizeNotifierFrameLayout parent, BaseFragment fragment, int style) { + this(context, parent, fragment, style, null); + } + + public EditTextEmoji(Context context, SizeNotifierFrameLayout parent, BaseFragment fragment, int style, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; currentStyle = style; NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); @@ -104,7 +110,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not sizeNotifierLayout = parent; sizeNotifierLayout.setDelegate(this); - editText = new EditTextCaption(context) { + editText = new EditTextCaption(context, resourcesProvider) { @Override public boolean onTouchEvent(MotionEvent event) { if (isPopupShowing() && event.getAction() == MotionEvent.ACTION_DOWN) { @@ -138,18 +144,18 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not editText.setFocusable(editText.isEnabled()); editText.setCursorSize(AndroidUtilities.dp(20)); editText.setCursorWidth(1.5f); - editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); if (style == STYLE_FRAGMENT) { editText.setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)); editText.setBackgroundDrawable(Theme.createEditTextDrawable(context, false)); - editText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText)); - editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + editText.setHintTextColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText)); + editText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); editText.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(40) : 0, 0, LocaleController.isRTL ? 0 : AndroidUtilities.dp(40), AndroidUtilities.dp(8)); addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 11 : 0, 1, LocaleController.isRTL ? 0 : 11, 0)); } else { editText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - editText.setHintTextColor(Theme.getColor(Theme.key_dialogTextHint)); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + editText.setHintTextColor(getThemedColor(Theme.key_dialogTextHint)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); editText.setBackgroundDrawable(null); editText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12)); addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 48, 0, 0, 0)); @@ -158,7 +164,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not emojiButton = new ImageView(context); emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); emojiButton.setImageDrawable(emojiIconDrawable = new ReplaceableIconDrawable(context)); - emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); if (style == STYLE_FRAGMENT) { emojiIconDrawable.setIcon(R.drawable.smiles_tab_smiles, false); addView(emojiButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT), 0, 0, 0, 7)); @@ -167,7 +173,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not addView(emojiButton, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 0)); } if (Build.VERSION.SDK_INT >= 21) { - emojiButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector))); + emojiButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector))); } emojiButton.setOnClickListener(view -> { if (!emojiButton.isEnabled() || (adjustPanLayoutHelper != null && adjustPanLayoutHelper.animationInProgress())) { @@ -266,14 +272,14 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not public void updateColors() { if (currentStyle == STYLE_FRAGMENT) { - editText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText)); - editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); - editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + editText.setHintTextColor(getThemedColor(Theme.key_windowBackgroundWhiteHintText)); + editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); + editText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); } else { - editText.setHintTextColor(Theme.getColor(Theme.key_dialogTextHint)); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + editText.setHintTextColor(getThemedColor(Theme.key_dialogTextHint)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); } - emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); + emojiIconDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY)); if (emojiView != null) { emojiView.updateColors(); } @@ -470,7 +476,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not if (emojiView != null) { return; } - emojiView = new EmojiView(false, false, getContext(), false, null, null); + emojiView = new EmojiView(false, false, getContext(), false, null, null, resourcesProvider); emojiView.setVisibility(GONE); if (AndroidUtilities.isTablet()) { emojiView.setForseMultiwindowLayout(true); @@ -506,7 +512,7 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not @Override public void onClearEmojiRecent() { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ClearRecentEmoji", R.string.ClearRecentEmoji)); builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> emojiView.clearRecentEmoji()); @@ -583,4 +589,9 @@ public class EditTextEmoji extends FrameLayout implements NotificationCenter.Not public EditTextCaption getEditText() { return editText; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java index a83b56659..7665eebfb 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java @@ -190,15 +190,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific private final int[] tabsMinusDy = new int[3]; private ObjectAnimator[] tabsYAnimators = new ObjectAnimator[3]; private boolean firstTabUpdate; - - public void setShowing(boolean showing) { - this.showing = showing; - updateStickerTabsPosition(); - } - - public void onMessageSend() { - chooseStickerActionTracker.reset(); - } + private ChooseStickerActionTracker chooseStickerActionTracker; @IntDef({Type.STICKERS, Type.EMOJIS, Type.GIFS}) @Retention(RetentionPolicy.SOURCE) @@ -234,7 +226,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific private EmojiViewDelegate delegate; - private int currentChatId; + private long currentChatId; private TLRPC.StickerSetCovered[] primaryInstallingStickerSets = new TLRPC.StickerSetCovered[10]; private LongSparseArray installingStickerSets = new LongSparseArray<>(); @@ -275,6 +267,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific private float emojiTouchedY; private float lastStickersX; private boolean expandStickersByDragg; + private final Theme.ResourcesProvider resourcesProvider; + private Drawable searchIconDrawable; + private Drawable searchIconDotDrawable; private Runnable checkExpandStickerTabsRunnable = new Runnable() { @Override @@ -303,7 +298,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } - default void onStickersGroupClick(int chatId) { + default void onStickersGroupClick(long chatId) { } @@ -481,21 +476,21 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific shadowView = new View(context); shadowView.setAlpha(0.0f); shadowView.setTag(1); - shadowView.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + shadowView.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); addView(shadowView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.BOTTOM | Gravity.LEFT)); backgroundView = new View(context); - backgroundView.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + backgroundView.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); addView(backgroundView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, searchFieldHeight)); searchBackground = new View(context); - searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(Theme.key_chat_emojiSearchBackground))); + searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(Theme.key_chat_emojiSearchBackground))); addView(searchBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 14, 14, 0)); searchIconImageView = new ImageView(context); searchIconImageView.setScaleType(ImageView.ScaleType.CENTER); searchIconImageView.setImageResource(R.drawable.smiles_inputsearch); - searchIconImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); + searchIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); addView(searchIconImageView, LayoutHelper.createFrame(36, 36, Gravity.LEFT | Gravity.TOP, 16, 14, 0, 0)); clearSearchImageView = new ImageView(context); @@ -505,7 +500,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific clearSearchImageView.setScaleX(0.1f); clearSearchImageView.setScaleY(0.1f); clearSearchImageView.setAlpha(0.0f); - clearSearchImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); + clearSearchImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); addView(clearSearchImageView, LayoutHelper.createFrame(36, 36, Gravity.RIGHT | Gravity.TOP, 14, 14, 14, 0)); clearSearchImageView.setOnClickListener(v -> { searchEditText.setText(""); @@ -530,8 +525,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } }; searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - searchEditText.setHintTextColor(Theme.getColor(Theme.key_chat_emojiSearchIcon)); - searchEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + searchEditText.setHintTextColor(getThemedColor(Theme.key_chat_emojiSearchIcon)); + searchEditText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); searchEditText.setBackgroundDrawable(null); searchEditText.setPadding(0, 0, 0, 0); searchEditText.setMaxLines(1); @@ -545,7 +540,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } else if (type == 2) { searchEditText.setHint(LocaleController.getString("SearchGifsTitle", R.string.SearchGifsTitle)); } - searchEditText.setCursorColor(Theme.getColor(Theme.key_featuredStickers_addedIcon)); + searchEditText.setCursorColor(getThemedColor(Theme.key_featuredStickers_addedIcon)); searchEditText.setCursorSize(AndroidUtilities.dp(20)); searchEditText.setCursorWidth(1.5f); addView(searchEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 40, Gravity.LEFT | Gravity.TOP, 16 + 38, 12, 16 + 30, 0)); @@ -654,6 +649,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific stopAnimatingTabsY(type); } if (type == Type.STICKERS) { + if (chooseStickerActionTracker == null) { + createStickersChooseActionTracker(); + } chooseStickerActionTracker.doSomeAction(); } } @@ -696,8 +694,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific private boolean draggingVertically, draggingHorizontally; private VelocityTracker vTracker; - public DraggableScrollSlidingTabStrip(Context context) { - super(context); + public DraggableScrollSlidingTabStrip(Context context, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } @@ -1021,8 +1019,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific backgroundDrawable = getResources().getDrawable(R.drawable.stickers_back_all); arrowDrawable = getResources().getDrawable(R.drawable.stickers_back_arrow); - Theme.setDrawableColor(backgroundDrawable, Theme.getColor(Theme.key_dialogBackground)); - Theme.setDrawableColor(arrowDrawable, Theme.getColor(Theme.key_dialogBackground)); + Theme.setDrawableColor(backgroundDrawable, getThemedColor(Theme.key_dialogBackground)); + Theme.setDrawableColor(arrowDrawable, getThemedColor(Theme.key_dialogBackground)); } @Override @@ -1076,46 +1074,47 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } } - public EmojiView(boolean needStickers, boolean needGif, final Context context, boolean needSearch, final TLRPC.ChatFull chatFull, ViewGroup parentView) { + public EmojiView(boolean needStickers, boolean needGif, final Context context, boolean needSearch, final TLRPC.ChatFull chatFull, ViewGroup parentView, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; - int color = Theme.getColor(Theme.key_chat_emojiBottomPanelIcon); + int color = getThemedColor(Theme.key_chat_emojiBottomPanelIcon); color = Color.argb(30, Color.red(color), Color.green(color), Color.blue(color)); searchFieldHeight = AndroidUtilities.dp(64); needEmojiSearch = needSearch; tabIcons = new Drawable[]{ - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_smiles, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_gif, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_stickers, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)) + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_smiles, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_gif, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_tab_stickers, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)) }; emojiIcons = new Drawable[]{ - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_recent, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_smiles, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_cat, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_food, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_activities, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_travel, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_objects, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_other, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_flags, Theme.getColor(Theme.key_chat_emojiPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_recent, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_smiles, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_cat, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_food, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_activities, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_travel, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_objects, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_other, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.smiles_panel_flags, getThemedColor(Theme.key_chat_emojiPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), }; stickerIcons = new Drawable[]{ - Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_recent, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_faves, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new3, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_recent, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_faves, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new3, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), new LayerDrawable(new Drawable[]{ - Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new1, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new2, Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine), Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)) + searchIconDrawable = Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new1, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + searchIconDotDrawable = Theme.createEmojiIconSelectorDrawable(context, R.drawable.emoji_tabs_new2, getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine), getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)) }) }; gifIcons = new Drawable[]{ - Theme.createEmojiIconSelectorDrawable(context, R.drawable.stickers_recent, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), - Theme.createEmojiIconSelectorDrawable(context, R.drawable.stickers_gifs_trending, Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), Theme.getColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.stickers_recent, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), + Theme.createEmojiIconSelectorDrawable(context, R.drawable.stickers_gifs_trending, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), getThemedColor(Theme.key_chat_emojiPanelIconSelected)), }; emojiTitles = new String[]{ @@ -1133,7 +1132,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific info = chatFull; dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending)); + dotPaint.setColor(getThemedColor(Theme.key_chat_emojiPanelNewTrending)); if (Build.VERSION.SDK_INT >= 21) { outlineProvider = new ViewOutlineProvider() { @@ -1270,7 +1269,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific emojiGridView.setTopGlowOffset(AndroidUtilities.dp(38)); emojiGridView.setBottomGlowOffset(AndroidUtilities.dp(48)); emojiGridView.setPadding(0, AndroidUtilities.dp(38), 0, AndroidUtilities.dp(44)); - emojiGridView.setGlowColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + emojiGridView.setGlowColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); emojiGridView.setClipToPadding(false); emojiLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override @@ -1418,7 +1417,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } }); - emojiTabs = new ScrollSlidingTabStrip(context) { + emojiTabs = new ScrollSlidingTabStrip(context, resourcesProvider) { @Override public void setTranslationY(float translationY) { super.setTranslationY(translationY); @@ -1444,7 +1443,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific emojiTabs.setShouldExpand(true); emojiTabs.setIndicatorHeight(-1); emojiTabs.setUnderlineHeight(-1); - emojiTabs.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + emojiTabs.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); emojiContainer.addView(emojiTabs, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38)); emojiTabs.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() { @Override @@ -1466,7 +1465,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific emojiTabsShadow = new View(context); emojiTabsShadow.setAlpha(0.0f); emojiTabsShadow.setTag(1); - emojiTabsShadow.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + emojiTabsShadow.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT); layoutParams.topMargin = AndroidUtilities.dp(38); emojiContainer.addView(emojiTabsShadow, layoutParams); @@ -1483,7 +1482,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gifGridView, 0, contentPreviewViewerDelegate); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gifGridView, 0, contentPreviewViewerDelegate, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } @@ -1546,7 +1545,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific gifGridView.setAdapter(gifAdapter = new GifAdapter(context, true)); gifSearchAdapter = new GifAdapter(context); gifGridView.setOnScrollListener(new TypedScrollListener(Type.GIFS)); - gifGridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gifGridView, 0, gifOnItemClickListener, contentPreviewViewerDelegate)); + gifGridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gifGridView, 0, gifOnItemClickListener, contentPreviewViewerDelegate, resourcesProvider)); gifOnItemClickListener = (view, position) -> { if (delegate == null) { return; @@ -1584,12 +1583,12 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific gifSearchField.setVisibility(INVISIBLE); gifContainer.addView(gifSearchField, new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, searchFieldHeight + AndroidUtilities.getShadowHeight())); - gifTabs = new DraggableScrollSlidingTabStrip(context); + gifTabs = new DraggableScrollSlidingTabStrip(context, resourcesProvider); gifTabs.setType(ScrollSlidingTabStrip.Type.TAB); gifTabs.setUnderlineHeight(AndroidUtilities.getShadowHeight()); - gifTabs.setIndicatorColor(Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); - gifTabs.setUnderlineColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); - gifTabs.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + gifTabs.setIndicatorColor(getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); + gifTabs.setUnderlineColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); + gifTabs.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); gifContainer.addView(gifTabs, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP)); updateGifTabs(); @@ -1629,13 +1628,15 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } stickersContainer = new FrameLayout(context) { - + @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); stickersContainerAttached = true; updateStickerTabsPosition(); - chooseStickerActionTracker.checkVisibility(); + if (chooseStickerActionTracker != null) { + chooseStickerActionTracker.checkVisibility(); + } } @Override @@ -1643,7 +1644,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific super.onDetachedFromWindow(); stickersContainerAttached = false; updateStickerTabsPosition(); - chooseStickerActionTracker.checkVisibility(); + if (chooseStickerActionTracker != null) { + chooseStickerActionTracker.checkVisibility(); + } } }; @@ -1655,7 +1658,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersGridView, EmojiView.this.getMeasuredHeight(), contentPreviewViewerDelegate); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersGridView, EmojiView.this.getMeasuredHeight(), contentPreviewViewerDelegate, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } @@ -1704,6 +1707,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific expandStickersByDragg = false; updateStickerTabsPosition(); } + if (chooseStickerActionTracker == null) { + createStickersChooseActionTracker(); + } chooseStickerActionTracker.doSomeAction(); return i; } @@ -1738,7 +1744,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific views.add(stickersContainer); stickersSearchGridAdapter = new StickersSearchGridAdapter(context); stickersGridView.setAdapter(stickersGridAdapter = new StickersGridAdapter(context)); - stickersGridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersGridView, EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener, contentPreviewViewerDelegate)); + stickersGridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersGridView, EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener, contentPreviewViewerDelegate, resourcesProvider)); stickersOnItemClickListener = (view, position) -> { String query = null; if (stickersGridView.getAdapter() == stickersSearchGridAdapter) { @@ -1761,14 +1767,14 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific delegate.onStickerSelected(cell, cell.getSticker(), query, cell.getParentObject(), cell.getSendAnimationData(), true, 0); }; stickersGridView.setOnItemClickListener(stickersOnItemClickListener); - stickersGridView.setGlowColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + stickersGridView.setGlowColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); stickersContainer.addView(stickersGridView); scrollHelper = new RecyclerAnimationScrollHelper(stickersGridView, stickersLayoutManager); stickersSearchField = new SearchField(context, 0); stickersContainer.addView(stickersSearchField, new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, searchFieldHeight + AndroidUtilities.getShadowHeight())); - stickersTab = new DraggableScrollSlidingTabStrip(context) { + stickersTab = new DraggableScrollSlidingTabStrip(context, resourcesProvider) { @Override protected void updatePosition() { @@ -1826,9 +1832,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific stickersTab.setWillNotDraw(false); stickersTab.setType(ScrollSlidingTabStrip.Type.TAB); stickersTab.setUnderlineHeight(AndroidUtilities.getShadowHeight()); - stickersTab.setIndicatorColor(Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); - stickersTab.setUnderlineColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + stickersTab.setIndicatorColor(getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); + stickersTab.setUnderlineColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); if (parentView != null) { stickersTabContainer = new FrameLayout(context) { @@ -1844,7 +1850,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific if (searchProgressOffset != 0) { canvas.clipRect(0, searchProgressOffset, getMeasuredWidth(), getMeasuredHeight()); } - paint.setColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + paint.setColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); canvas.drawRect(0, 0, getMeasuredWidth(), AndroidUtilities.dp(48) + stickersTab.getExpandedOffset(), paint); super.dispatchDraw(canvas); stickersTab.drawOverlays(canvas); @@ -1963,7 +1969,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } }; backspaceButton.setImageResource(R.drawable.smiles_tab_clear); - backspaceButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + backspaceButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); backspaceButton.setScaleType(ImageView.ScaleType.CENTER); backspaceButton.setContentDescription(LocaleController.getString("AccDescrBackspace", R.string.AccDescrBackspace)); backspaceButton.setFocusable(true); @@ -1985,7 +1991,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific }; shadowLine = new View(context); - shadowLine.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + shadowLine.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); bottomTabContainer.addView(shadowLine, new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight())); bottomTabContainerBackground = new View(context); @@ -2000,7 +2006,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific stickerSettingsButton = new ImageView(context); stickerSettingsButton.setImageResource(R.drawable.smiles_tab_settings); - stickerSettingsButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + stickerSettingsButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); stickerSettingsButton.setScaleType(ImageView.ScaleType.CENTER); stickerSettingsButton.setFocusable(true); if (Build.VERSION.SDK_INT >= 21) { @@ -2089,7 +2095,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific searchButton = new ImageView(context); searchButton.setImageResource(R.drawable.smiles_tab_search); - searchButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + searchButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); searchButton.setScaleType(ImageView.ScaleType.CENTER); searchButton.setContentDescription(LocaleController.getString("Search", R.string.Search)); searchButton.setFocusable(true); @@ -2124,7 +2130,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } else { addView(bottomTabContainer, LayoutHelper.createFrame((Build.VERSION.SDK_INT >= 21 ? 40 : 44) + 20, (Build.VERSION.SDK_INT >= 21 ? 40 : 44) + 12, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, 0, 0, 2, 0)); - Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chat_emojiPanelBackground), Theme.getColor(Theme.key_chat_emojiPanelBackground)); + Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_chat_emojiPanelBackground), getThemedColor(Theme.key_chat_emojiPanelBackground)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -2156,8 +2162,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific addView(pager, 0, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP)); mediaBanTooltip = new CorrectlyMeasuringTextView(context); - mediaBanTooltip.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(3), Theme.getColor(Theme.key_chat_gifSaveHintBackground))); - mediaBanTooltip.setTextColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); + mediaBanTooltip.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(3), getThemedColor(Theme.key_chat_gifSaveHintBackground))); + mediaBanTooltip.setTextColor(getThemedColor(Theme.key_chat_gifSaveHintText)); mediaBanTooltip.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(7), AndroidUtilities.dp(8), AndroidUtilities.dp(7)); mediaBanTooltip.setGravity(Gravity.CENTER_VERTICAL); mediaBanTooltip.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); @@ -2192,6 +2198,16 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } } + private void createStickersChooseActionTracker() { + chooseStickerActionTracker = new ChooseStickerActionTracker(currentAccount, delegate.getDialogId(), delegate.getThreadId()) { + @Override + public boolean isShown() { + return delegate != null && getVisibility() == View.VISIBLE && stickersContainerAttached; + } + }; + chooseStickerActionTracker.checkVisibility(); + } + private void checkGridVisibility(int position, float positionOffset) { if (stickersContainer == null || gifContainer == null) { return; @@ -2251,12 +2267,12 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific @Override public boolean onListViewInterceptTouchEvent(RecyclerListView listView, MotionEvent event) { - return ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, EmojiView.this.getMeasuredHeight(), contentPreviewViewerDelegate); + return ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, EmojiView.this.getMeasuredHeight(), contentPreviewViewerDelegate, resourcesProvider); } @Override public boolean onListViewTouchEvent(RecyclerListView listView, RecyclerListView.OnItemClickListener onItemClickListener, MotionEvent event) { - return ContentPreviewViewer.getInstance().onTouch(event, listView, EmojiView.this.getMeasuredHeight(), onItemClickListener, contentPreviewViewerDelegate); + return ContentPreviewViewer.getInstance().onTouch(event, listView, EmojiView.this.getMeasuredHeight(), onItemClickListener, contentPreviewViewerDelegate, resourcesProvider); } @Override @@ -2289,7 +2305,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific return delegate.isInScheduleMode(); } }; - this.delegate.showTrendingStickersAlert(new TrendingStickersLayout(getContext(), trendingDelegate, primaryInstallingStickerSets, installingStickerSets, removingStickerSets, set)); + this.delegate.showTrendingStickersAlert(new TrendingStickersLayout(getContext(), trendingDelegate, primaryInstallingStickerSets, installingStickerSets, removingStickerSets, set, resourcesProvider)); } @Override @@ -2330,7 +2346,6 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific expandStickersByDragg = false; stickersTab.expandStickers(lastStickersX, false); } - } private void updateBottomTabContainerPosition() { @@ -3447,22 +3462,22 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific if (AndroidUtilities.isInMultiwindow || forseMultiwindowLayout) { Drawable background = getBackground(); if (background != null) { - background.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackground), PorterDuff.Mode.MULTIPLY)); + background.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackground), PorterDuff.Mode.MULTIPLY)); } } else { - setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); if (needEmojiSearch) { - bottomTabContainerBackground.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + bottomTabContainerBackground.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } } if (emojiTabs != null) { - emojiTabs.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); - emojiTabsShadow.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + emojiTabs.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); + emojiTabsShadow.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); } if (pickerView != null) { - Theme.setDrawableColor(pickerView.backgroundDrawable, Theme.getColor(Theme.key_dialogBackground)); - Theme.setDrawableColor(pickerView.arrowDrawable, Theme.getColor(Theme.key_dialogBackground)); + Theme.setDrawableColor(pickerView.backgroundDrawable, getThemedColor(Theme.key_dialogBackground)); + Theme.setDrawableColor(pickerView.arrowDrawable, getThemedColor(Theme.key_dialogBackground)); } for (int a = 0; a < 3; a++) { SearchField searchField; @@ -3476,75 +3491,83 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific if (searchField == null) { continue; } - searchField.backgroundView.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); - searchField.shadowView.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); - searchField.clearSearchImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); - searchField.searchIconImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); + searchField.backgroundView.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); + searchField.shadowView.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); + searchField.clearSearchImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); + searchField.searchIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiSearchIcon), PorterDuff.Mode.MULTIPLY)); Theme.setDrawableColorByKey(searchField.searchBackground.getBackground(), Theme.key_chat_emojiSearchBackground); searchField.searchBackground.invalidate(); - searchField.searchEditText.setHintTextColor(Theme.getColor(Theme.key_chat_emojiSearchIcon)); - searchField.searchEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + searchField.searchEditText.setHintTextColor(getThemedColor(Theme.key_chat_emojiSearchIcon)); + searchField.searchEditText.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); } if (dotPaint != null) { - dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending)); + dotPaint.setColor(getThemedColor(Theme.key_chat_emojiPanelNewTrending)); } if (emojiGridView != null) { - emojiGridView.setGlowColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + emojiGridView.setGlowColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } if (stickersGridView != null) { - stickersGridView.setGlowColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + stickersGridView.setGlowColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } if (stickersTab != null) { - stickersTab.setIndicatorColor(Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); - stickersTab.setUnderlineColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); - stickersTab.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + stickersTab.setIndicatorColor(getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); + stickersTab.setUnderlineColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); + stickersTab.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } if (gifTabs != null) { - gifTabs.setIndicatorColor(Theme.getColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); - gifTabs.setUnderlineColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); - gifTabs.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + gifTabs.setIndicatorColor(getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine)); + gifTabs.setUnderlineColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); + gifTabs.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } if (backspaceButton != null) { - backspaceButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + backspaceButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); if (emojiSearchField == null) { - Theme.setSelectorDrawableColor(backspaceButton.getBackground(), Theme.getColor(Theme.key_chat_emojiPanelBackground), false); - Theme.setSelectorDrawableColor(backspaceButton.getBackground(), Theme.getColor(Theme.key_chat_emojiPanelBackground), true); + Theme.setSelectorDrawableColor(backspaceButton.getBackground(), getThemedColor(Theme.key_chat_emojiPanelBackground), false); + Theme.setSelectorDrawableColor(backspaceButton.getBackground(), getThemedColor(Theme.key_chat_emojiPanelBackground), true); } } if (stickerSettingsButton != null) { - stickerSettingsButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + stickerSettingsButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); } if (searchButton != null) { - searchButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); + searchButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackspace), PorterDuff.Mode.MULTIPLY)); } if (shadowLine != null) { - shadowLine.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelShadowLine)); + shadowLine.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelShadowLine)); } if (mediaBanTooltip != null) { - ((ShapeDrawable) mediaBanTooltip.getBackground()).getPaint().setColor(Theme.getColor(Theme.key_chat_gifSaveHintBackground)); - mediaBanTooltip.setTextColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); + ((ShapeDrawable) mediaBanTooltip.getBackground()).getPaint().setColor(getThemedColor(Theme.key_chat_gifSaveHintBackground)); + mediaBanTooltip.setTextColor(getThemedColor(Theme.key_chat_gifSaveHintText)); } if (gifSearchAdapter != null) { - gifSearchAdapter.progressEmptyView.imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); - gifSearchAdapter.progressEmptyView.textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText)); - gifSearchAdapter.progressEmptyView.progressView.setProgressColor(Theme.getColor(Theme.key_progressCircle)); + gifSearchAdapter.progressEmptyView.imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); + gifSearchAdapter.progressEmptyView.textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelEmptyText)); + gifSearchAdapter.progressEmptyView.progressView.setProgressColor(getThemedColor(Theme.key_progressCircle)); } for (int a = 0; a < tabIcons.length; a++) { - Theme.setEmojiDrawableColor(tabIcons[a], Theme.getColor(Theme.key_chat_emojiBottomPanelIcon), false); - Theme.setEmojiDrawableColor(tabIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIconSelected), true); + Theme.setEmojiDrawableColor(tabIcons[a], getThemedColor(Theme.key_chat_emojiBottomPanelIcon), false); + Theme.setEmojiDrawableColor(tabIcons[a], getThemedColor(Theme.key_chat_emojiPanelIconSelected), true); } for (int a = 0; a < emojiIcons.length; a++) { - Theme.setEmojiDrawableColor(emojiIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIcon), false); - Theme.setEmojiDrawableColor(emojiIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIconSelected), true); + Theme.setEmojiDrawableColor(emojiIcons[a], getThemedColor(Theme.key_chat_emojiPanelIcon), false); + Theme.setEmojiDrawableColor(emojiIcons[a], getThemedColor(Theme.key_chat_emojiPanelIconSelected), true); } for (int a = 0; a < stickerIcons.length; a++) { - Theme.setEmojiDrawableColor(stickerIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIcon), false); - Theme.setEmojiDrawableColor(stickerIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIconSelected), true); + Theme.setEmojiDrawableColor(stickerIcons[a], getThemedColor(Theme.key_chat_emojiPanelIcon), false); + Theme.setEmojiDrawableColor(stickerIcons[a], getThemedColor(Theme.key_chat_emojiPanelIconSelected), true); } for (int a = 0; a < gifIcons.length; a++) { - Theme.setEmojiDrawableColor(gifIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIcon), false); - Theme.setEmojiDrawableColor(gifIcons[a], Theme.getColor(Theme.key_chat_emojiPanelIconSelected), true); + Theme.setEmojiDrawableColor(gifIcons[a], getThemedColor(Theme.key_chat_emojiPanelIcon), false); + Theme.setEmojiDrawableColor(gifIcons[a], getThemedColor(Theme.key_chat_emojiPanelIconSelected), true); + } + if (searchIconDrawable != null) { + Theme.setEmojiDrawableColor(searchIconDrawable, getThemedColor(Theme.key_chat_emojiBottomPanelIcon), false); + Theme.setEmojiDrawableColor(searchIconDrawable, getThemedColor(Theme.key_chat_emojiPanelIconSelected), true); + } + if (searchIconDotDrawable != null) { + Theme.setEmojiDrawableColor(searchIconDotDrawable, getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine), false); + Theme.setEmojiDrawableColor(searchIconDotDrawable, getThemedColor(Theme.key_chat_emojiPanelStickerPackSelectorLine), true); } } @@ -3559,9 +3582,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific setElevation(AndroidUtilities.dp(2)); } setBackgroundResource(R.drawable.smiles_popup); - getBackground().setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelBackground), PorterDuff.Mode.MULTIPLY)); + getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelBackground), PorterDuff.Mode.MULTIPLY)); if (needEmojiSearch) { - bottomTabContainerBackground.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + bottomTabContainerBackground.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } currentBackgroundType = 1; } @@ -3572,9 +3595,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific setClipToOutline(false); setElevation(0); } - setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); if (needEmojiSearch) { - bottomTabContainerBackground.setBackgroundColor(Theme.getColor(Theme.key_chat_emojiPanelBackground)); + bottomTabContainerBackground.setBackgroundColor(getThemedColor(Theme.key_chat_emojiPanelBackground)); } currentBackgroundType = 0; } @@ -3730,7 +3753,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific MediaDataController.getInstance(currentAccount).loadRecents(MediaDataController.TYPE_IMAGE, false, true, false); MediaDataController.getInstance(currentAccount).loadRecents(MediaDataController.TYPE_FAVE, false, true, false); } - chooseStickerActionTracker.checkVisibility(); + if (chooseStickerActionTracker != null) { + chooseStickerActionTracker.checkVisibility(); + } } public int getCurrentPage() { @@ -3786,9 +3811,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific private void updateRecentGifs() { final int prevSize = recentGifs.size(); - int prevHash = MediaDataController.calcDocumentsHash(recentGifs, Integer.MAX_VALUE); + long prevHash = MediaDataController.calcDocumentsHash(recentGifs, Integer.MAX_VALUE); recentGifs = MediaDataController.getInstance(currentAccount).getRecentGifs(); - int newHash = MediaDataController.calcDocumentsHash(recentGifs, Integer.MAX_VALUE); + long newHash = MediaDataController.calcDocumentsHash(recentGifs, Integer.MAX_VALUE); if (gifTabs != null && prevSize == 0 && !recentGifs.isEmpty() || prevSize != 0 && recentGifs.isEmpty()) { updateGifTabs(); } @@ -3797,7 +3822,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } } - public void setStickersBanned(boolean value, int chatId) { + public void setStickersBanned(boolean value, long chatId) { if (typeTabs == null) { return; } @@ -3987,6 +4012,11 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + private class TrendingAdapter extends RecyclerListView.SelectionAdapter { @Override @@ -4186,7 +4216,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific view = new EmptyCell(context); break; case 2: - view = new StickerSetNameCell(context, false); + view = new StickerSetNameCell(context, false, resourcesProvider); ((StickerSetNameCell) view).setOnIconClickListener(v -> { if (groupStickerSet != null) { if (delegate != null) { @@ -4215,7 +4245,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific view.setLayoutParams(new RecyclerView.LayoutParams(LayoutHelper.MATCH_PARENT, searchFieldHeight)); break; case 5: - view = new StickerSetNameCell(context, false); + view = new StickerSetNameCell(context, false, resourcesProvider); ((StickerSetNameCell) view).setOnIconClickListener(v -> { MediaDataController mediaDataController = MediaDataController.getInstance(currentAccount); ArrayList featured = mediaDataController.getFeaturedStickerSets(); @@ -4480,7 +4510,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific view = new ImageViewEmoji(getContext()); break; case 1: - view = new StickerSetNameCell(getContext(), true); + view = new StickerSetNameCell(getContext(), true, resourcesProvider); break; case 2: default: @@ -4616,13 +4646,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific TextView textView = new TextView(getContext()); textView.setText(LocaleController.getString("NoEmojiFound", R.string.NoEmojiFound)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText)); + textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelEmptyText)); frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 10, 0, 0)); ImageView imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(R.drawable.smiles_panel_question); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); frameLayout.addView(imageView, LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.RIGHT)); imageView.setOnClickListener(new OnClickListener() { @Override @@ -4641,7 +4671,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific TextView textView = new TextView(getContext()); textView.setText(LocaleController.getString("EmojiSuggestions", R.string.EmojiSuggestions)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlue2)); textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 24, 0, 0)); @@ -4649,14 +4679,14 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific textView = new TextView(getContext()); textView.setText(AndroidUtilities.replaceTags(LocaleController.getString("EmojiSuggestionsInfo", R.string.EmojiSuggestionsInfo))); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 11, 0, 0)); textView = new TextView(getContext()); textView.setText(LocaleController.formatString("EmojiSuggestionsUrl", R.string.EmojiSuggestionsUrl, lastSearchAlias != null ? lastSearchAlias : lastSearchKeyboardLanguage)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextLink)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextLink)); textView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 18, 0, 16)); textView.setOnClickListener(new OnClickListener() { @@ -4924,7 +4954,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific view.setLayoutParams(new RecyclerView.LayoutParams(LayoutHelper.MATCH_PARENT, searchFieldHeight)); break; case 2: - final StickerSetNameCell cell1 = new StickerSetNameCell(context, false); + final StickerSetNameCell cell1 = new StickerSetNameCell(context, false, resourcesProvider); cell1.setText(LocaleController.getString("FeaturedGifs", R.string.FeaturedGifs), 0); view = cell1; final RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT); @@ -5416,18 +5446,18 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(R.drawable.gif_empty); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 59)); textView = new TextView(getContext()); textView.setText(LocaleController.getString("NoGIFsFound", R.string.NoGIFsFound)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText)); + textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelEmptyText)); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 9)); - progressView = new RadialProgressView(context); + progressView = new RadialProgressView(context, resourcesProvider); progressView.setVisibility(GONE); - progressView.setProgressColor(Theme.getColor(Theme.key_progressCircle)); + progressView.setProgressColor(getThemedColor(Theme.key_progressCircle)); addView(progressView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); } @@ -5739,10 +5769,10 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific view = new EmptyCell(context); break; case 2: - view = new StickerSetNameCell(context, false); + view = new StickerSetNameCell(context, false, resourcesProvider); break; case 3: - view = new FeaturedStickerSetInfoCell(context, 17); + view = new FeaturedStickerSetInfoCell(context, 17, false, true, resourcesProvider); ((FeaturedStickerSetInfoCell) view).setAddOnClickListener(v -> { FeaturedStickerSetInfoCell parent1 = (FeaturedStickerSetInfoCell) v.getParent(); TLRPC.StickerSetCovered pack = parent1.getStickerSet(); @@ -5775,13 +5805,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(R.drawable.stickers_empty); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_emojiPanelEmptyText), PorterDuff.Mode.MULTIPLY)); frameLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 59)); TextView textView = new TextView(context); textView.setText(LocaleController.getString("NoStickersFound", R.string.NoStickersFound)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelEmptyText)); + textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelEmptyText)); frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 9)); view = frameLayout; @@ -5991,15 +6021,34 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific return stickersTab == null ? 0 : stickersTab.getExpandedOffset(); } - private final ChooseStickerActionTracker chooseStickerActionTracker = new ChooseStickerActionTracker(); + public void setShowing(boolean showing) { + this.showing = showing; + updateStickerTabsPosition(); + } - private class ChooseStickerActionTracker { + public void onMessageSend() { + if (chooseStickerActionTracker != null) { + chooseStickerActionTracker.reset(); + } + } + + public static abstract class ChooseStickerActionTracker { + + private final int currentAccount; + private final long dialogId; + private final int threadId; + + public ChooseStickerActionTracker(int currentAccount, long dialogId, int threadId) { + this.currentAccount = currentAccount; + this.dialogId = dialogId; + this.threadId = threadId; + } boolean visible = false; boolean typingWasSent; long lastActionTime = -1; - void doSomeAction() { + public void doSomeAction() { if (visible) { if (lastActionTime == -1) { lastActionTime = System.currentTimeMillis(); @@ -6007,26 +6056,26 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } if (System.currentTimeMillis() - lastActionTime > 2000) { typingWasSent = true; - MessagesController.getInstance(currentAccount).sendTyping(delegate.getDialogId(), delegate.getThreadId(), 10, 0); + lastActionTime = System.currentTimeMillis(); + MessagesController.getInstance(currentAccount).sendTyping(dialogId, threadId, 10, 0); } } } - void checkVisibility() { - if (delegate == null) { - return; - } - visible = getVisibility() == View.VISIBLE && stickersContainerAttached; - if (!visible) { - reset(); - } - } - private void reset() { if (typingWasSent) { - MessagesController.getInstance(currentAccount).sendTyping(delegate.getDialogId(), delegate.getThreadId(), 2, 0); + MessagesController.getInstance(currentAccount).sendTyping(dialogId, threadId, 2, 0); } lastActionTime = -1; } + + public void checkVisibility() { + visible = isShown(); + if (!visible) { + reset(); + } + } + + public abstract boolean isShown(); } } \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmptyTextProgressView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmptyTextProgressView.java index 17d41eb32..96a9f1a25 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmptyTextProgressView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmptyTextProgressView.java @@ -25,17 +25,23 @@ import org.telegram.ui.ActionBar.Theme; public class EmptyTextProgressView extends FrameLayout { + private final Theme.ResourcesProvider resourcesProvider; private TextView textView; private View progressView; private boolean inLayout; private int showAtPos; public EmptyTextProgressView(Context context) { - this(context, null); + this(context, null, null); } public EmptyTextProgressView(Context context, View progressView) { + this(context, progressView, null); + } + + public EmptyTextProgressView(Context context, View progressView, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; if (progressView == null) { progressView = new RadialProgressView(context); @@ -47,7 +53,7 @@ public class EmptyTextProgressView extends FrameLayout { textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - textView.setTextColor(Theme.getColor(Theme.key_emptyListPlaceholder)); + textView.setTextColor(getThemedColor(Theme.key_emptyListPlaceholder)); textView.setGravity(Gravity.CENTER); textView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0); textView.setText(LocaleController.getString("NoResult", R.string.NoResult)); @@ -93,7 +99,7 @@ public class EmptyTextProgressView extends FrameLayout { } else { Drawable drawable = getContext().getResources().getDrawable(resId).mutate(); if (drawable != null) { - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_emptyListPlaceholder), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_emptyListPlaceholder), PorterDuff.Mode.MULTIPLY)); } textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); textView.setCompoundDrawablePadding(AndroidUtilities.dp(1)); @@ -154,4 +160,9 @@ public class EmptyTextProgressView extends FrameLayout { public boolean hasOverlappingRendering() { return false; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/FiltersListBottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/FiltersListBottomSheet.java index 5d790bf6c..d15e3c85d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/FiltersListBottomSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/FiltersListBottomSheet.java @@ -22,6 +22,7 @@ import android.widget.FrameLayout; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; @@ -315,27 +316,25 @@ public class FiltersListBottomSheet extends BottomSheet implements NotificationC return result; } - public static ArrayList getDialogsCount(BaseFragment fragment, MessagesController.DialogFilter filter, ArrayList selectedDialogs, boolean always, boolean check) { - ArrayList dids = new ArrayList<>(); + public static ArrayList getDialogsCount(BaseFragment fragment, MessagesController.DialogFilter filter, ArrayList selectedDialogs, boolean always, boolean check) { + ArrayList dids = new ArrayList<>(); for (int b = 0, N2 = selectedDialogs.size(); b < N2; b++) { long did = selectedDialogs.get(b); - int lowerId = (int) did; - if (lowerId == 0) { - int highId = (int) (did >> 32); - TLRPC.EncryptedChat encryptedChat = fragment.getMessagesController().getEncryptedChat(highId); + if (DialogObject.isEncryptedDialog(did)) { + TLRPC.EncryptedChat encryptedChat = fragment.getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(did)); if (encryptedChat != null) { - lowerId = encryptedChat.user_id; - if (dids.contains(lowerId)) { + did = encryptedChat.user_id; + if (dids.contains(did)) { continue; } } else { continue; } } - if (filter != null && (always && filter.alwaysShow.contains(lowerId) || !always && filter.neverShow.contains(lowerId))) { + if (filter != null && (always && filter.alwaysShow.contains(did) || !always && filter.neverShow.contains(did))) { continue; } - dids.add(lowerId); + dids.add(did); if (check) { break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/FlickerLoadingView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/FlickerLoadingView.java index a3e0bb8be..cf11f36d3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/FlickerLoadingView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/FlickerLoadingView.java @@ -31,6 +31,8 @@ public class FlickerLoadingView extends View { public final static int USERS2_TYPE = 10; public final static int BOTS_MENU_TYPE = 11; public final static int SHARE_ALERT_TYPE = 12; + public final static int MESSAGE_SEEN_TYPE = 13; + public final static int CHAT_THEMES_TYPE = 14; private int gradientWidth; private LinearGradient gradient; @@ -56,8 +58,10 @@ public class FlickerLoadingView extends View { private String colorKey2 = Theme.key_windowBackgroundGray; private String colorKey3; private int itemsCount = 1; + private final Theme.ResourcesProvider resourcesProvider; float[] randomParams; + private Paint backgroundPaint; public void setViewType(int type) { this.viewType = type; @@ -91,7 +95,12 @@ public class FlickerLoadingView extends View { } public FlickerLoadingView(Context context) { + this(context, null); + } + + public FlickerLoadingView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; matrix = new Matrix(); } @@ -110,12 +119,12 @@ public class FlickerLoadingView extends View { @Override protected void onDraw(Canvas canvas) { - int color0 = Theme.getColor(colorKey1); - int color1 = Theme.getColor(colorKey2); + int color0 = getThemedColor(colorKey1); + int color1 = getThemedColor(colorKey2); if (this.color1 != color1 || this.color0 != color0) { this.color0 = color0; this.color1 = color1; - if (isSingleCell) { + if (isSingleCell || viewType == MESSAGE_SEEN_TYPE || viewType == CHAT_THEMES_TYPE) { gradient = new LinearGradient(0, 0, gradientWidth = AndroidUtilities.dp(200), 0, new int[]{color1, color0, color0, color1}, new float[]{0.0f, 0.4f, 0.6f, 1f}, Shader.TileMode.CLAMP); } else { gradient = new LinearGradient(0, 0, 0, gradientWidth = AndroidUtilities.dp(600), new int[]{color1, color0, color0, color1}, new float[]{0.0f, 0.4f, 0.6f, 1f}, Shader.TileMode.CLAMP); @@ -127,7 +136,7 @@ public class FlickerLoadingView extends View { if (useHeaderOffset) { h += AndroidUtilities.dp(32); if (colorKey3 != null) { - headerPaint.setColor(Theme.getColor(colorKey3)); + headerPaint.setColor(getThemedColor(colorKey3)); } canvas.drawRect(0,0, getMeasuredWidth(), AndroidUtilities.dp(32), colorKey3 != null ? headerPaint : paint); } @@ -411,6 +420,51 @@ public class FlickerLoadingView extends View { break; } } + } else if (getViewType() == MESSAGE_SEEN_TYPE) { + float cy = getMeasuredHeight() / 2f; + + AndroidUtilities.rectTmp.set(AndroidUtilities.dp(40), cy - AndroidUtilities.dp(4), getMeasuredWidth() - AndroidUtilities.dp(120), cy + AndroidUtilities.dp(4)); + canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), paint); + + if (backgroundPaint == null) { + backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + backgroundPaint.setColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + } + + for (int i = 0; i < 3; i++) { + canvas.drawCircle(getMeasuredWidth() - AndroidUtilities.dp(8 + 24 + 12 + 12) + AndroidUtilities.dp(13) + AndroidUtilities.dp(12) * i, cy, AndroidUtilities.dp(13f), backgroundPaint); + canvas.drawCircle(getMeasuredWidth() - AndroidUtilities.dp(8 + 24 + 12 + 12) + AndroidUtilities.dp(13) + AndroidUtilities.dp(12) * i, cy, AndroidUtilities.dp(12f), paint); + } + } else if (getViewType() == CHAT_THEMES_TYPE) { + int x = AndroidUtilities.dp(12); + int itemWidth = AndroidUtilities.dp(77); + int INNER_RECT_SPACE = AndroidUtilities.dp(4); + float BUBBLE_HEIGHT = AndroidUtilities.dp(21); + float BUBBLE_WIDTH = AndroidUtilities.dp(41); + + while (x < getMeasuredWidth()) { + + if (backgroundPaint == null) { + backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + backgroundPaint.setColor(Theme.getColor(Theme.key_dialogBackground)); + } + + float bubbleTop = INNER_RECT_SPACE + AndroidUtilities.dp(8); + float bubbleLeft = INNER_RECT_SPACE + AndroidUtilities.dp(22); + AndroidUtilities.rectTmp.set(x + AndroidUtilities.dp(4), AndroidUtilities.dp(4), x + itemWidth - AndroidUtilities.dp(4), getMeasuredHeight() - AndroidUtilities.dp(4)); + canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(6), AndroidUtilities.dp(6), paint); + + rectF.set(x + bubbleLeft, bubbleTop, x + bubbleLeft + BUBBLE_WIDTH, bubbleTop + BUBBLE_HEIGHT); + canvas.drawRoundRect(rectF, rectF.height() * 0.5f, rectF.height() * 0.5f, backgroundPaint); + bubbleLeft = INNER_RECT_SPACE + AndroidUtilities.dp(5); + bubbleTop += BUBBLE_HEIGHT + AndroidUtilities.dp(4); + rectF.set(x + bubbleLeft, bubbleTop, x + bubbleLeft + BUBBLE_WIDTH, bubbleTop + BUBBLE_HEIGHT); + canvas.drawRoundRect(rectF, rectF.height() * 0.5f, rectF.height() * 0.5f, backgroundPaint); + + + canvas.drawCircle(x + itemWidth / 2, getMeasuredHeight() - AndroidUtilities.dp(20), AndroidUtilities.dp(8), backgroundPaint); + x += itemWidth; + } } long newUpdateTime = SystemClock.elapsedRealtime(); @@ -419,7 +473,7 @@ public class FlickerLoadingView extends View { dt = 16; } lastUpdateTime = newUpdateTime; - if (isSingleCell) { + if (isSingleCell || viewType == MESSAGE_SEEN_TYPE || getViewType() == CHAT_THEMES_TYPE) { totalTranslation += dt * getMeasuredWidth() / 400.0f; if (totalTranslation >= getMeasuredWidth() * 2) { totalTranslation = -gradientWidth * 2; @@ -505,4 +559,9 @@ public class FlickerLoadingView extends View { public void setItemsCount(int i) { this.itemsCount = i; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForegroundColorSpanThemable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForegroundColorSpanThemable.java index b95fa63cb..66b5690ed 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForegroundColorSpanThemable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForegroundColorSpanThemable.java @@ -12,14 +12,20 @@ public class ForegroundColorSpanThemable extends CharacterStyle implements Updat private int color; private String colorKey; + private final Theme.ResourcesProvider resourcesProvider; public ForegroundColorSpanThemable(String colorKey) { + this(colorKey, null); + } + + public ForegroundColorSpanThemable(String colorKey, Theme.ResourcesProvider resourcesProvider) { this.colorKey = colorKey; + this.resourcesProvider = resourcesProvider; } @Override public void updateDrawState(@NonNull TextPaint textPaint) { - color = Theme.getColor(colorKey); + color = Theme.getColor(colorKey, resourcesProvider); if (textPaint.getColor() != color) { textPaint.setColor(color); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardingPreviewView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardingPreviewView.java index 86a128505..499caef1e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardingPreviewView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardingPreviewView.java @@ -7,7 +7,6 @@ import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; -import android.graphics.Color; import android.graphics.Outline; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; @@ -42,13 +41,19 @@ import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenuSubItem; import org.telegram.ui.ActionBar.Theme; -import org.telegram.ui.Cells.BotHelpCell; import org.telegram.ui.Cells.ChatMessageCell; import java.util.ArrayList; public class ForwardingPreviewView extends FrameLayout { + public interface ResourcesDelegate extends Theme.ResourcesProvider { + + Drawable getWallpaperDrawable(); + + boolean isWallpaperMotion(); + } + SizeNotifierFrameLayout chatPreviewContainer; ActionBar actionBar; RecyclerListView chatListView; @@ -100,17 +105,25 @@ public class ForwardingPreviewView extends FrameLayout { }; private final ArrayList drawingGroups = new ArrayList<>(10); + private final ResourcesDelegate resourcesProvider; @SuppressLint("ClickableViewAccessibility") - public ForwardingPreviewView(@NonNull Context context, ForwardingMessagesParams params, TLRPC.User user, TLRPC.Chat chat, int currentAccount) { + public ForwardingPreviewView(@NonNull Context context, ForwardingMessagesParams params, TLRPC.User user, TLRPC.Chat chat, int currentAccount, ResourcesDelegate resourcesProvider) { super(context); this.currentAccount = currentAccount; currentUser = user; currentChat = chat; forwardingMessagesParams = params; + this.resourcesProvider = resourcesProvider; - chatPreviewContainer = new SizeNotifierFrameLayout(context); - chatPreviewContainer.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion()); + chatPreviewContainer = new SizeNotifierFrameLayout(context) { + @Override + protected Drawable getNewDrawable() { + Drawable drawable = resourcesProvider.getWallpaperDrawable(); + return drawable != null ? drawable : super.getNewDrawable(); + } + }; + chatPreviewContainer.setBackgroundImage(resourcesProvider.getWallpaperDrawable(), resourcesProvider.isWallpaperMotion()); chatPreviewContainer.setOccupyStatusBar(false); if (Build.VERSION.SDK_INT >= 21) { @@ -125,11 +138,11 @@ public class ForwardingPreviewView extends FrameLayout { chatPreviewContainer.setElevation(AndroidUtilities.dp(4)); } - actionBar = new ActionBar(context); - actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault)); + actionBar = new ActionBar(context, resourcesProvider); + actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarDefault)); actionBar.setOccupyStatusBar(false); - chatListView = new RecyclerListView(context) { + chatListView = new RecyclerListView(context, resourcesProvider) { @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { @@ -314,7 +327,7 @@ public class ForwardingPreviewView extends FrameLayout { } } }; - chatListView.setItemAnimator(itemAnimator = new ChatListItemAnimator(null, chatListView) { + chatListView.setItemAnimator(itemAnimator = new ChatListItemAnimator(null, chatListView, resourcesProvider) { int scrollAnimationIndex = -1; @@ -512,16 +525,16 @@ public class ForwardingPreviewView extends FrameLayout { buttonsLayout = new LinearLayout(context); buttonsLayout.setOrientation(LinearLayout.VERTICAL); Drawable shadowDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); buttonsLayout.setBackground(shadowDrawable); menuContainer.addView(buttonsLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - showSendersNameView = new ActionBarMenuSubItem(context, true, true, false); + showSendersNameView = new ActionBarMenuSubItem(context, true, true, false, resourcesProvider); buttonsLayout.addView(showSendersNameView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); showSendersNameView.setTextAndIcon(forwardingMessagesParams.multiplyUsers ? LocaleController.getString("ShowSenderNames", R.string.ShowSenderNames) : LocaleController.getString("ShowSendersName", R.string.ShowSendersName), 0); showSendersNameView.setChecked(true); - hideSendersNameView = new ActionBarMenuSubItem(context, true, false, !params.hasCaption); + hideSendersNameView = new ActionBarMenuSubItem(context, true, false, !params.hasCaption, resourcesProvider); buttonsLayout.addView(hideSendersNameView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); hideSendersNameView.setTextAndIcon(forwardingMessagesParams.multiplyUsers ? LocaleController.getString("HideSenderNames", R.string.HideSenderNames) : LocaleController.getString("HideSendersName", R.string.HideSendersName), 0); hideSendersNameView.setChecked(false); @@ -533,16 +546,16 @@ public class ForwardingPreviewView extends FrameLayout { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(2, MeasureSpec.EXACTLY)); } }; - dividerView.setBackgroundColor(Theme.getColor(Theme.key_divider)); + dividerView.setBackgroundColor(getThemedColor(Theme.key_divider)); buttonsLayout.addView(dividerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); - showCaptionView = new ActionBarMenuSubItem(context, true, false, false); + showCaptionView = new ActionBarMenuSubItem(context, true, false, false, resourcesProvider); buttonsLayout.addView(showCaptionView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); showCaptionView.setTextAndIcon(LocaleController.getString("ShowCaption", R.string.ShowCaption), 0); showCaptionView.setChecked(true); - hideCaptionView = new ActionBarMenuSubItem(context, true, false, true); + hideCaptionView = new ActionBarMenuSubItem(context, true, false, true, resourcesProvider); buttonsLayout.addView(hideCaptionView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); hideCaptionView.setTextAndIcon(LocaleController.getString("HideCaption", R.string.HideCaption), 0); hideCaptionView.setChecked(false); @@ -551,15 +564,15 @@ public class ForwardingPreviewView extends FrameLayout { buttonsLayout2 = new LinearLayout(context); buttonsLayout2.setOrientation(LinearLayout.VERTICAL); shadowDrawable = getContext().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); buttonsLayout2.setBackground(shadowDrawable); menuContainer.addView(buttonsLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, forwardingMessagesParams.hasSenders ? -8 : 0, 0, 0)); - changeRecipientView = new ActionBarMenuSubItem(context, true, false); + changeRecipientView = new ActionBarMenuSubItem(context, true, false, resourcesProvider); buttonsLayout2.addView(changeRecipientView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); changeRecipientView.setTextAndIcon(LocaleController.getString("ChangeRecipient", R.string.ChangeRecipient), R.drawable.msg_forward_replace); - sendMessagesView = new ActionBarMenuSubItem(context, false, true); + sendMessagesView = new ActionBarMenuSubItem(context, false, true, resourcesProvider); buttonsLayout2.addView(sendMessagesView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48)); sendMessagesView.setTextAndIcon(LocaleController.getString("ForwardSendMessages", R.string.ForwardSendMessages), R.drawable.msg_forward_send); @@ -948,7 +961,7 @@ public class ForwardingPreviewView extends FrameLayout { @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - ChatMessageCell chatMessageCell = new ChatMessageCell(parent.getContext()); + ChatMessageCell chatMessageCell = new ChatMessageCell(parent.getContext(), resourcesProvider); return new RecyclerListView.Holder(chatMessageCell); } @@ -995,4 +1008,9 @@ public class ForwardingPreviewView extends FrameLayout { } return groupedMessages; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/FragmentContextView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/FragmentContextView.java index ecea1f224..b588a7dbb 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/FragmentContextView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/FragmentContextView.java @@ -53,6 +53,7 @@ import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocationController; import org.telegram.messenger.MediaController; @@ -155,6 +156,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent private boolean isLocation; private FragmentContextViewDelegate delegate; + private final Theme.ResourcesProvider resourcesProvider; private boolean firstLocationsLoaded; private int lastLocationSharingCount = -1; @@ -201,11 +203,16 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } public FragmentContextView(Context context, BaseFragment parentFragment, boolean location) { - this(context, parentFragment, null, location); + this(context, parentFragment, null, location, null); } - public FragmentContextView(Context context, BaseFragment parentFragment, View paddingView, boolean location) { + public FragmentContextView(Context context, BaseFragment parentFragment, boolean location, Theme.ResourcesProvider resourcesProvider) { + this(context, parentFragment, null, location, resourcesProvider); + } + + public FragmentContextView(Context context, BaseFragment parentFragment, View paddingView, boolean location, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; fragment = parentFragment; applyingView = paddingView; @@ -274,10 +281,10 @@ public class FragmentContextView extends FrameLayout implements NotificationCent playButton = new ImageView(context); playButton.setScaleType(ImageView.ScaleType.CENTER); - playButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_inappPlayerPlayPause), PorterDuff.Mode.MULTIPLY)); + playButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_inappPlayerPlayPause), PorterDuff.Mode.MULTIPLY)); playButton.setImageDrawable(playPauseDrawable = new PlayPauseDrawable(14)); if (Build.VERSION.SDK_INT >= 21) { - playButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerPlayPause) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + playButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerPlayPause) & 0x19ffffff, 1, AndroidUtilities.dp(14))); } addView(playButton, LayoutHelper.createFrame(36, 36, Gravity.TOP | Gravity.LEFT)); playButton.setOnClickListener(v -> { @@ -294,7 +301,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent importingImageView.setScaleType(ImageView.ScaleType.CENTER); importingImageView.setAutoRepeat(true); importingImageView.setAnimation(R.raw.import_progress, 30, 30); - importingImageView.setBackground(Theme.createCircleDrawable(AndroidUtilities.dp(22), Theme.getColor(Theme.key_inappPlayerPlayPause))); + importingImageView.setBackground(Theme.createCircleDrawable(AndroidUtilities.dp(22), getThemedColor(Theme.key_inappPlayerPlayPause))); addView(importingImageView, LayoutHelper.createFrame(22, 22, Gravity.TOP | Gravity.LEFT, 7, 7, 0, 0)); titleTextView = new AudioPlayerAlert.ClippingTextViewSwitcher(context) { @@ -307,20 +314,18 @@ public class FragmentContextView extends FrameLayout implements NotificationCent textView.setEllipsize(TextUtils.TruncateAt.END); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - if (currentStyle == 0 || currentStyle == 2) { textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerTitle)); textView.setTypeface(Typeface.DEFAULT); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentStyle == 4) { textView.setGravity(Gravity.TOP | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerPerformer)); + textView.setTextColor(getThemedColor(Theme.key_inappPlayerPerformer)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } else if (currentStyle == 1 || currentStyle == 3) { textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_returnToCallText)); + textView.setTextColor(getThemedColor(Theme.key_returnToCallText)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } @@ -339,7 +344,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent textView.setEllipsize(TextUtils.TruncateAt.END); textView.setGravity(Gravity.LEFT); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerClose)); + textView.setTextColor(getThemedColor(Theme.key_inappPlayerClose)); return textView; } }; @@ -347,8 +352,8 @@ public class FragmentContextView extends FrameLayout implements NotificationCent joinButton = new TextView(context); joinButton.setText(LocaleController.getString("VoipChatJoin", R.string.VoipChatJoin)); - joinButton.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); - joinButton.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + joinButton.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); + joinButton.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); joinButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); joinButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); joinButton.setGravity(Gravity.CENTER); @@ -357,7 +362,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent joinButton.setOnClickListener(v -> FragmentContextView.this.callOnClick()); if (!location) { - playbackSpeedButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_dialogTextBlack)); + playbackSpeedButton = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_dialogTextBlack), resourcesProvider); playbackSpeedButton.setLongClickEnabled(false); playbackSpeedButton.setShowSubmenuByMove(false); playbackSpeedButton.setContentDescription(LocaleController.getString("AccDescrPlayerSpeed", R.string.AccDescrPlayerSpeed)); @@ -500,9 +505,9 @@ public class FragmentContextView extends FrameLayout implements NotificationCent info.setText(isMuted ? LocaleController.getString("VoipUnmute", R.string.VoipUnmute) : LocaleController.getString("VoipMute", R.string.VoipMute)); } }; - muteButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_returnToCallText), PorterDuff.Mode.MULTIPLY)); + muteButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_returnToCallText), PorterDuff.Mode.MULTIPLY)); if (Build.VERSION.SDK_INT >= 21) { - muteButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + muteButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); } muteButton.setAnimation(muteDrawable); muteButton.setScaleType(ImageView.ScaleType.CENTER); @@ -539,15 +544,15 @@ public class FragmentContextView extends FrameLayout implements NotificationCent closeButton = new ImageView(context); closeButton.setImageResource(R.drawable.miniplayer_close); - closeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_inappPlayerClose), PorterDuff.Mode.MULTIPLY)); + closeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_inappPlayerClose), PorterDuff.Mode.MULTIPLY)); if (Build.VERSION.SDK_INT >= 21) { - closeButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + closeButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14))); } closeButton.setScaleType(ImageView.ScaleType.CENTER); addView(closeButton, LayoutHelper.createFrame(36, 36, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0)); closeButton.setOnClickListener(v -> { if (currentStyle == 2) { - AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity()); + AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity(), resourcesProvider); builder.setTitle(LocaleController.getString("StopLiveLocationAlertToTitle", R.string.StopLiveLocationAlertToTitle)); if (fragment instanceof DialogsActivity) { builder.setMessage(LocaleController.getString("StopLiveLocationAlertAllText", R.string.StopLiveLocationAlertAllText)); @@ -577,7 +582,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent builder.show(); TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { - button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2)); + button.setTextColor(getThemedColor(Theme.key_dialogTextRed2)); } } else { MediaController.getInstance().cleanupPlayer(true, true); @@ -589,27 +594,23 @@ public class FragmentContextView extends FrameLayout implements NotificationCent MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); if (fragment != null && messageObject != null) { if (messageObject.isMusic()) { - fragment.showDialog(new AudioPlayerAlert(getContext())); + fragment.showDialog(new AudioPlayerAlert(getContext(), resourcesProvider)); } else { - long dialog_id = 0; + long dialogId = 0; if (fragment instanceof ChatActivity) { - dialog_id = ((ChatActivity) fragment).getDialogId(); + dialogId = ((ChatActivity) fragment).getDialogId(); } - if (messageObject.getDialogId() == dialog_id) { + if (messageObject.getDialogId() == dialogId) { ((ChatActivity) fragment).scrollToMessageId(messageObject.getId(), 0, false, 0, true, 0); } else { - dialog_id = messageObject.getDialogId(); + dialogId = messageObject.getDialogId(); Bundle args = new Bundle(); - int lower_part = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + args.putLong("chat_id", -dialogId); } args.putInt("message_id", messageObject.getId()); fragment.presentFragment(new ChatActivity(args), fragment instanceof ChatActivity); @@ -639,7 +640,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent if (did != 0) { openSharingLocation(LocationController.getInstance(account).getSharingLocationInfo(did)); } else { - fragment.showDialog(new SharingLocationsAlert(getContext(), this::openSharingLocation)); + fragment.showDialog(new SharingLocationsAlert(getContext(), this::openSharingLocation, resourcesProvider)); } } else if (currentStyle == 3) { if (VoIPService.getSharedInstance() != null && getContext() instanceof LaunchActivity) { @@ -660,7 +661,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent if (importingHistory == null) { return; } - ImportingAlert importingAlert = new ImportingAlert(getContext(), null, (ChatActivity) fragment); + ImportingAlert importingAlert = new ImportingAlert(getContext(), null, (ChatActivity) fragment, resourcesProvider); importingAlert.setOnHideListener(dialog -> checkImport(false)); fragment.showDialog(importingAlert); checkImport(false); @@ -681,12 +682,6 @@ public class FragmentContextView extends FrameLayout implements NotificationCent return; } float currentPlaybackSpeed = MediaController.getInstance().getPlaybackSpeed(isMusic); - String key; - if (Math.abs(currentPlaybackSpeed - 1.0f) > 0.001f) { - key = Theme.key_inappPlayerPlayPause; - } else { - key = Theme.key_inappPlayerClose; - } float speed = MediaController.getInstance().getFastPlaybackSpeed(isMusic); if (Math.abs(speed - 1.8f) < 0.001f) { playbackSpeedButton.setIcon(R.drawable.voice_mini_2_0); @@ -695,22 +690,36 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } else { playbackSpeedButton.setIcon(R.drawable.voice_mini_0_5); } - playbackSpeedButton.setIconColor(Theme.getColor(key)); - if (Build.VERSION.SDK_INT >= 21) { - playbackSpeedButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(key) & 0x19ffffff, 1, AndroidUtilities.dp(14))); - } + updateColors(); for (int a = 0; a < speedItems.length; a++) { if (a == 0 && Math.abs(currentPlaybackSpeed - 0.5f) < 0.001f || a == 1 && Math.abs(currentPlaybackSpeed - 1.0f) < 0.001f || a == 2 && Math.abs(currentPlaybackSpeed - 1.5f) < 0.001f || a == 3 && Math.abs(currentPlaybackSpeed - 1.8f) < 0.001f) { - speedItems[a].setColors(Theme.getColor(Theme.key_inappPlayerPlayPause), Theme.getColor(Theme.key_inappPlayerPlayPause)); + speedItems[a].setColors(getThemedColor(Theme.key_inappPlayerPlayPause), getThemedColor(Theme.key_inappPlayerPlayPause)); } else { - speedItems[a].setColors(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon)); + speedItems[a].setColors(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon)); } } } + public void updateColors() { + if (playbackSpeedButton != null) { + String key; + float currentPlaybackSpeed = MediaController.getInstance().getPlaybackSpeed(isMusic); + if (Math.abs(currentPlaybackSpeed - 1.0f) > 0.001f) { + key = Theme.key_inappPlayerPlayPause; + } else { + key = Theme.key_inappPlayerClose; + } + playbackSpeedButton.setIconColor(getThemedColor(key)); + if (Build.VERSION.SDK_INT >= 21) { + playbackSpeedButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(key) & 0x19ffffff, 1, AndroidUtilities.dp(14))); + } + } + + } + public void setAdditionalContextView(FragmentContextView contextView) { additionalContextView = contextView; } @@ -807,7 +816,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } if (style == 5) { selector.setBackground(Theme.getSelectorDrawable(false)); - frameLayout.setBackgroundColor(Theme.getColor(Theme.key_inappPlayerBackground)); + frameLayout.setBackgroundColor(getThemedColor(Theme.key_inappPlayerBackground)); frameLayout.setTag(Theme.key_inappPlayerBackground); for (int i = 0; i < 2; i++) { @@ -816,7 +825,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent continue; } textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerTitle)); + textView.setTextColor(getThemedColor(Theme.key_inappPlayerTitle)); textView.setTypeface(Typeface.DEFAULT); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } @@ -836,7 +845,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent titleTextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 35, 0, 36, 0)); } else if (style == 0 || style == 2) { selector.setBackground(Theme.getSelectorDrawable(false)); - frameLayout.setBackgroundColor(Theme.getColor(Theme.key_inappPlayerBackground)); + frameLayout.setBackgroundColor(getThemedColor(Theme.key_inappPlayerBackground)); frameLayout.setTag(Theme.key_inappPlayerBackground); subtitleTextView.setVisibility(GONE); @@ -853,7 +862,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent continue; } textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerTitle)); + textView.setTextColor(getThemedColor(Theme.key_inappPlayerTitle)); textView.setTypeface(Typeface.DEFAULT); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } @@ -872,7 +881,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } } else if (style == 4) { selector.setBackground(Theme.getSelectorDrawable(false)); - frameLayout.setBackgroundColor(Theme.getColor(Theme.key_inappPlayerBackground)); + frameLayout.setBackgroundColor(getThemedColor(Theme.key_inappPlayerBackground)); frameLayout.setTag(Theme.key_inappPlayerBackground); muteButton.setVisibility(GONE); subtitleTextView.setVisibility(VISIBLE); @@ -883,7 +892,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent continue; } textView.setGravity(Gravity.TOP | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_inappPlayerPerformer)); + textView.setTextColor(getThemedColor(Theme.key_inappPlayerPerformer)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); } @@ -928,7 +937,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent continue; } textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); - textView.setTextColor(Theme.getColor(Theme.key_returnToCallText)); + textView.setTextColor(getThemedColor(Theme.key_returnToCallText)); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); } @@ -1238,13 +1247,13 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } if (infos.size() == 1) { LocationController.SharingLocationInfo info = infos.get(0); - int lower_id = (int) info.messageObject.getDialogId(); - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(info.messageObject.currentAccount).getUser(lower_id); + long dialogId = info.messageObject.getDialogId(); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = MessagesController.getInstance(info.messageObject.currentAccount).getUser(dialogId); param = UserObject.getFirstName(user); str = LocaleController.getString("AttachLiveLocationIsSharing", R.string.AttachLiveLocationIsSharing); } else { - TLRPC.Chat chat = MessagesController.getInstance(info.messageObject.currentAccount).getChat(-lower_id); + TLRPC.Chat chat = MessagesController.getInstance(info.messageObject.currentAccount).getChat(-dialogId); if (chat != null) { param = chat.title; } else { @@ -1267,7 +1276,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent textView.setEllipsize(TextUtils.TruncateAt.END); } - TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_inappPlayerPerformer)); + TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, getThemedColor(Theme.key_inappPlayerPerformer)); stringBuilder.setSpan(span, start, start + liveLocation.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); titleTextView.setText(stringBuilder, false); } else { @@ -1293,7 +1302,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent int locationSharingCount = 0; TLRPC.User notYouUser = null; if (messages != null) { - int currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); + long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId(); int date = ConnectionsManager.getInstance(currentAccount).getCurrentTime(); for (int a = 0; a < messages.size(); a++) { TLRPC.Message message = messages.get(a); @@ -1301,7 +1310,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent continue; } if (message.date + message.media.period > date) { - int fromId = MessageObject.getFromChatId(message); + long fromId = MessageObject.getFromChatId(message); if (notYouUser == null && fromId != currentUserId) { notYouUser = MessagesController.getInstance(currentAccount).getUser(fromId); } @@ -1352,7 +1361,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent textView.setEllipsize(TextUtils.TruncateAt.END); } if (start >= 0) { - TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_inappPlayerPerformer)); + TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, getThemedColor(Theme.key_inappPlayerPerformer)); stringBuilder.setSpan(span, start, start + liveLocation.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); } titleTextView.setText(stringBuilder, false); @@ -1544,7 +1553,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent textView.setEllipsize(TextUtils.TruncateAt.END); } } - TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, Theme.getColor(Theme.key_inappPlayerPerformer)); + TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, getThemedColor(Theme.key_inappPlayerPerformer)); stringBuilder.setSpan(span, 0, messageObject.getMusicAuthor().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); titleTextView.setText(stringBuilder, !create && wasVisible && isMusic); } @@ -2112,4 +2121,18 @@ public class FragmentContextView extends FrameLayout implements NotificationCent } } } + + private int getTitleTextColor() { + if (currentStyle == 4) { + return getThemedColor(Theme.key_inappPlayerPerformer); + } else if (currentStyle == 1 || currentStyle == 3) { + return getThemedColor(Theme.key_returnToCallText); + } + return getThemedColor(Theme.key_inappPlayerTitle); + } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallFullscreenAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallFullscreenAdapter.java index 914a3404a..7441bf33c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallFullscreenAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallFullscreenAdapter.java @@ -7,7 +7,6 @@ import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; -import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.text.TextPaint; @@ -152,7 +151,7 @@ public class GroupCallFullscreenAdapter extends RecyclerListView.SelectionAdapte private BackupImageView avatarImageView; boolean hasAvatar; - int peerId; + long peerId; ChatObject.VideoParticipant videoParticipant; TLRPC.TL_groupCallParticipant participant; @@ -222,7 +221,7 @@ public class GroupCallFullscreenAdapter extends RecyclerListView.SelectionAdapte public void setParticipant(ChatObject.VideoParticipant videoParticipant, TLRPC.TL_groupCallParticipant participant) { this.videoParticipant = videoParticipant; this.participant = participant; - int lastPeerId = peerId; + long lastPeerId = peerId; peerId = MessageObject.getPeerId(participant.peer); if (peerId > 0) { currentUser = AccountInstance.getInstance(currentAccount).getMessagesController().getUser(peerId); @@ -366,7 +365,7 @@ public class GroupCallFullscreenAdapter extends RecyclerListView.SelectionAdapte } } - public int getPeerId() { + public long getPeerId() { return peerId; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallPip.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallPip.java index d3aebbb50..7a0df8e92 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallPip.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallPip.java @@ -680,7 +680,7 @@ public class GroupCallPip implements NotificationCenter.NotificationCenterDelega call = null; } if (call != null) { - int selfId = voIPService.getSelfId(); + long selfId = voIPService.getSelfId(); for (int a = 0, N = call.sortedParticipants.size(), k = 0; k < 2; a++) { if (a < N) { TLRPC.TL_groupCallParticipant participant = call.sortedParticipants.get(a); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallRecordAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallRecordAlert.java index 3207d8e31..71e169f4e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallRecordAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCallRecordAlert.java @@ -45,7 +45,7 @@ public class GroupCallRecordAlert extends BottomSheet { private float pageOffset; private int currentPage; - public GroupCallRecordAlert(Context context, TLRPC.Chat chat) { + public GroupCallRecordAlert(Context context, TLRPC.Chat chat, boolean hasVideo) { super(context, false); int color = Theme.getColor(Theme.key_voipgroup_inviteMembersBackground); @@ -239,6 +239,9 @@ public class GroupCallRecordAlert extends BottomSheet { int num = a; titles[a].setOnClickListener(view -> viewPager.setCurrentItem(num, true)); } + if (hasVideo) { + viewPager.setCurrentItem(1); + } } private void updateTitlesLayout() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCreateSpan.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCreateSpan.java index 8a2fb3ef8..544cea424 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCreateSpan.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupCreateSpan.java @@ -38,7 +38,7 @@ import androidx.core.graphics.ColorUtils; public class GroupCreateSpan extends View { - private int uid; + private long uid; private String key; private static TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private static Paint backPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -226,7 +226,7 @@ public class GroupCreateSpan extends View { invalidate(); } - public int getUid() { + public long getUid() { return uid; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupVoipInviteAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupVoipInviteAlert.java index d9e8d6192..85b26f219 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupVoipInviteAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupVoipInviteAlert.java @@ -13,7 +13,6 @@ import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; -import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; @@ -43,6 +42,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.RecyclerView; public class GroupVoipInviteAlert extends UsersAlertBase { @@ -57,13 +57,13 @@ public class GroupVoipInviteAlert extends UsersAlertBase { private ArrayList participants = new ArrayList<>(); private ArrayList contacts = new ArrayList<>(); private boolean contactsEndReached; - private SparseArray participantsMap = new SparseArray<>(); - private SparseArray contactsMap = new SparseArray<>(); + private LongSparseArray participantsMap = new LongSparseArray<>(); + private LongSparseArray contactsMap = new LongSparseArray<>(); private boolean loadingUsers; private boolean firstLoaded; - private SparseArray ignoredUsers; - private HashSet invitedUsers; + private LongSparseArray ignoredUsers; + private HashSet invitedUsers; private GroupVoipInviteAlertDelegate delegate; @@ -83,7 +83,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { public interface GroupVoipInviteAlertDelegate { void copyInviteLink(); - void inviteUser(int id); + void inviteUser(long id); void needOpenSearch(MotionEvent ev, EditTextBoldCursor editText); } @@ -104,8 +104,8 @@ public class GroupVoipInviteAlert extends UsersAlertBase { keySearchIconUnscrolled = Theme.key_voipgroup_mutedIconUnscrolled; } - public GroupVoipInviteAlert(final Context context, int account, TLRPC.Chat chat, TLRPC.ChatFull chatFull, SparseArray participants, HashSet invited) { - super(context, false, account); + public GroupVoipInviteAlert(final Context context, int account, TLRPC.Chat chat, TLRPC.ChatFull chatFull, LongSparseArray participants, HashSet invited) { + super(context, false, account, null); setDimBehindAlpha(75); @@ -114,10 +114,6 @@ public class GroupVoipInviteAlert extends UsersAlertBase { ignoredUsers = participants; invitedUsers = invited; - currentChat = chat; - info = chatFull; - ignoredUsers = participants; - invitedUsers = invited; listView.setOnItemClickListener((view, position) -> { if (position == addNewRow) { delegate.copyInviteLink(); @@ -195,13 +191,13 @@ public class GroupVoipInviteAlert extends UsersAlertBase { return; } contacts.addAll(ContactsController.getInstance(currentAccount).contacts); - int selfId = UserConfig.getInstance(currentAccount).clientUserId; + long selfId = UserConfig.getInstance(currentAccount).clientUserId; for (int a = 0, N = contacts.size(); a < N; a++) { TLObject object = contacts.get(a); if (!(object instanceof TLRPC.TL_contact)) { continue; } - int userId = ((TLRPC.TL_contact) contacts.get(a)).user_id; + long userId = ((TLRPC.TL_contact) object).user_id; if (userId == selfId || ignoredUsers.indexOfKey(userId) >= 0 || invitedUsers.contains(userId)) { contacts.remove(a); a--; @@ -260,7 +256,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { participantsMap.clear(); contactsMap.clear(); if (info != null) { - int selfUserId = UserConfig.getInstance(currentAccount).clientUserId; + long selfUserId = UserConfig.getInstance(currentAccount).clientUserId; for (int a = 0, size = info.participants.participants.size(); a < size; a++) { TLRPC.ChatParticipant participant = info.participants.participants.get(a); if (participant.user_id == selfUserId) { @@ -315,7 +311,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response; MessagesController.getInstance(currentAccount).putUsers(res.users, false); MessagesController.getInstance(currentAccount).putChats(res.chats, false); - int selfId = UserConfig.getInstance(currentAccount).getClientUserId(); + long selfId = UserConfig.getInstance(currentAccount).getClientUserId(); for (int a = 0; a < res.participants.size(); a++) { if (MessageObject.getPeerId(res.participants.get(a).peer) == selfId) { res.participants.remove(a); @@ -323,7 +319,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { } } ArrayList objects; - SparseArray map; + LongSparseArray map; delayResults--; if (req.filter instanceof TLRPC.TL_channelParticipantsContacts) { objects = contacts; @@ -340,7 +336,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { } for (int a = 0, N = participants.size(); a < N; a++) { TLRPC.ChannelParticipant participant = (TLRPC.ChannelParticipant) participants.get(a); - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); boolean remove = false; if (contactsMap.get(peerId) != null) { remove = true; @@ -473,7 +469,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { } @Override - public SparseArray getExcludeCallParticipants() { + public LongSparseArray getExcludeCallParticipants() { return ignoredUsers; } }); @@ -534,40 +530,38 @@ public class GroupVoipInviteAlert extends UsersAlertBase { } ArrayList resultArray2 = new ArrayList<>(); - if (participantsCopy != null) { - for (int a = 0, N = participantsCopy.size(); a < N; a++) { - int userId; - TLObject o = participantsCopy.get(a); - if (o instanceof TLRPC.ChatParticipant) { - userId = ((TLRPC.ChatParticipant) o).user_id; - } else if (o instanceof TLRPC.ChannelParticipant) { - userId = MessageObject.getPeerId(((TLRPC.ChannelParticipant) o).peer); - } else { - continue; - } - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userId); - if (UserObject.isUserSelf(user)) { - continue; + for (int a = 0, N = participantsCopy.size(); a < N; a++) { + long userId; + TLObject o = participantsCopy.get(a); + if (o instanceof TLRPC.ChatParticipant) { + userId = ((TLRPC.ChatParticipant) o).user_id; + } else if (o instanceof TLRPC.ChannelParticipant) { + userId = MessageObject.getPeerId(((TLRPC.ChannelParticipant) o).peer); + } else { + continue; + } + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userId); + if (UserObject.isUserSelf(user)) { + continue; + } + + String name = UserObject.getUserName(user).toLowerCase(); + String tName = LocaleController.getInstance().getTranslitString(name); + if (name.equals(tName)) { + tName = null; + } + + int found = 0; + for (String q : search) { + if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { + found = 1; + } else if (user.username != null && user.username.startsWith(q)) { + found = 2; } - String name = UserObject.getUserName(user).toLowerCase(); - String tName = LocaleController.getInstance().getTranslitString(name); - if (name.equals(tName)) { - tName = null; - } - - int found = 0; - for (String q : search) { - if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) { - found = 1; - } else if (user.username != null && user.username.startsWith(q)) { - found = 2; - } - - if (found != 0) { - resultArray2.add(o); - break; - } + if (found != 0) { + resultArray2.add(o); + break; } } } @@ -875,7 +869,7 @@ public class GroupVoipInviteAlert extends UsersAlertBase { lastRow = contactsEndRow; } - int userId; + long userId; if (item instanceof TLRPC.TL_contact) { TLRPC.TL_contact contact = (TLRPC.TL_contact) item; userId = contact.user_id; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupedPhotosListView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupedPhotosListView.java index 659187aaa..fa5876edd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupedPhotosListView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/GroupedPhotosListView.java @@ -65,7 +65,7 @@ public class GroupedPhotosListView extends View implements GestureDetector.OnGes public interface GroupedPhotosListViewDelegate { int getCurrentIndex(); int getCurrentAccount(); - int getAvatarsDialogId(); + long getAvatarsDialogId(); int getSlideshowMessageId(); ArrayList getImagesArrLocations(); ArrayList getImagesArr(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/HintView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/HintView.java index 982bac2dc..53782c916 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/HintView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/HintView.java @@ -48,19 +48,29 @@ public class HintView extends FrameLayout { private int bottomOffset; private long showingDuration = 2000; + private final Theme.ResourcesProvider resourcesProvider; public HintView(Context context, int type) { - this(context, type, false); + this(context, type, false, null); } public HintView(Context context, int type, boolean topArrow) { + this(context, type, topArrow, null); + } + + public HintView(Context context, int type, Theme.ResourcesProvider resourcesProvider) { + this(context, type, false, resourcesProvider); + } + + public HintView(Context context, int type, boolean topArrow, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; currentType = type; isTopArrow = topArrow; textView = new CorrectlyMeasuringTextView(context); - textView.setTextColor(Theme.getColor(Theme.key_chat_gifSaveHintText)); + textView.setTextColor(getThemedColor(Theme.key_chat_gifSaveHintText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setMaxLines(2); if (type == 7 || type == 8 || type == 9) { @@ -72,12 +82,12 @@ public class HintView extends FrameLayout { } if (currentType == TYPE_SEARCH_AS_LIST) { textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); - textView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(5), Theme.getColor(Theme.key_chat_gifSaveHintBackground))); + textView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(5), getThemedColor(Theme.key_chat_gifSaveHintBackground))); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 30, Gravity.LEFT | Gravity.TOP, 0, topArrow ? 6 : 0, 0, topArrow ? 0 : 6)); } else { textView.setGravity(Gravity.LEFT | Gravity.TOP); - textView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(currentType == 7 || currentType == 8 || currentType == 9 ? 6 : 3), Theme.getColor(Theme.key_chat_gifSaveHintBackground))); + textView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(currentType == 7 || currentType == 8 || currentType == 9 ? 6 : 3), getThemedColor(Theme.key_chat_gifSaveHintBackground))); if (currentType == TYPE_POLL_VOTE || currentType == 4) { textView.setPadding(AndroidUtilities.dp(9), AndroidUtilities.dp(6), AndroidUtilities.dp(9), AndroidUtilities.dp(7)); } else if (currentType == 2) { @@ -96,13 +106,13 @@ public class HintView extends FrameLayout { imageView = new ImageView(context); imageView.setImageResource(R.drawable.tooltip_sound); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_gifSaveHintText), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_gifSaveHintText), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(38, 34, Gravity.LEFT | Gravity.TOP, 7, 7, 0, 0)); } arrowImageView = new ImageView(context); arrowImageView.setImageResource(topArrow ? R.drawable.tooltip_arrow_up : R.drawable.tooltip_arrow); - arrowImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); + arrowImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_gifSaveHintBackground), PorterDuff.Mode.MULTIPLY)); addView(arrowImageView, LayoutHelper.createFrame(14, 6, Gravity.LEFT | (topArrow ? Gravity.TOP : Gravity.BOTTOM), 0, 0, 0, 0)); } @@ -467,4 +477,9 @@ public class HintView extends FrameLayout { public void setBottomOffset(int offset) { this.bottomOffset = offset; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ImportingAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ImportingAlert.java index 35af7569a..4d093fbdd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ImportingAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ImportingAlert.java @@ -52,12 +52,14 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No private TextView textView; private RLottieImageView imageView; private LinearLayout linearLayout; + private Theme.ResourcesProvider resourcesProvider; - public BottomSheetCell(Context context) { + public BottomSheetCell(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; background = new View(context); - background.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + background.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); addView(background, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 16, 16, 16, 16)); linearLayout = new LinearLayout(context); @@ -65,9 +67,9 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER)); imageView = new RLottieImageView(context); - imageView.setBackground(Theme.createCircleDrawable(AndroidUtilities.dp(20), Theme.getColor(Theme.key_featuredStickers_buttonText))); + imageView.setBackground(Theme.createCircleDrawable(AndroidUtilities.dp(20), getThemedColor(Theme.key_featuredStickers_buttonText))); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_featuredStickers_addButton), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_featuredStickers_addButton), PorterDuff.Mode.MULTIPLY)); imageView.setAnimation(R.raw.import_check, 26, 26); imageView.setScaleX(0.8f); imageView.setScaleY(0.8f); @@ -79,7 +81,7 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setGravity(Gravity.CENTER); - textView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + textView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); linearLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 10, 0, 0, 0)); @@ -101,6 +103,11 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No public void setText(CharSequence text) { textView.setText(text); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } @SuppressWarnings("FieldCanBeLocal") @@ -112,8 +119,8 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No } }; - public ImportingAlert(final Context context, String shortName, ChatActivity chatActivity) { - super(context, false); + public ImportingAlert(final Context context, String shortName, ChatActivity chatActivity, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); setApplyBottomPadding(false); setApplyTopPadding(false); parentFragment = chatActivity; @@ -125,7 +132,7 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No TextView textView = new TextView(context); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 17, 20, 17, 0)); @@ -143,15 +150,15 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No percentTextView = new TextView(context); percentTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); percentTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24); - percentTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + percentTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); frameLayout.addView(percentTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 17, 262, 17, 0)); lineProgressView = new LineProgressView(getContext()); - lineProgressView.setProgressColor(Theme.getColor(Theme.key_featuredStickers_addButton)); - lineProgressView.setBackColor(Theme.getColor(Theme.key_dialogLineProgressBackground)); + lineProgressView.setProgressColor(getThemedColor(Theme.key_featuredStickers_addButton)); + lineProgressView.setBackColor(getThemedColor(Theme.key_dialogLineProgressBackground)); frameLayout.addView(lineProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 4, Gravity.LEFT | Gravity.TOP, 50, 307, 50, 0)); - cell = new BottomSheetCell(context); + cell = new BottomSheetCell(context, resourcesProvider); cell.setBackground(null); cell.setText(LocaleController.getString("ImportDone", R.string.ImportDone)); cell.setVisibility(View.INVISIBLE); @@ -164,12 +171,12 @@ public class ImportingAlert extends BottomSheet implements NotificationCenter.No importCountTextView[a] = new TextView(context); importCountTextView[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); importCountTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - importCountTextView[a].setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + importCountTextView[a].setTextColor(getThemedColor(Theme.key_dialogTextBlack)); frameLayout.addView(importCountTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 17, 340, 17, 0)); infoTextView[a] = new TextView(context); infoTextView[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - infoTextView[a].setTextColor(Theme.getColor(Theme.key_dialogTextGray3)); + infoTextView[a].setTextColor(getThemedColor(Theme.key_dialogTextGray3)); infoTextView[a].setGravity(Gravity.CENTER_HORIZONTAL); frameLayout.addView(infoTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 30, 368, 30, 44)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/InstantCameraView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/InstantCameraView.java index e3bc56aa8..76c57fca1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/InstantCameraView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/InstantCameraView.java @@ -221,10 +221,12 @@ public class InstantCameraView extends FrameLayout implements NotificationCenter private int textureViewSize; private boolean isMessageTransition; private boolean updateTextureViewSize; + private final Theme.ResourcesProvider resourcesProvider; @SuppressLint("ClickableViewAccessibility") - public InstantCameraView(Context context, ChatActivity parentFragment) { + public InstantCameraView(Context context, ChatActivity parentFragment, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; parentView = parentFragment.getFragmentView(); setWillNotDraw(false); @@ -354,7 +356,7 @@ public class InstantCameraView extends FrameLayout implements NotificationCenter addView(textureOverlayView, new FrameLayout.LayoutParams(AndroidUtilities.roundPlayingMessageSize, AndroidUtilities.roundPlayingMessageSize, Gravity.CENTER)); setVisibility(INVISIBLE); - blurBehindDrawable = new BlurBehindDrawable(parentView, this, 0); + blurBehindDrawable = new BlurBehindDrawable(parentView, this, 0, null); } @Override @@ -2042,7 +2044,7 @@ public class InstantCameraView extends FrameLayout implements NotificationCenter startAnimation(false); }, () -> { startAnimation(false); - }); + }, resourcesProvider); } else { baseFragment.sendMedia(new MediaController.PhotoEntry(0, 0, 0, videoFile.getAbsolutePath(), 0, true, 0, 0, 0), videoEditedInfo, true, 0, false); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteLinkBottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteLinkBottomSheet.java index 4c7e411a2..f841433e2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteLinkBottomSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteLinkBottomSheet.java @@ -52,7 +52,7 @@ import java.util.Locale; public class InviteLinkBottomSheet extends BottomSheet { TLRPC.TL_chatInviteExported invite; - HashMap users; + HashMap users; TLRPC.ChatFull info; int creatorHeaderRow; @@ -88,7 +88,7 @@ public class InviteLinkBottomSheet extends BottomSheet { ArrayList invitedUsers = new ArrayList<>(); - private int chatId; + private long chatId; private boolean isChannel; private final long timeDif; @@ -96,7 +96,7 @@ public class InviteLinkBottomSheet extends BottomSheet { private boolean canEdit = true; - public InviteLinkBottomSheet(Context context, TLRPC.TL_chatInviteExported invite, TLRPC.ChatFull info, HashMap users, BaseFragment fragment, int chatId, boolean permanent, boolean isChannel) { + public InviteLinkBottomSheet(Context context, TLRPC.TL_chatInviteExported invite, TLRPC.ChatFull info, HashMap users, BaseFragment fragment, long chatId, boolean permanent, boolean isChannel) { super(context, false); this.invite = invite; this.users = users; @@ -279,7 +279,7 @@ public class InviteLinkBottomSheet extends BottomSheet { } if (user != null) { Bundle bundle = new Bundle(); - bundle.putInt("user_id", user.id); + bundle.putLong("user_id", user.id); MessagesController.getInstance(UserConfig.selectedAccount).putUser(user, false); ProfileActivity profileActivity = new ProfileActivity(bundle); fragment.presentFragment(profileActivity); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteMembersBottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteMembersBottomSheet.java index 980aa2443..50d9467f3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteMembersBottomSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/InviteMembersBottomSheet.java @@ -20,7 +20,6 @@ import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; -import android.util.SparseArray; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; @@ -31,6 +30,7 @@ import android.widget.ImageView; import android.widget.ScrollView; import androidx.annotation.NonNull; +import androidx.collection.LongSparseArray; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.RecyclerView; @@ -38,6 +38,7 @@ import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; @@ -61,7 +62,7 @@ import java.util.ArrayList; public class InviteMembersBottomSheet extends UsersAlertBase implements NotificationCenter.NotificationCenterDelegate { - private SparseArray ignoreUsers; + private LongSparseArray ignoreUsers; private final SpansContainer spansContainer; private final ScrollView spansScrollView; private SearchAdapter searchAdapter; @@ -78,7 +79,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica private AnimatorSet currentAnimation; private ArrayList contacts = new ArrayList<>(); - private SparseArray selectedContacts = new SparseArray<>(); + private LongSparseArray selectedContacts = new LongSparseArray<>(); private boolean spanEnter; private float spansEnterProgress = 0; @@ -117,14 +118,14 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica private final ImageView floatingButton; private AnimatorSet currentDoneButtonAnimation; private int searchAdditionalHeight; - private int chatId; + private long chatId; public interface InviteMembersBottomSheetDelegate { void didSelectDialogs(ArrayList dids); } - public InviteMembersBottomSheet(Context context, int account, SparseArray ignoreUsers, int chatId, BaseFragment parentFragment) { - super(context, false, account); + public InviteMembersBottomSheet(Context context, int account, LongSparseArray ignoreUsers, long chatId, BaseFragment parentFragment, Theme.ResourcesProvider resourcesProvider) { + super(context, false, account, null); this.ignoreUsers = ignoreUsers; needSnapToTop = false; this.parentFragment = parentFragment; @@ -195,7 +196,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica } if (object != null) { - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { @@ -287,8 +288,8 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica if (dialogsDelegate != null) { ArrayList dialogs = new ArrayList<>(); for (int a = 0; a < selectedContacts.size(); a++) { - int uid = selectedContacts.keyAt(a); - dialogs.add((long) uid); + long uid = selectedContacts.keyAt(a); + dialogs.add(uid); } dialogsDelegate.didSelectDialogs(dialogs); dismiss(); @@ -301,7 +302,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica } StringBuilder stringBuilder = new StringBuilder(); for (int a = 0; a < selectedContacts.size(); a++) { - int uid = selectedContacts.keyAt(a); + long uid = selectedContacts.keyAt(a); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid); if (user == null) { continue; @@ -362,12 +363,12 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica public void setSelectedContacts(ArrayList dialogs) { for (int a = 0, N = dialogs.size(); a < N; a++) { - int lowerId = (int) (long) dialogs.get(a); + long dialogId = dialogs.get(a); TLObject object; - if (lowerId < 0) { - object = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(dialogId)) { + object = MessagesController.getInstance(currentAccount).getChat(-dialogId); } else { - object = MessagesController.getInstance(currentAccount).getUser(lowerId); + object = MessagesController.getInstance(currentAccount).getUser(dialogId); } GroupCreateSpan span = new GroupCreateSpan(spansContainer.getContext(), object); spansContainer.addSpan(span, false); @@ -598,11 +599,10 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica public TLObject getObject(int position) { if (dialogsDelegate != null) { TLRPC.Dialog dialog = dialogsServerOnly.get(position - contactsStartRow); - int lowerId = (int) dialog.id; - if (lowerId > 0) { - return MessagesController.getInstance(currentAccount).getUser(lowerId); + if (DialogObject.isUserDialog(dialog.id)) { + return MessagesController.getInstance(currentAccount).getUser(dialog.id); } else { - return MessagesController.getInstance(currentAccount).getChat(-lowerId); + return MessagesController.getInstance(currentAccount).getChat(-dialog.id); } } else { return contacts.get(position - contactsStartRow); @@ -620,7 +620,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica TLObject object = getObject(position); Object oldObject = cell.getObject(); - int oldId; + long oldId; if (oldObject instanceof TLRPC.User) { oldId = ((TLRPC.User) oldObject).id; } else if (oldObject instanceof TLRPC.Chat) { @@ -630,7 +630,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica } cell.setObject(object, null, null, position != contactsEndRow); - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { @@ -811,7 +811,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica Object oldObject = cell.getObject(); - int oldId; + long oldId; if (oldObject instanceof TLRPC.User) { oldId = ((TLRPC.User) oldObject).id; } else if (oldObject instanceof TLRPC.Chat) { @@ -821,7 +821,7 @@ public class InviteMembersBottomSheet extends UsersAlertBase implements Notifica } cell.setObject(object, name, username); - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinCallAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinCallAlert.java index 477b24820..ef030ee6f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinCallAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinCallAlert.java @@ -24,6 +24,7 @@ import android.widget.TextView; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; @@ -180,7 +181,7 @@ public class JoinCallAlert extends BottomSheet { } } - public static void checkFewUsers(Context context, int did, AccountInstance accountInstance, MessagesStorage.BooleanCallback callback) { + public static void checkFewUsers(Context context, long did, AccountInstance accountInstance, MessagesStorage.BooleanCallback callback) { if (lastCachedAccount == accountInstance.getCurrentAccount() && lastCacheDid == did && cachedChats != null && SystemClock.elapsedRealtime() - lastCacheTime < 4 * 60 * 1000) { callback.run(cachedChats.size() == 1); return; @@ -213,7 +214,7 @@ public class JoinCallAlert extends BottomSheet { } } - public static void open(Context context, int did, AccountInstance accountInstance, BaseFragment fragment, int type, TLRPC.Peer scheduledPeer, JoinCallAlertDelegate delegate) { + public static void open(Context context, long did, AccountInstance accountInstance, BaseFragment fragment, int type, TLRPC.Peer scheduledPeer, JoinCallAlertDelegate delegate) { if (context == null || delegate == null) { return; } @@ -280,7 +281,7 @@ public class JoinCallAlert extends BottomSheet { shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); if (type == TYPE_DISPLAY) { if (VoIPService.getSharedInstance() != null) { - int did = VoIPService.getSharedInstance().getSelfId(); + long did = VoIPService.getSharedInstance().getSelfId(); for (int a = 0, N = chats.size(); a < N; a++) { TLRPC.Peer p = chats.get(a); if (MessageObject.getPeerId(p) == did) { @@ -420,7 +421,7 @@ public class JoinCallAlert extends BottomSheet { containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0); } - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat((int) -dialogId); //TODO long + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); listView = new RecyclerListView(context) { @Override @@ -522,7 +523,7 @@ public class JoinCallAlert extends BottomSheet { messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); boolean hasGroup = false; for (int a = 0, N = chats.size(); a < N; a++) { - int peerId = MessageObject.getPeerId(chats.get(a)); + long peerId = MessageObject.getPeerId(chats.get(a)); if (peerId < 0) { TLRPC.Chat peerChat = MessagesController.getInstance(currentAccount).getChat(-peerId); if (!ChatObject.isChannel(peerChat) || peerChat.megagroup) { @@ -603,8 +604,8 @@ public class JoinCallAlert extends BottomSheet { doneButton.setText(LocaleController.formatString("VoipGroupStartVoiceChat", R.string.VoipGroupStartVoiceChat), animated); } } else { - int did = MessageObject.getPeerId(selectedPeer); - if (did > 0) { + long did = MessageObject.getPeerId(selectedPeer); + if (DialogObject.isUserDialog(did)) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); doneButton.setText(LocaleController.formatString("VoipGroupContinueAs", R.string.VoipGroupContinueAs, UserObject.getFirstName(user)), animated); } else { @@ -675,7 +676,7 @@ public class JoinCallAlert extends BottomSheet { public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (currentType == TYPE_CREATE) { - view = new ShareDialogCell(context, ShareDialogCell.TYPE_CREATE); + view = new ShareDialogCell(context, ShareDialogCell.TYPE_CREATE, null); view.setLayoutParams(new RecyclerView.LayoutParams(AndroidUtilities.dp(80), AndroidUtilities.dp(100))); } else { view = new GroupCreateUserCell(context, 2, 0, false, currentType == TYPE_DISPLAY); @@ -708,7 +709,7 @@ public class JoinCallAlert extends BottomSheet { @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { - int did = MessageObject.getPeerId(chats.get(position)); + long did = MessageObject.getPeerId(chats.get(position)); TLObject object; String status; if (did > 0) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinGroupAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinGroupAlert.java index cb23c73a1..643d5b0e2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinGroupAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/JoinGroupAlert.java @@ -155,7 +155,7 @@ public class JoinGroupAlert extends BottomSheet { MessagesController.getInstance(currentAccount).putUsers(updates.users, false); MessagesController.getInstance(currentAccount).putChats(updates.chats, false); Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, fragment)) { ChatActivity chatActivity = new ChatActivity(args); fragment.presentFragment(chatActivity, fragment instanceof ChatActivity); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/LinkActionView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/LinkActionView.java index cff80a497..df574cc8f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/LinkActionView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/LinkActionView.java @@ -6,14 +6,12 @@ import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; -import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; -import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; @@ -75,7 +73,7 @@ public class LinkActionView extends LinearLayout { float[] point = new float[2]; - public LinkActionView(Context context, BaseFragment fragment, BottomSheet bottomSheet, int chatId, boolean permanent, boolean isChannel) { + public LinkActionView(Context context, BaseFragment fragment, BottomSheet bottomSheet, long chatId, boolean permanent, boolean isChannel) { super(context); this.fragment = fragment; this.permanent = permanent; @@ -503,7 +501,7 @@ public class LinkActionView extends LinearLayout { } } - public void loadUsers(TLRPC.TL_chatInviteExported invite, int chatId) { + public void loadUsers(TLRPC.TL_chatInviteExported invite, long chatId) { if (invite == null) { setUsers(0, null); return; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/MotionBackgroundDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/MotionBackgroundDrawable.java index 70d84c936..56bfefc96 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/MotionBackgroundDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/MotionBackgroundDrawable.java @@ -1,5 +1,6 @@ package org.telegram.ui.Components; +import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.BlendMode; @@ -11,6 +12,7 @@ import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; @@ -20,8 +22,9 @@ import android.os.Build; import android.os.SystemClock; import android.view.View; +import androidx.core.graphics.ColorUtils; + import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.Utilities; @@ -31,6 +34,9 @@ public class MotionBackgroundDrawable extends Drawable { private final static int ANIMATION_CACHE_BITMAPS_COUNT = 3; + private static final boolean useLegacyBitmap = Build.VERSION.SDK_INT < 28; + private static final boolean useSoftLight = Build.VERSION.SDK_INT >= 29; + private int[] colors = new int[]{ 0xff426D57, 0xffF7E48B, @@ -72,6 +78,9 @@ public class MotionBackgroundDrawable extends Drawable { private Canvas legacyCanvas; private Bitmap legacyBitmap; + private Canvas legacyCanvas2; + private Bitmap legacyBitmap2; + private boolean invalidateLegacy; private boolean rotationBack; @@ -81,7 +90,10 @@ public class MotionBackgroundDrawable extends Drawable { private android.graphics.Rect patternBounds = new android.graphics.Rect(); + private ColorFilter patternColorFilter; private int roundRadius; + private float patternAlpha = 1f; + private int alpha = 255; public MotionBackgroundDrawable() { super(); @@ -98,6 +110,7 @@ public class MotionBackgroundDrawable extends Drawable { init(); } + @SuppressLint("NewApi") private void init() { currentBitmap = Bitmap.createBitmap(60, 80, Bitmap.Config.ARGB_8888); for (int i = 0; i < ANIMATION_CACHE_BITMAPS_COUNT; i++) { @@ -109,7 +122,7 @@ public class MotionBackgroundDrawable extends Drawable { gradientFromCanvas = new Canvas(gradientFromBitmap); Utilities.generateGradient(currentBitmap, true, phase, interpolator.getInterpolation(posAnimationProgress), currentBitmap.getWidth(), currentBitmap.getHeight(), currentBitmap.getRowBytes(), colors); - if (Build.VERSION.SDK_INT >= 29) { + if (useSoftLight) { paint2.setBlendMode(BlendMode.SOFT_LIGHT); } } @@ -158,9 +171,9 @@ public class MotionBackgroundDrawable extends Drawable { public static int getPatternColor(int color1, int color2, int color3, int color4) { if (isDark(color1, color2, color3, color4)) { - return Build.VERSION.SDK_INT < 29 ? 0x7fffffff : 0xffffffff; + return !useSoftLight ? 0x7fffffff : 0xffffffff; } else { - if (Build.VERSION.SDK_INT < 29) { + if (!useSoftLight) { int averageColor = AndroidUtilities.getAverageColor(color3, AndroidUtilities.getAverageColor(color1, color2)); if (color4 != 0) { averageColor = AndroidUtilities.getAverageColor(color4, averageColor); @@ -226,6 +239,22 @@ public class MotionBackgroundDrawable extends Drawable { } private void generateNextGradient() { + if (useLegacyBitmap && intensity < 0) { + if (legacyBitmap != null) { + if (legacyBitmap2 == null || legacyBitmap2.getHeight() != legacyBitmap.getHeight() || legacyBitmap2.getWidth() != legacyBitmap.getWidth()) { + if (legacyBitmap2 != null) { + legacyBitmap2.recycle(); + } + legacyBitmap2 = Bitmap.createBitmap(legacyBitmap.getWidth(), legacyBitmap.getHeight(), Bitmap.Config.ARGB_8888); + legacyCanvas2 = new Canvas(legacyBitmap2); + } else { + legacyBitmap2.eraseColor(Color.TRANSPARENT); + } + legacyCanvas2.drawBitmap(legacyBitmap,0 ,0, null); + } + Utilities.generateGradient(currentBitmap, true, phase, 1f, currentBitmap.getWidth(), currentBitmap.getHeight(), currentBitmap.getRowBytes(), colors); + invalidateLegacy = true; + } for (int i = 0; i < ANIMATION_CACHE_BITMAPS_COUNT; i++) { float p = (i + 1) / (float) ANIMATION_CACHE_BITMAPS_COUNT; Utilities.generateGradient(gradientToBitmap[i], true, phase, p, currentBitmap.getWidth(), currentBitmap.getHeight(), currentBitmap.getRowBytes(), colors); @@ -257,6 +286,14 @@ public class MotionBackgroundDrawable extends Drawable { setColors(c1, c2, c3, c4, true); } + public void setColors(int c1, int c2, int c3, int c4, Bitmap bitmap) { + colors[0] = c1; + colors[1] = c2; + colors[2] = c3; + colors[3] = c4; + Utilities.generateGradient(bitmap, true, phase, interpolator.getInterpolation(posAnimationProgress), currentBitmap.getWidth(), currentBitmap.getHeight(), currentBitmap.getRowBytes(), colors); + } + public void setColors(int c1, int c2, int c3, int c4, boolean invalidate) { colors[0] = c1; colors[1] = c2; @@ -269,6 +306,7 @@ public class MotionBackgroundDrawable extends Drawable { } private void invalidateParent() { + invalidateSelf(); if (parentView != null && parentView.get() != null) { parentView.get().invalidate(); } @@ -278,6 +316,7 @@ public class MotionBackgroundDrawable extends Drawable { AndroidUtilities.cancelRunOnUIThread(updateAnimationRunnable); AndroidUtilities.runOnUIThread(updateAnimationRunnable, 16); } + // invalidateLegacy = true; } public boolean hasPattern() { @@ -304,10 +343,20 @@ public class MotionBackgroundDrawable extends Drawable { translationY = y; } + public void setPatternBitmap(int intensity) { + setPatternBitmap(intensity, patternBitmap); + + } + + @SuppressLint("NewApi") public void setPatternBitmap(int intensity, Bitmap bitmap) { this.intensity = intensity; patternBitmap = bitmap; - if (Build.VERSION.SDK_INT >= 29) { + invalidateLegacy = true; + if (patternBitmap == null) { + return; + } + if (useSoftLight) { if (intensity >= 0) { paint2.setBlendMode(BlendMode.SOFT_LIGHT); } else { @@ -315,30 +364,56 @@ public class MotionBackgroundDrawable extends Drawable { } } if (intensity < 0) { - if (Build.VERSION.SDK_INT >= 28) { + if (!useLegacyBitmap) { bitmapShader = new BitmapShader(currentBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); gradientShader = new BitmapShader(patternBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); paint2.setShader(new ComposeShader(bitmapShader, gradientShader, PorterDuff.Mode.DST_IN)); matrix = new Matrix(); } else { + createLegacyBitmap(); paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } + } else { + if (!useLegacyBitmap) { + + } else { + paint2.setXfermode(null); + } } } + public void setPatternColorFilter(int color) { + patternColorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN); + invalidateParent(); + } + + public void setPatternAlpha(float alpha) { + this.patternAlpha = alpha; + invalidateParent(); + } + @Override public void setBounds(int left, int top, int right, int bottom) { super.setBounds(left, top, right, bottom); patternBounds.set(left, top, right, bottom); - if (Build.VERSION.SDK_INT < 28 && intensity < 0) { - int w = right - left; - int h = bottom - top; + createLegacyBitmap(); + } + + private void createLegacyBitmap() { + if (useLegacyBitmap && intensity < 0) { + int w = patternBounds.width(); + int h = patternBounds.height(); if (w > 0 && h > 0 && (legacyBitmap == null || legacyBitmap.getWidth() != w || legacyBitmap.getHeight() != h)) { if (legacyBitmap != null) { legacyBitmap.recycle(); } + if (legacyBitmap2 != null) { + legacyBitmap2.recycle(); + legacyBitmap2 = null; + } legacyBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); legacyCanvas = new Canvas(legacyBitmap); + invalidateLegacy = true; } } } @@ -362,47 +437,70 @@ public class MotionBackgroundDrawable extends Drawable { y += bounds.top; canvas.clipRect(bounds.left, bounds.top, bounds.right, bounds.bottom); } - if (patternBitmap != null && intensity < 0) { - canvas.drawColor(0xff000000); - if (legacyBitmap != null) { - rect.set(0, 0, legacyBitmap.getWidth(), legacyBitmap.getHeight()); - legacyCanvas.drawBitmap(currentBitmap, null, rect, paint); + if (intensity < 0) { + canvas.drawColor(ColorUtils.setAlphaComponent(Color.BLACK, alpha)); + if (patternBitmap != null) { + if (useLegacyBitmap) { + if (legacyBitmap != null) { + if (invalidateLegacy) { + rect.set(0, 0, legacyBitmap.getWidth(), legacyBitmap.getHeight()); + int oldAlpha = paint.getAlpha(); + paint.setAlpha(255); + legacyCanvas.drawBitmap(currentBitmap, null, rect, paint); + paint.setAlpha(oldAlpha); - bitmapWidth = patternBitmap.getWidth(); - bitmapHeight = patternBitmap.getHeight(); - maxScale = Math.max(w / bitmapWidth, h / bitmapHeight); - width = bitmapWidth * maxScale; - height = bitmapHeight * maxScale; - x = (w - width) / 2; - y = (h - height) / 2; - rect.set(x, y, x + width, y + height); - legacyCanvas.drawBitmap(patternBitmap, null, rect, paint2); + bitmapWidth = patternBitmap.getWidth(); + bitmapHeight = patternBitmap.getHeight(); + maxScale = Math.max(w / bitmapWidth, h / bitmapHeight); + width = bitmapWidth * maxScale; + height = bitmapHeight * maxScale; + x = (w - width) / 2; + y = (h - height) / 2; + rect.set(x, y, x + width, y + height); - rect.set(bounds.left, bounds.top, bounds.right, bounds.bottom); - canvas.drawBitmap(legacyBitmap, null, rect, paint); - } else { - matrix.reset(); - matrix.setTranslate(x, y + tr); - float scaleW = (currentBitmap.getWidth() / (float) bounds.width()); - float scaleH = (currentBitmap.getHeight() / (float) bounds.height()); - float scale = 1.0f / Math.min(scaleW, scaleH); - matrix.preScale(scale, scale); - bitmapShader.setLocalMatrix(matrix); + paint2.setColorFilter(null); + paint2.setAlpha((int) ((Math.abs(intensity) / 100f) * 255)); + legacyCanvas.drawBitmap(patternBitmap, null, rect, paint2); + invalidateLegacy = false; + } - matrix.reset(); - bitmapWidth = patternBitmap.getWidth(); - bitmapHeight = patternBitmap.getHeight(); - maxScale = Math.max(w / bitmapWidth, h / bitmapHeight); - width = bitmapWidth * maxScale; - height = bitmapHeight * maxScale; - x = (w - width) / 2; - y = (h - height) / 2; - matrix.setTranslate(x, y + tr); - matrix.preScale(maxScale, maxScale); - gradientShader.setLocalMatrix(matrix); + rect.set(bounds.left, bounds.top, bounds.right, bounds.bottom); + if (legacyBitmap2 != null && posAnimationProgress != 1f) { + paint.setAlpha((int) (alpha * patternAlpha * (1f - posAnimationProgress))); + canvas.drawBitmap(legacyBitmap2, null, rect, paint); - rect.set(bounds.left, bounds.top, bounds.right, bounds.bottom); - canvas.drawRoundRect(rect, roundRadius, roundRadius, paint2); + paint.setAlpha((int) (alpha * patternAlpha * posAnimationProgress)); + canvas.drawBitmap(legacyBitmap, null, rect, paint); + paint.setAlpha(alpha); + } else { + canvas.drawBitmap(legacyBitmap, null, rect, paint); + } + } + } else { + matrix.reset(); + matrix.setTranslate(x, y + tr); + float scaleW = (currentBitmap.getWidth() / (float) bounds.width()); + float scaleH = (currentBitmap.getHeight() / (float) bounds.height()); + float scale = 1.0f / Math.min(scaleW, scaleH); + matrix.preScale(scale, scale); + bitmapShader.setLocalMatrix(matrix); + + matrix.reset(); + bitmapWidth = patternBitmap.getWidth(); + bitmapHeight = patternBitmap.getHeight(); + maxScale = Math.max(w / bitmapWidth, h / bitmapHeight); + width = bitmapWidth * maxScale; + height = bitmapHeight * maxScale; + x = (w - width) / 2; + y = (h - height) / 2; + matrix.setTranslate(x, y + tr); + matrix.preScale(maxScale, maxScale); + gradientShader.setLocalMatrix(matrix); + paint2.setColorFilter(null); + paint2.setAlpha((int) ((Math.abs(intensity) / 100f) * alpha * patternAlpha)); + rect.set(bounds.left, bounds.top, bounds.right, bounds.bottom); + canvas.drawRoundRect(rect, roundRadius, roundRadius, paint2); + } } } else { if (roundRadius != 0) { @@ -431,6 +529,9 @@ public class MotionBackgroundDrawable extends Drawable { x = (w - width) / 2; y = (h - height) / 2; rect.set(x, y, x + width, y + height); + + paint2.setColorFilter(patternColorFilter); + paint2.setAlpha((int) ((Math.abs(intensity) / 100f) * alpha * patternAlpha)); canvas.drawBitmap(patternBitmap, null, rect, paint2); } } @@ -524,29 +625,34 @@ public class MotionBackgroundDrawable extends Drawable { if (postInvalidateParent || rotatingPreview) { Utilities.generateGradient(currentBitmap, true, phase, progress, currentBitmap.getWidth(), currentBitmap.getHeight(), currentBitmap.getRowBytes(), colors); + invalidateLegacy = true; } else { - if (progress != 1f) { - float part = 1f / ANIMATION_CACHE_BITMAPS_COUNT; - int i = (int) (progress / part); - if (i == 0) { - gradientCanvas.drawBitmap(gradientFromBitmap, 0, 0, null); - } else { - gradientCanvas.drawBitmap(gradientToBitmap[i - 1], 0, 0, null); - } - float alpha = (progress - i * part) / part; - paint3.setAlpha((int) (255 * alpha)); - gradientCanvas.drawBitmap(gradientToBitmap[i], 0, 0, paint3); + if (useLegacyBitmap && intensity < 0) { + } else { - gradientCanvas.drawBitmap(gradientToBitmap[ANIMATION_CACHE_BITMAPS_COUNT - 1], 0, 0, paint3); + if (progress != 1f) { + float part = 1f / ANIMATION_CACHE_BITMAPS_COUNT; + int i = (int) (progress / part); + if (i == 0) { + gradientCanvas.drawBitmap(gradientFromBitmap, 0, 0, null); + } else { + gradientCanvas.drawBitmap(gradientToBitmap[i - 1], 0, 0, null); + } + float alpha = (progress - i * part) / part; + paint3.setAlpha((int) (255 * alpha)); + gradientCanvas.drawBitmap(gradientToBitmap[i], 0, 0, paint3); + } else { + gradientCanvas.drawBitmap(gradientToBitmap[ANIMATION_CACHE_BITMAPS_COUNT - 1], 0, 0, paint3); + } } } - invalidateParent(); } } @Override public void setAlpha(int alpha) { + this.alpha = alpha; paint.setAlpha(alpha); paint2.setAlpha(alpha); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/MsgClockDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/MsgClockDrawable.java index 8c500f66e..991ac933d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/MsgClockDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/MsgClockDrawable.java @@ -8,6 +8,7 @@ import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.graphics.ColorUtils; @@ -15,11 +16,12 @@ import org.telegram.messenger.AndroidUtilities; public class MsgClockDrawable extends Drawable { - Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - int alpha = 255; - int colorAlpha = 255; - - long startTime; + private ConstantState constantState; + private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private int alpha = 255; + private int colorAlpha = 255; + private long startTime; + private int color; public MsgClockDrawable() { paint.setStyle(Paint.Style.STROKE); @@ -50,8 +52,11 @@ public class MsgClockDrawable extends Drawable { } public void setColor(int color) { - colorAlpha = Color.alpha(color); - paint.setColor(color); + if (color != this.color) { + colorAlpha = Color.alpha(color); + paint.setColor(ColorUtils.setAlphaComponent(color, (int) (alpha * (colorAlpha / 255f)))); + } + this.color = color; } @Override @@ -82,4 +87,22 @@ public class MsgClockDrawable extends Drawable { return PixelFormat.TRANSPARENT; } + @Nullable + @Override + public ConstantState getConstantState() { + if (constantState == null) { + constantState = new ConstantState() { + @NonNull + @Override + public Drawable newDrawable() { + return new MsgClockDrawable(); + } + @Override + public int getChangingConfigurations() { + return 0; + } + }; + } + return constantState; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/NumberPicker.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/NumberPicker.java index e10abe87c..ed1fe3cf6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/NumberPicker.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/NumberPicker.java @@ -106,6 +106,7 @@ public class NumberPicker extends LinearLayout { private PressedStateHelper mPressedStateHelper; private int mLastHandledDownDpadKeyCode = -1; private SeekBarAccessibilityDelegate accessibilityDelegate; + private final Theme.ResourcesProvider resourcesProvider; private boolean drawDividers = true; @@ -138,7 +139,7 @@ public class NumberPicker extends LinearLayout { private void init() { mSolidColor = 0; mSelectionDivider = new Paint(); - mSelectionDivider.setColor(Theme.getColor(Theme.key_dialogButton)); + mSelectionDivider.setColor(getThemedColor(Theme.key_dialogButton)); mSelectionDividerHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDER_HEIGHT, getResources().getDisplayMetrics()); mSelectionDividersDistance = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_DEFAULT_SELECTION_DIVIDERS_DISTANCE, getResources().getDisplayMetrics()); @@ -166,7 +167,7 @@ public class NumberPicker extends LinearLayout { mInputText = new TextView(getContext()); mInputText.setGravity(Gravity.CENTER); mInputText.setSingleLine(true); - mInputText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + mInputText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); mInputText.setBackgroundResource(0); mInputText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); mInputText.setVisibility(INVISIBLE); @@ -230,11 +231,20 @@ public class NumberPicker extends LinearLayout { } public NumberPicker(Context context) { - this(context, 18); + this(context, null); + } + + public NumberPicker(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, 18, resourcesProvider); } public NumberPicker(Context context, int textSize) { + this(context, textSize, null); + } + + public NumberPicker(Context context, int textSize, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; mTextSize = AndroidUtilities.dp(textSize); init(); } @@ -1133,4 +1143,9 @@ public class NumberPicker extends LinearLayout { this.drawDividers = drawDividers; invalidate(); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PermanentLinkBottomSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PermanentLinkBottomSheet.java index f03edee43..0ee85f44f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PermanentLinkBottomSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PermanentLinkBottomSheet.java @@ -34,11 +34,11 @@ public class PermanentLinkBottomSheet extends BottomSheet { private final TextView manage; private final RLottieImageView imageView; private final LinkActionView linkActionView; - private int chatId; + private long chatId; private BaseFragment fragment; private boolean isChannel; - public PermanentLinkBottomSheet(Context context, boolean needFocus, BaseFragment fragment, TLRPC.ChatFull info, int chatId, boolean isChannel) { + public PermanentLinkBottomSheet(Context context, boolean needFocus, BaseFragment fragment, TLRPC.ChatFull info, long chatId, boolean isChannel) { super(context, needFocus); this.info = info; this.chatId = chatId; @@ -147,17 +147,13 @@ public class PermanentLinkBottomSheet extends BottomSheet { @Override public void show() { super.show(); - AndroidUtilities.runOnUIThread(() -> { - linkIcon.start(); - }, 50); + AndroidUtilities.runOnUIThread(() -> linkIcon.start(), 50); } @Override public ArrayList getThemeDescriptions() { ArrayList arrayList = new ArrayList<>(); - ThemeDescription.ThemeDescriptionDelegate descriptionDelegate = () -> { - updateColors(); - }; + ThemeDescription.ThemeDescriptionDelegate descriptionDelegate = this::updateColors; arrayList.add(new ThemeDescription(titleView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlackText)); arrayList.add(new ThemeDescription(subtitle, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteGrayText)); arrayList.add(new ThemeDescription(manage, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_windowBackgroundWhiteBlueText)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhonebookShareAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhonebookShareAlert.java index 72715bc8b..92419e29d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhonebookShareAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhonebookShareAlert.java @@ -41,7 +41,6 @@ import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLog; -import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.messenger.browser.Browser; @@ -123,7 +122,7 @@ public class PhonebookShareAlert extends BottomSheet { TextView textView = new TextView(context); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setText(ContactsController.formatName(currentUser.first_name, currentUser.last_name)); @@ -132,7 +131,7 @@ public class PhonebookShareAlert extends BottomSheet { if (status != null) { textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextGray3)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextGray3)); textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); textView.setText(status); @@ -153,7 +152,7 @@ public class PhonebookShareAlert extends BottomSheet { super(context); textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setSingleLine(false); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); @@ -161,7 +160,7 @@ public class PhonebookShareAlert extends BottomSheet { addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? (isImport ? 17 : 64) : 72, 10, LocaleController.isRTL ? 72 : (isImport ? 17 : 64), 0)); valueTextView = new TextView(context); - valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); + valueTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText2)); valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); valueTextView.setLines(1); valueTextView.setMaxLines(1); @@ -171,7 +170,7 @@ public class PhonebookShareAlert extends BottomSheet { imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY)); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 20, 20, LocaleController.isRTL ? 20 : 0, 0)); if (!isImport) { @@ -241,7 +240,11 @@ public class PhonebookShareAlert extends BottomSheet { } public PhonebookShareAlert(BaseFragment parent, ContactsController.Contact contact, TLRPC.User user, Uri uri, File file, String firstName, String lastName) { - super(parent.getParentActivity(), false); + this(parent, contact, user, uri, file, firstName, lastName, null); + } + + public PhonebookShareAlert(BaseFragment parent, ContactsController.Contact contact, TLRPC.User user, Uri uri, File file, String firstName, String lastName, Theme.ResourcesProvider resourcesProvider) { + super(parent.getParentActivity(), false, resourcesProvider); String name = ContactsController.formatName(firstName, lastName); ArrayList result = null; @@ -410,12 +413,12 @@ public class PhonebookShareAlert extends BottomSheet { shadowDrawable.draw(canvas); if (rad != 1.0f) { - backgroundPaint.setColor(Theme.getColor(Theme.key_dialogBackground)); + backgroundPaint.setColor(getThemedColor(Theme.key_dialogBackground)); rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24)); canvas.drawRoundRect(rect, r * rad, r * rad, backgroundPaint); } - int color1 = Theme.getColor(Theme.key_dialogBackground); + int color1 = getThemedColor(Theme.key_dialogBackground); int finalColor = Color.argb((int) (255 * actionBar.getAlpha()), (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); backgroundPaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, 0, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, backgroundPaint); @@ -521,7 +524,7 @@ public class PhonebookShareAlert extends BottomSheet { break; } } - int color = Theme.getColor(Theme.key_featuredStickers_buttonText); + int color = getThemedColor(Theme.key_featuredStickers_buttonText); buttonTextView.setEnabled(hasChecked); buttonTextView.setTextColor(hasChecked ? color : (color & 0x7fffffff)); } @@ -546,9 +549,9 @@ public class PhonebookShareAlert extends BottomSheet { clipboard.setPrimaryClip(clip); if (BulletinFactory.canShowBulletin(parentFragment)) { if (item.type == 3) { - BulletinFactory.of((FrameLayout) containerView).createCopyLinkBulletin().show(); + BulletinFactory.of((FrameLayout) containerView, resourcesProvider).createCopyLinkBulletin().show(); } else { - final Bulletin.SimpleLayout layout = new Bulletin.SimpleLayout(context); + final Bulletin.SimpleLayout layout = new Bulletin.SimpleLayout(context, resourcesProvider); if (item.type == 0) { layout.textView.setText(LocaleController.getString("PhoneCopied", R.string.PhoneCopied)); layout.imageView.setImageResource(R.drawable.menu_calls); @@ -574,11 +577,11 @@ public class PhonebookShareAlert extends BottomSheet { containerView.invalidate(); } }; - actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + actionBar.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); actionBar.setBackButtonImage(R.drawable.ic_ab_back); - actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false); - actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false); - actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack)); + actionBar.setItemsColor(getThemedColor(Theme.key_dialogTextBlack), false); + actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_dialogButtonSelector), false); + actionBar.setTitleColor(getThemedColor(Theme.key_dialogTextBlack)); actionBar.setOccupyStatusBar(false); actionBar.setAlpha(0.0f); if (isImport) { @@ -598,18 +601,18 @@ public class PhonebookShareAlert extends BottomSheet { actionBarShadow = new View(context); actionBarShadow.setAlpha(0.0f); - actionBarShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + actionBarShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); containerView.addView(actionBarShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1)); shadow = new View(context); - shadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadow.setAlpha(0.0f); containerView.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 77)); buttonTextView = new TextView(context); buttonTextView.setPadding(AndroidUtilities.dp(34), 0, AndroidUtilities.dp(34), 0); buttonTextView.setGravity(Gravity.CENTER); - buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + buttonTextView.setTextColor(getThemedColor(Theme.key_featuredStickers_buttonText)); buttonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); if (isImport) { buttonTextView.setText(LocaleController.getString("AddContactPhonebookTitle", R.string.AddContactPhonebookTitle)); @@ -617,7 +620,7 @@ public class PhonebookShareAlert extends BottomSheet { buttonTextView.setText(LocaleController.getString("ShareContactTitle", R.string.ShareContactTitle)); } buttonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - buttonTextView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + buttonTextView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), getThemedColor(Theme.key_featuredStickers_addButton), getThemedColor(Theme.key_featuredStickers_addButtonPressed))); frameLayout.addView(buttonTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 42, Gravity.LEFT | Gravity.BOTTOM, 16, 16, 16, 16)); buttonTextView.setOnClickListener(v -> { if (isImport) { @@ -910,7 +913,7 @@ public class PhonebookShareAlert extends BottomSheet { AlertsCreator.createScheduleDatePickerDialog(getContext(), chatActivity.getDialogId(), (notify, scheduleDate) -> { delegate.didSelectContact(currentUser, notify, scheduleDate); dismiss(); - }); + }, resourcesProvider); } else { delegate.didSelectContact(currentUser, true, 0); dismiss(); @@ -924,7 +927,7 @@ public class PhonebookShareAlert extends BottomSheet { super.onStart(); Bulletin.addDelegate((FrameLayout) containerView, new Bulletin.Delegate() { @Override - public int getBottomOffset() { + public int getBottomOffset(int tag) { return AndroidUtilities.dp(74); } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoCropView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoCropView.java index b5e47caf8..093010cfa 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoCropView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoCropView.java @@ -62,6 +62,7 @@ public class PhotoCropView extends FrameLayout { private float flashAlpha = 0.0f; private Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Theme.ResourcesProvider resourcesProvider; public final Property ANIMATION_VALUE = new AnimationProperties.FloatProperty("thumbAnimationProgress") { @Override @@ -89,8 +90,9 @@ public class PhotoCropView extends FrameLayout { } }; - public PhotoCropView(Context context) { + public PhotoCropView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; inBubbleMode = context instanceof BubbleActivity; @@ -209,7 +211,7 @@ public class PhotoCropView extends FrameLayout { canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 2, circlePaint); } - circlePaint.setColor(Theme.getColor(Theme.key_dialogFloatingButton)); + circlePaint.setColor(getThemedColor(Theme.key_dialogFloatingButton)); circlePaint.setAlpha(Math.min(255, (int) (255 * thumbAnimationProgress * thumbImageVisibleProgress))); canvas.drawCircle(targetX + targetSize / 2, targetY + targetSize + AndroidUtilities.dp(8), AndroidUtilities.dp(3), circlePaint); } @@ -380,4 +382,9 @@ public class PhotoCropView extends FrameLayout { super.invalidate(); cropView.invalidate(); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoFilterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoFilterView.java index 421b94013..d2192e4a1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoFilterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoFilterView.java @@ -119,6 +119,7 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter private Bitmap bitmapToEdit; private int orientation; + private final Theme.ResourcesProvider resourcesProvider; public static class CurvesValue { @@ -269,8 +270,9 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter } } - public PhotoFilterView(Context context, VideoEditTextureView videoTextureView, Bitmap bitmap, int rotation, MediaController.SavedFilterState state, PaintingOverlay overlay, int hasFaces, boolean mirror) { + public PhotoFilterView(Context context, VideoEditTextureView videoTextureView, Bitmap bitmap, int rotation, MediaController.SavedFilterState state, PaintingOverlay overlay, int hasFaces, boolean mirror, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; inBubbleMode = context instanceof BubbleActivity; paintingOverlay = overlay; @@ -427,7 +429,7 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter doneTextView = new TextView(context); doneTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - doneTextView.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + doneTextView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); doneTextView.setGravity(Gravity.CENTER); doneTextView.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_PICKER_SELECTOR_COLOR, 0)); doneTextView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0); @@ -441,12 +443,12 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter tuneItem = new ImageView(context); tuneItem.setScaleType(ImageView.ScaleType.CENTER); tuneItem.setImageResource(R.drawable.photo_tools); - tuneItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + tuneItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); tuneItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR)); linearLayout.addView(tuneItem, LayoutHelper.createLinear(56, 48)); tuneItem.setOnClickListener(v -> { selectedTool = 0; - tuneItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + tuneItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); blurItem.setColorFilter(null); curveItem.setColorFilter(null); switchMode(); @@ -460,7 +462,7 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter blurItem.setOnClickListener(v -> { selectedTool = 1; tuneItem.setColorFilter(null); - blurItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + blurItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); curveItem.setColorFilter(null); switchMode(); }); @@ -477,7 +479,7 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter selectedTool = 2; tuneItem.setColorFilter(null); blurItem.setColorFilter(null); - curveItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + curveItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); switchMode(); }); @@ -606,16 +608,16 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter public void updateColors() { if (doneTextView != null) { - doneTextView.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + doneTextView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); } if (tuneItem != null && tuneItem.getColorFilter() != null) { - tuneItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + tuneItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } if (blurItem != null && blurItem.getColorFilter() != null) { - blurItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + blurItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } if (curveItem != null && curveItem.getColorFilter() != null) { - curveItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + curveItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } updateSelectedBlurType(); } @@ -623,9 +625,9 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter private void updateSelectedBlurType() { if (blurType == 0) { Drawable drawable = blurOffButton.getContext().getResources().getDrawable(R.drawable.blur_off).mutate(); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); blurOffButton.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); - blurOffButton.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + blurOffButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); blurRadialButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blur_radial, 0, 0); blurRadialButton.setTextColor(0xffffffff); @@ -637,9 +639,9 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter blurOffButton.setTextColor(0xffffffff); Drawable drawable = blurOffButton.getContext().getResources().getDrawable(R.drawable.blur_radial).mutate(); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); blurRadialButton.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); - blurRadialButton.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + blurRadialButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); blurLinearButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blur_linear, 0, 0); blurLinearButton.setTextColor(0xffffffff); @@ -651,9 +653,9 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter blurRadialButton.setTextColor(0xffffffff); Drawable drawable = blurOffButton.getContext().getResources().getDrawable(R.drawable.blur_linear).mutate(); - drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); blurLinearButton.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); - blurLinearButton.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + blurLinearButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); } } @@ -1019,6 +1021,11 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter return cancelTextView; } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + public class ToolsAdapter extends RecyclerListView.SelectionAdapter { private Context mContext; @@ -1041,7 +1048,7 @@ public class PhotoFilterView extends FrameLayout implements FilterShaders.Filter public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view; if (i == 0) { - PhotoEditToolCell cell = new PhotoEditToolCell(mContext); + PhotoEditToolCell cell = new PhotoEditToolCell(mContext, resourcesProvider); view = cell; cell.setSeekBarDelegate((i1, progress) -> { if (i1 == enhanceTool) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoPaintView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoPaintView.java index daf17147c..ba6356050 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoPaintView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoPaintView.java @@ -131,9 +131,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView private boolean inBubbleMode; private MediaController.CropState currentCropState; + private final Theme.ResourcesProvider resourcesProvider; - public PhotoPaintView(Context context, Bitmap bitmap, Bitmap originalBitmap, int originalRotation, ArrayList entities, MediaController.CropState cropState, Runnable onInit) { + public PhotoPaintView(Context context, Bitmap bitmap, Bitmap originalBitmap, int originalRotation, ArrayList entities, MediaController.CropState cropState, Runnable onInit, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; inBubbleMode = context instanceof BubbleActivity; currentCropState = cropState; @@ -283,7 +285,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView doneTextView = new TextView(context); doneTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - doneTextView.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + doneTextView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); doneTextView.setGravity(Gravity.CENTER); doneTextView.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_PICKER_SELECTOR_COLOR, 0)); doneTextView.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0); @@ -417,7 +419,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView setCurrentSwatch(brushSwatch, true); brushSwatch = null; } - paintButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + paintButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); paintButton.setImageResource(R.drawable.photo_paint); } @@ -426,10 +428,10 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView public void updateColors() { if (paintButton != null && paintButton.getColorFilter() != null) { - paintButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + paintButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } if (doneTextView != null) { - doneTextView.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + doneTextView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); } } @@ -1033,7 +1035,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView } private void openStickersView() { - StickerMasksAlert stickerMasksAlert = new StickerMasksAlert(getContext(), facesBitmap == null); + StickerMasksAlert stickerMasksAlert = new StickerMasksAlert(getContext(), facesBitmap == null, resourcesProvider); stickerMasksAlert.setDelegate((parentObject, sticker) -> createSticker(parentObject, sticker, true)); stickerMasksAlert.setOnDismissListener(dialog -> onOpenCloseStickersAlert(false)); stickerMasksAlert.show(); @@ -1234,7 +1236,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView parent.setOrientation(LinearLayout.HORIZONTAL); TextView deleteView = new TextView(getContext()); - deleteView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + deleteView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); deleteView.setBackgroundDrawable(Theme.getSelectorDrawable(false)); deleteView.setGravity(Gravity.CENTER_VERTICAL); deleteView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(14), 0); @@ -1252,7 +1254,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView if (entityView instanceof TextPaintView) { TextView editView = new TextView(getContext()); - editView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + editView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); editView.setBackgroundDrawable(Theme.getSelectorDrawable(false)); editView.setGravity(Gravity.CENTER_VERTICAL); editView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), 0); @@ -1270,7 +1272,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView } TextView duplicateView = new TextView(getContext()); - duplicateView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + duplicateView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); duplicateView.setBackgroundDrawable(Theme.getSelectorDrawable(false)); duplicateView.setGravity(Gravity.CENTER_VERTICAL); duplicateView.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(16), 0); @@ -1315,11 +1317,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView ImageView imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(icon); - imageView.setColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + imageView.setColorFilter(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); button.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 16, 0, 16, 0)); TextView textView = new TextView(getContext()); - textView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + textView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setText(text); textView.setMinWidth(AndroidUtilities.dp(70)); @@ -1328,7 +1330,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView ImageView check = new ImageView(getContext()); check.setImageResource(R.drawable.msg_text_check); check.setScaleType(ImageView.ScaleType.CENTER); - check.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); + check.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); check.setVisibility(selected ? VISIBLE : INVISIBLE); button.addView(check, LayoutHelper.createLinear(50, LayoutHelper.MATCH_PARENT)); @@ -1372,11 +1374,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView ImageView imageView = new ImageView(getContext()); imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(icon); - imageView.setColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + imageView.setColorFilter(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); button.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 16, 0, 16, 0)); TextView textView = new TextView(getContext()); - textView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + textView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setText(text); button.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 0, 0, 16, 0)); @@ -1385,7 +1387,7 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView ImageView check = new ImageView(getContext()); check.setImageResource(R.drawable.msg_text_check); check.setScaleType(ImageView.ScaleType.CENTER); - check.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); + check.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); button.addView(check, LayoutHelper.createLinear(50, LayoutHelper.MATCH_PARENT)); } @@ -1637,6 +1639,11 @@ public class PhotoPaintView extends FrameLayout implements EntityView.EntityView return false; } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + private static class StickerPosition { private Point position; private float scale; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoViewerCaptionEnterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoViewerCaptionEnterView.java index 56304fa20..f43ac13c8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoViewerCaptionEnterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PhotoViewerCaptionEnterView.java @@ -110,9 +110,11 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica private TextPaint lengthTextPaint; private String lengthText; + private final Theme.ResourcesProvider resourcesProvider; - public PhotoViewerCaptionEnterView(Context context, SizeNotifierFrameLayoutPhoto parent, final View window) { + public PhotoViewerCaptionEnterView(Context context, SizeNotifierFrameLayoutPhoto parent, final View window, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; paint.setColor(0x7f000000); setWillNotDraw(false); setFocusable(true); @@ -153,7 +155,7 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica lengthTextPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); lengthTextPaint.setColor(0xffd9d9d9); - messageEditText = new EditTextCaption(context) { + messageEditText = new EditTextCaption(context, null) { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { try { @@ -318,7 +320,7 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica sendButtonColorAnimator = ValueAnimator.ofFloat(sendButtonEnabled ? 0 : 1f, sendButtonEnabled ? 1f : 0); sendButtonColorAnimator.addUpdateListener(valueAnimator -> { sendButtonEnabledProgress = (float) valueAnimator.getAnimatedValue(); - int color = Theme.getColor(Theme.key_dialogFloatingIcon); + int color = getThemedColor(Theme.key_dialogFloatingIcon); int alpha = Color.alpha(color); Theme.setDrawableColor(checkDrawable, ColorUtils.setAlphaComponent(color, (int) (alpha * (0.58f + 0.42f * sendButtonEnabledProgress)))); doneButton.invalidate(); @@ -445,8 +447,8 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica } public void updateColors() { - Theme.setDrawableColor(doneDrawable, Theme.getColor(Theme.key_dialogFloatingButton)); - int color = Theme.getColor(Theme.key_dialogFloatingIcon); + Theme.setDrawableColor(doneDrawable, getThemedColor(Theme.key_dialogFloatingButton)); + int color = getThemedColor(Theme.key_dialogFloatingIcon); int alpha = Color.alpha(color); Theme.setDrawableColor(checkDrawable, ColorUtils.setAlphaComponent(color, (int) (alpha * (0.58f + 0.42f * sendButtonEnabledProgress)))); if (emojiView != null) { @@ -537,7 +539,7 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica if (emojiView != null) { return; } - emojiView = new EmojiView(false, false, getContext(), false, null, null); + emojiView = new EmojiView(false, false, getContext(), false, null, null, null); emojiView.setDelegate(new EmojiView.EmojiViewDelegate() { @Override public boolean onBackspace() { @@ -823,4 +825,9 @@ public class PhotoViewerCaptionEnterView extends FrameLayout implements Notifica public EditTextCaption getMessageEditText() { return messageEditText; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PinnedLineView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PinnedLineView.java index fd9a5bd17..b27814aaa 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PinnedLineView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PinnedLineView.java @@ -49,9 +49,11 @@ public class PinnedLineView extends View { Paint selectedPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int nextPosition = -1; private int color; + private final Theme.ResourcesProvider resourcesProvider; - public PinnedLineView(Context context) { + public PinnedLineView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; paint.setStyle(Paint.Style.FILL); paint.setStrokeCap(Paint.Cap.ROUND); @@ -73,9 +75,9 @@ public class PinnedLineView extends View { } public void updateColors() { - color = Theme.getColor(Theme.key_chat_topPanelLine); + color = getThemedColor(Theme.key_chat_topPanelLine); paint.setColor(ColorUtils.setAlphaComponent(color, (int) ((Color.alpha(color) / 255f) * 112))); - selectedPaint.setColor(Theme.getColor(Theme.key_chat_topPanelLine)); + selectedPaint.setColor(color); } private void selectPosition(int position) { @@ -281,4 +283,9 @@ public class PinnedLineView extends View { } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PlayingGameDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PlayingGameDrawable.java index 461697380..026974189 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PlayingGameDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PlayingGameDrawable.java @@ -30,9 +30,11 @@ public class PlayingGameDrawable extends StatusDrawable { private RectF rect = new RectF(); private float progress; private final boolean isDialogScreen; + Theme.ResourcesProvider resourcesProvider; - public PlayingGameDrawable(boolean isDialogScreen) { + public PlayingGameDrawable(boolean isDialogScreen, Theme.ResourcesProvider resourcesProvider) { this.isDialogScreen = isDialogScreen; + this.resourcesProvider = resourcesProvider; } public void setIsChat(boolean value) { isChat = value; @@ -40,7 +42,6 @@ public class PlayingGameDrawable extends StatusDrawable { @Override public void setColor(int color) { - } private void update() { @@ -82,7 +83,7 @@ public class PlayingGameDrawable extends StatusDrawable { //y = AndroidUtilities.dp(9.3f) + getBounds().top; } - paint.setColor(Theme.getColor(isDialogScreen ? Theme.key_chats_actionMessage : Theme.key_chat_status)); + paint.setColor(Theme.getColor(isDialogScreen ? Theme.key_chats_actionMessage : Theme.key_chat_status, resourcesProvider)); rect.set(0, y, size, y + size); int rad; if (progress < 0.5f) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/PollVotesAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/PollVotesAlert.java index 8fea9040a..93f5cc057 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/PollVotesAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/PollVotesAlert.java @@ -790,7 +790,7 @@ public class PollVotesAlert extends BottomSheet { } TLRPC.User currentUser = parentFragment.getCurrentUser(); Bundle args = new Bundle(); - args.putInt("user_id", userCell.currentUser.id); + args.putLong("user_id", userCell.currentUser.id); dismiss(); ProfileActivity fragment = new ProfileActivity(args); fragment.setPlayProfileAnimation(currentUser != null && currentUser.id == userCell.currentUser.id ? 1 : 0); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ProfileGalleryView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ProfileGalleryView.java index f4eb8457e..7e91a06e7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ProfileGalleryView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ProfileGalleryView.java @@ -23,6 +23,7 @@ import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; @@ -277,7 +278,7 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoaded); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.fileLoadProgressChanged); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.reloadDialogPhotos); - MessagesController.getInstance(currentAccount).loadDialogPhotos((int) dialogId, 80, 0, true, parentClassGuid); + MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } public void onDestroy() { @@ -459,10 +460,10 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio if (prevImageLocation == null || prevImageLocation.location.local_id != imageLocation.location.local_id) { if (!imagesLocations.isEmpty()) { prevImageLocation = imageLocation; - MessagesController.getInstance(currentAccount).loadDialogPhotos((int) dialogId, 80, 0, true, parentClassGuid); + MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); return true; } else { - MessagesController.getInstance(currentAccount).loadDialogPhotos((int) dialogId, 80, 0, true, parentClassGuid); + MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } } if (!imagesLocations.isEmpty()) { @@ -733,7 +734,7 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.dialogPhotosLoaded) { int guid = (Integer) args[3]; - int did = (Integer) args[0]; + long did = (Long) args[0]; if (did == dialogId && parentClassGuid == guid && adapter != null) { boolean fromCache = (Boolean) args[2]; ArrayList arrayList = (ArrayList) args[4]; @@ -746,7 +747,7 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio imagesLocationsSizes.clear(); imagesUploadProgress.clear(); ImageLocation currentImageLocation = null; - if (did < 0) { + if (DialogObject.isChatDialog(did)) { TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); currentImageLocation = ImageLocation.getForUserOrChat(chat, ImageLocation.TYPE_BIG); if (currentImageLocation != null) { @@ -887,7 +888,7 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio if (settingMainPhoto != 0) { return; } - MessagesController.getInstance(currentAccount).loadDialogPhotos((int) dialogId, 80, 0, true, parentClassGuid); + MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } } @@ -1111,7 +1112,7 @@ public class ProfileGalleryView extends CircularViewPager implements Notificatio reset(); this.dialogId = dialogId; if (dialogId != 0) { - MessagesController.getInstance(currentAccount).loadDialogPhotos((int) dialogId, 80, 0, true, parentClassGuid); + MessagesController.getInstance(currentAccount).loadDialogPhotos(dialogId, 80, 0, true, parentClassGuid); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RLottieDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RLottieDrawable.java index 1920e92be..326b89d7b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RLottieDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RLottieDrawable.java @@ -1053,4 +1053,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable { invalidateOnProgressSet = value; } + public boolean isGeneratingCache() { + return cacheGenerateTask != null; + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgress2.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgress2.java index 88b70abb0..963d27cb4 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgress2.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgress2.java @@ -16,6 +16,8 @@ import android.graphics.Paint; import android.graphics.RectF; import android.view.View; +import com.google.android.exoplayer2.util.Log; + import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; @@ -65,8 +67,14 @@ public class RadialProgress2 { private Canvas miniDrawCanvas; private float overrideAlpha = 1.0f; + private final Theme.ResourcesProvider resourcesProvider; public RadialProgress2(View parentView) { + this(parentView, null); + } + + public RadialProgress2(View parentView, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; miniProgressBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); parent = parentView; @@ -274,7 +282,7 @@ public class RadialProgress2 { } public void draw(Canvas canvas) { - if (mediaActionDrawable.getCurrentIcon() == MediaActionDrawable.ICON_NONE && mediaActionDrawable.getTransitionProgress() >= 1.0f) { + if (mediaActionDrawable.getCurrentIcon() == MediaActionDrawable.ICON_NONE && mediaActionDrawable.getTransitionProgress() >= 1.0f || progressRect.isEmpty()) { return; } @@ -298,26 +306,26 @@ public class RadialProgress2 { if (isPressedMini && circleCrossfadeColorKey == null) { if (iconPressedColorKey != null) { - miniMediaActionDrawable.setColor(Theme.getColor(iconPressedColorKey)); + miniMediaActionDrawable.setColor(getThemedColor(iconPressedColorKey)); } else { miniMediaActionDrawable.setColor(iconPressedColor); } if (circlePressedColorKey != null) { - circleMiniPaint.setColor(Theme.getColor(circlePressedColorKey)); + circleMiniPaint.setColor(getThemedColor(circlePressedColorKey)); } else { circleMiniPaint.setColor(circlePressedColor); } } else { if (iconColorKey != null) { - miniMediaActionDrawable.setColor(Theme.getColor(iconColorKey)); + miniMediaActionDrawable.setColor(getThemedColor(iconColorKey)); } else { miniMediaActionDrawable.setColor(iconColor); } if (circleColorKey != null) { if (circleCrossfadeColorKey != null) { - circleMiniPaint.setColor(AndroidUtilities.getOffsetColor(Theme.getColor(circleColorKey), Theme.getColor(circleCrossfadeColorKey), circleCrossfadeColorProgress, circleCheckProgress)); + circleMiniPaint.setColor(AndroidUtilities.getOffsetColor(getThemedColor(circleColorKey), getThemedColor(circleCrossfadeColorKey), circleCrossfadeColorProgress, circleCheckProgress)); } else { - circleMiniPaint.setColor(Theme.getColor(circleColorKey)); + circleMiniPaint.setColor(getThemedColor(circleColorKey)); } } else { circleMiniPaint.setColor(circleColor); @@ -327,27 +335,27 @@ public class RadialProgress2 { int color; if (isPressed) { if (iconPressedColorKey != null) { - mediaActionDrawable.setColor(color = Theme.getColor(iconPressedColorKey)); - mediaActionDrawable.setBackColor(Theme.getColor(circlePressedColorKey)); + mediaActionDrawable.setColor(color = getThemedColor(iconPressedColorKey)); + mediaActionDrawable.setBackColor(getThemedColor(circlePressedColorKey)); } else { mediaActionDrawable.setColor(color = iconPressedColor); mediaActionDrawable.setBackColor(circlePressedColor); } if (circlePressedColorKey != null) { - circlePaint.setColor(Theme.getColor(circlePressedColorKey)); + circlePaint.setColor(getThemedColor(circlePressedColorKey)); } else { circlePaint.setColor(circlePressedColor); } } else { if (iconColorKey != null) { - mediaActionDrawable.setColor(color = Theme.getColor(iconColorKey)); - mediaActionDrawable.setBackColor(Theme.getColor(circleColorKey)); + mediaActionDrawable.setColor(color = getThemedColor(iconColorKey)); + mediaActionDrawable.setBackColor(getThemedColor(circleColorKey)); } else { mediaActionDrawable.setColor(color = iconColor); mediaActionDrawable.setBackColor(circleColor); } if (circleColorKey != null) { - circlePaint.setColor(Theme.getColor(circleColorKey)); + circlePaint.setColor(getThemedColor(circleColorKey)); } else { circlePaint.setColor(circleColor); } @@ -501,4 +509,9 @@ public class RadialProgress2 { public String getCircleColorKey() { return circleColorKey; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgressView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgressView.java index eea62c934..f0ac1cdef 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgressView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RadialProgressView.java @@ -49,13 +49,19 @@ public class RadialProgressView extends View { private float toCircleProgress; private boolean noProgress = true; + private final Theme.ResourcesProvider resourcesProvider; public RadialProgressView(Context context) { + this(context, null); + } + + public RadialProgressView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; size = AndroidUtilities.dp(40); - progressColor = Theme.getColor(Theme.key_progressCircle); + progressColor = getThemedColor(Theme.key_progressCircle); decelerateInterpolator = new DecelerateInterpolator(); accelerateInterpolator = new AccelerateInterpolator(); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -214,4 +220,9 @@ public class RadialProgressView extends View { public boolean isCircle() { return Math.abs(drawingCircleLenght) >= 360; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java index c84f45a1c..d6b1f6eee 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java @@ -143,6 +143,8 @@ public class RecyclerListView extends RecyclerView { int[] listPaddings; HashSet selectedPositions; + protected final Theme.ResourcesProvider resourcesProvider; + public interface OnItemClickListener { void onItemClick(View view, int position); } @@ -882,12 +884,17 @@ public class RecyclerListView extends RecyclerView { return null; } - @SuppressLint("PrivateApi") public RecyclerListView(Context context) { - super(context); + this(context, null); + } - setGlowColor(Theme.getColor(Theme.key_actionBarDefault)); - selectorDrawable = Theme.getSelectorDrawable(false); + @SuppressLint("PrivateApi") + public RecyclerListView(Context context, Theme.ResourcesProvider resourcesProvider) { + super(context); + this.resourcesProvider = resourcesProvider; + + setGlowColor(getThemedColor(Theme.key_actionBarDefault)); + selectorDrawable = Theme.getSelectorDrawable(getThemedColor(Theme.key_listSelector), false); selectorDrawable.setCallback(this); try { @@ -2087,6 +2094,21 @@ public class RecyclerListView extends RecyclerView { return multiSelectionGesture; } + protected int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + protected Drawable getThemedDrawable(String key) { + Drawable drawable = resourcesProvider != null ? resourcesProvider.getDrawable(key) : null; + return drawable != null ? drawable : Theme.getThemeDrawable(key); + } + + protected Paint getThemedPaint(String paintKey) { + Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(paintKey) : null; + return paint != null ? paint : Theme.getThemePaint(paintKey); + } + public interface onMultiSelectionChanged { void onSelectionChanged(int position, boolean selected, float x, float y); boolean canSelect(int position); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ReorderingBulletinLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ReorderingBulletinLayout.java index 9eae112ed..138839438 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ReorderingBulletinLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ReorderingBulletinLayout.java @@ -5,13 +5,15 @@ import android.content.Context; import androidx.annotation.NonNull; +import org.telegram.ui.ActionBar.Theme; + @SuppressLint("ViewConstructor") public class ReorderingBulletinLayout extends Bulletin.SimpleLayout { private final ReorderingHintDrawable hintDrawable; - public ReorderingBulletinLayout(@NonNull Context context, String text) { - super(context); + public ReorderingBulletinLayout(@NonNull Context context, String text, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); textView.setText(text); textView.setTranslationY(-1); imageView.setImageDrawable(hintDrawable = new ReorderingHintDrawable()); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RoundVideoPlayingDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RoundVideoPlayingDrawable.java index 4fad3e108..3e4dc417d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RoundVideoPlayingDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RoundVideoPlayingDrawable.java @@ -32,8 +32,11 @@ public class RoundVideoPlayingDrawable extends Drawable { private View parentView; int alpha = 255; - public RoundVideoPlayingDrawable(View view) { + private final Theme.ResourcesProvider resourcesProvider; + + public RoundVideoPlayingDrawable(View view, Theme.ResourcesProvider resourcesProvider) { super(); + this.resourcesProvider = resourcesProvider; parentView = view; } @@ -92,7 +95,7 @@ public class RoundVideoPlayingDrawable extends Drawable { @Override public void draw(Canvas canvas) { - paint.setColor(Theme.getColor(Theme.key_chat_serviceText)); + paint.setColor(getThemedColor(Theme.key_chat_serviceText)); if (alpha != 255) { paint.setAlpha((int) (alpha * (paint.getAlpha() / 255f))); } @@ -132,4 +135,9 @@ public class RoundVideoPlayingDrawable extends Drawable { public int getIntrinsicHeight() { return AndroidUtilities.dp(12); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrollSlidingTabStrip.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrollSlidingTabStrip.java index 5cb2af266..e2764afac 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrollSlidingTabStrip.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrollSlidingTabStrip.java @@ -40,8 +40,6 @@ import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; -import com.google.android.exoplayer2.util.Log; - import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DocumentObject; import org.telegram.messenger.Emoji; @@ -106,6 +104,8 @@ public class ScrollSlidingTabStrip extends HorizontalScrollView { private int tabPadding = AndroidUtilities.dp(24); private int lastScrollX = 0; + private final Theme.ResourcesProvider resourcesProvider; + SparseArray currentPlayingImages = new SparseArray<>(); SparseArray currentPlayingImagesTmp = new SparseArray<>(); private boolean dragEnabled; @@ -145,8 +145,9 @@ public class ScrollSlidingTabStrip extends HorizontalScrollView { } }; - public ScrollSlidingTabStrip(Context context) { + public ScrollSlidingTabStrip(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); setFillViewport(true); @@ -297,9 +298,9 @@ public class ScrollSlidingTabStrip extends HorizontalScrollView { textView = new TextView(getContext()); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); - textView.setTextColor(Theme.getColor(Theme.key_chat_emojiPanelBadgeText)); + textView.setTextColor(getThemedColor(Theme.key_chat_emojiPanelBadgeText)); textView.setGravity(Gravity.CENTER); - textView.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(9), Theme.getColor(Theme.key_chat_emojiPanelBadgeBackground))); + textView.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(9), getThemedColor(Theme.key_chat_emojiPanelBadgeBackground))); textView.setMinWidth(AndroidUtilities.dp(18)); textView.setPadding(AndroidUtilities.dp(5), 0, AndroidUtilities.dp(5), AndroidUtilities.dp(1)); tab.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 18, Gravity.TOP | Gravity.LEFT, 26, 6, 0, 0)); @@ -959,7 +960,6 @@ public class ScrollSlidingTabStrip extends HorizontalScrollView { currentDragPosition = p; tabsContainer.removeView(draggingView); tabsContainer.addView(draggingView, currentDragPosition); - invalidate(); } dragDx = x - startDragFromX; @@ -1072,4 +1072,9 @@ public class ScrollSlidingTabStrip extends HorizontalScrollView { public void setDragEnabled(boolean enabled) { dragEnabled = enabled; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchCounterView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchCounterView.java index 6f0133a04..c9dcea7b4 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchCounterView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchCounterView.java @@ -53,10 +53,11 @@ public class SearchCounterView extends View { public float horizontalPadding; String currentString; + private final Theme.ResourcesProvider resourcesProvider; - - public SearchCounterView(Context context) { + public SearchCounterView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textPaint.setTextSize(AndroidUtilities.dp(15)); } @@ -214,7 +215,7 @@ public class SearchCounterView extends View { @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); - int textColor = Theme.getColor(textColorKey); + int textColor = Theme.getColor(textColorKey, resourcesProvider); if (this.textColor != textColor) { this.textColor = textColor; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchField.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchField.java index 3c89c4cd3..ad33e4a8a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchField.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchField.java @@ -30,18 +30,16 @@ public class SearchField extends FrameLayout { private CloseProgressDrawable2 progressDrawable; private EditTextBoldCursor searchEditText; private View backgroundView; + private final Theme.ResourcesProvider resourcesProvider; - public SearchField(Context context) { - this(context, false); - } - - public SearchField(Context context, boolean supportRtl) { + public SearchField(Context context, boolean supportRtl, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; FrameLayout.LayoutParams lp; searchBackground = new View(context); - searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(Theme.key_dialogSearchBackground))); + searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(Theme.key_dialogSearchBackground))); if (supportRtl) { lp = LayoutHelper.createFrameRelatively(LayoutHelper.MATCH_PARENT, 36, Gravity.START | Gravity.TOP, 14, 11, 14, 0); } else { @@ -52,7 +50,7 @@ public class SearchField extends FrameLayout { searchIconImageView = new ImageView(context); searchIconImageView.setScaleType(ImageView.ScaleType.CENTER); searchIconImageView.setImageResource(R.drawable.smiles_inputsearch); - searchIconImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); + searchIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); if (supportRtl) { lp = LayoutHelper.createFrameRelatively(36, 36, Gravity.START | Gravity.TOP, 16, 11, 0, 0); } else { @@ -67,7 +65,7 @@ public class SearchField extends FrameLayout { clearSearchImageView.setScaleX(0.1f); clearSearchImageView.setScaleY(0.1f); clearSearchImageView.setAlpha(0.0f); - clearSearchImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); + clearSearchImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); if (supportRtl) { lp = LayoutHelper.createFrameRelatively(36, 36, Gravity.END | Gravity.TOP, 14, 11, 14, 0); } else { @@ -98,8 +96,8 @@ public class SearchField extends FrameLayout { } }; searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - searchEditText.setHintTextColor(Theme.getColor(Theme.key_dialogSearchHint)); - searchEditText.setTextColor(Theme.getColor(Theme.key_dialogSearchText)); + searchEditText.setHintTextColor(getThemedColor(Theme.key_dialogSearchHint)); + searchEditText.setTextColor(getThemedColor(Theme.key_dialogSearchText)); searchEditText.setBackgroundDrawable(null); searchEditText.setPadding(0, 0, 0, 0); searchEditText.setMaxLines(1); @@ -107,7 +105,7 @@ public class SearchField extends FrameLayout { searchEditText.setSingleLine(true); searchEditText.setGravity((supportRtl ? LayoutHelper.getAbsoluteGravityStart() : Gravity.LEFT) | Gravity.CENTER_VERTICAL); searchEditText.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI); - searchEditText.setCursorColor(Theme.getColor(Theme.key_featuredStickers_addedIcon)); + searchEditText.setCursorColor(getThemedColor(Theme.key_featuredStickers_addedIcon)); searchEditText.setCursorSize(AndroidUtilities.dp(20)); searchEditText.setCursorWidth(1.5f); if (supportRtl) { @@ -196,4 +194,9 @@ public class SearchField extends FrameLayout { descriptions.add(new ThemeDescription(searchEditText, ThemeDescription.FLAG_HINTTEXTCOLOR, null, null, null, null, Theme.key_dialogSearchHint)); descriptions.add(new ThemeDescription(searchEditText, ThemeDescription.FLAG_CURSORCOLOR, null, null, null, null, Theme.key_featuredStickers_addedIcon)); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchViewPager.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchViewPager.java index 389194665..73a3176b5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchViewPager.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SearchViewPager.java @@ -14,6 +14,7 @@ import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.R; @@ -88,7 +89,7 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie this.folderId = folderId; parent = fragment; this.chatPreviewDelegate = chatPreviewDelegate; - dialogsSearchAdapter = new DialogsSearchAdapter(context, type, initialDialogsType, folderId) { + dialogsSearchAdapter = new DialogsSearchAdapter(context, type, initialDialogsType) { @Override public void notifyDataSetChanged() { int itemCount = getCurrentItemCount(); @@ -229,7 +230,7 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie } private void search(View view, int position, String query, boolean reset) { - int dialogId = 0; + long dialogId = 0; long minDate = 0; long maxDate = 0; boolean includeFolder = false; @@ -410,20 +411,16 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie fragment1.finishFragment(); } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); } else { - args1.putInt("enc_id", high_part); - } - if (lower_part != 0) { + if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); + } else { + args1.putLong("chat_id", -did); + } if (!AccountInstance.getInstance(currentAccount).getMessagesController().checkCanOpenChat(args1, fragment1)) { return; } @@ -439,21 +436,18 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie public void goToMessage(MessageObject messageObject) { Bundle args = new Bundle(); - int lower_part = (int) messageObject.getDialogId(); - int high_id = (int) (messageObject.getDialogId() >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - TLRPC.Chat chat = AccountInstance.getInstance(currentAccount).getMessagesController().getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - args.putInt("chat_id", -lower_part); - } + long dialogId = messageObject.getDialogId(); + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + TLRPC.Chat chat = AccountInstance.getInstance(currentAccount).getMessagesController().getChat(-dialogId); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", dialogId); + dialogId = -chat.migrated_to.channel_id; + } + args.putLong("chat_id", -dialogId); } args.putInt("message_id", messageObject.getId()); parent.presentFragment(new ChatActivity(args)); @@ -639,7 +633,7 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie this.showOnlyDialogsAdapter = showOnlyDialogsAdapter; } - public void messagesDeleted(int channelId, ArrayList markAsDeletedMessages) { + public void messagesDeleted(long channelId, ArrayList markAsDeletedMessages) { int n = viewsByType.size(); for (int i = 0; i < n; i++) { View v = viewsByType.valueAt(i); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SeekBarView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SeekBarView.java index 0198100e5..d21620236 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SeekBarView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SeekBarView.java @@ -48,6 +48,7 @@ public class SeekBarView extends FrameLayout { private int transitionThumbX; private boolean twoSided; + private final Theme.ResourcesProvider resourcesProvider; public interface SeekBarViewDelegate { void onSeekBarDrag(boolean stop, float progress); @@ -61,23 +62,28 @@ public class SeekBarView extends FrameLayout { } public SeekBarView(Context context) { - this(context, false); + this(context, null); } - public SeekBarView(Context context, boolean inPercents) { + public SeekBarView(Context context, Theme.ResourcesProvider resourcesProvider) { + this(context, false, resourcesProvider); + } + + public SeekBarView(Context context, boolean inPercents, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; setWillNotDraw(false); innerPaint1 = new Paint(Paint.ANTI_ALIAS_FLAG); outerPaint1 = new Paint(Paint.ANTI_ALIAS_FLAG); - outerPaint1.setColor(Theme.getColor(Theme.key_player_progress)); + outerPaint1.setColor(getThemedColor(Theme.key_player_progress)); selectorWidth = AndroidUtilities.dp(32); thumbSize = AndroidUtilities.dp(24); currentRadius = AndroidUtilities.dp(6); if (Build.VERSION.SDK_INT >= 21) { - hoverDrawable = Theme.createSelectorDrawable(ColorUtils.setAlphaComponent(Theme.getColor(Theme.key_player_progress), 40), 1, AndroidUtilities.dp(16)); + hoverDrawable = Theme.createSelectorDrawable(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_player_progress), 40), 1, AndroidUtilities.dp(16)); hoverDrawable.setCallback(this); hoverDrawable.setVisible(true, false); } @@ -338,10 +344,10 @@ public class SeekBarView extends FrameLayout { @Override protected void onDraw(Canvas canvas) { int y = (getMeasuredHeight() - thumbSize) / 2; - innerPaint1.setColor(Theme.getColor(Theme.key_player_progressBackground)); + innerPaint1.setColor(getThemedColor(Theme.key_player_progressBackground)); canvas.drawRect(selectorWidth / 2, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), getMeasuredWidth() - selectorWidth / 2, getMeasuredHeight() / 2 + AndroidUtilities.dp(1), innerPaint1); if (bufferedProgress > 0) { - innerPaint1.setColor(Theme.getColor(Theme.key_player_progressCachedBackground)); + innerPaint1.setColor(getThemedColor(Theme.key_player_progressCachedBackground)); canvas.drawRect(selectorWidth / 2, getMeasuredHeight() / 2 - AndroidUtilities.dp(1), selectorWidth / 2 + bufferedProgress * (getMeasuredWidth() - selectorWidth), getMeasuredHeight() / 2 + AndroidUtilities.dp(1), innerPaint1); } if (twoSided) { @@ -407,4 +413,9 @@ public class SeekBarView extends FrameLayout { public SeekBarAccessibilityDelegate getSeekBarAccessibilityDelegate() { return seekBarAccessibilityDelegate; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ShareAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ShareAlert.java index afe28b8ab..915dad5a6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ShareAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ShareAlert.java @@ -33,7 +33,6 @@ import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; -import android.util.LongSparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; @@ -52,19 +51,19 @@ import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; +import androidx.collection.LongSparseArray; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.google.android.exoplayer2.util.Log; - import org.telegram.SQLite.SQLiteCursor; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaDataController; @@ -161,6 +160,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi private ArrayList recentSearchObjects = new ArrayList<>(); private LongSparseArray recentSearchObjectsById = new LongSparseArray<>(); + private final Theme.ResourcesProvider resourcesProvider; public interface ShareAlertDelegate { default void didShare() { @@ -194,7 +194,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi rect = new RectF(); searchBackground = new View(context); - searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground))); + searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground))); addView(searchBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 0, 14, 0)); slidingView = new View(context) { @@ -226,7 +226,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi addView(slidingView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 0, 14, 0)); leftTab = new SimpleTextView(context); - leftTab.setTextColor(Theme.getColor(Theme.key_voipgroup_nameText)); + leftTab.setTextColor(getThemedColor(Theme.key_voipgroup_nameText)); leftTab.setTextSize(13); leftTab.setLeftDrawable(R.drawable.msg_tabs_mic1); leftTab.setText(LocaleController.getString("VoipGroupInviteCanSpeak", R.string.VoipGroupInviteCanSpeak)); @@ -235,7 +235,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi leftTab.setOnClickListener(v -> switchToTab(0)); rightTab = new SimpleTextView(context); - rightTab.setTextColor(Theme.getColor(Theme.key_voipgroup_nameText)); + rightTab.setTextColor(getThemedColor(Theme.key_voipgroup_nameText)); rightTab.setTextSize(13); rightTab.setLeftDrawable(R.drawable.msg_tabs_mic2); rightTab.setText(LocaleController.getString("VoipGroupInviteListenOnly", R.string.VoipGroupInviteListenOnly)); @@ -305,13 +305,13 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi super(context); searchBackground = new View(context); - searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), Theme.getColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground))); + searchBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(18), getThemedColor(darkTheme ? Theme.key_voipgroup_searchBackground : Theme.key_dialogSearchBackground))); addView(searchBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.LEFT | Gravity.TOP, 14, 11, 14, 0)); searchIconImageView = new ImageView(context); searchIconImageView.setScaleType(ImageView.ScaleType.CENTER); searchIconImageView.setImageResource(R.drawable.smiles_inputsearch); - searchIconImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(darkTheme ? Theme.key_voipgroup_mutedIcon : Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); + searchIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_mutedIcon : Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); addView(searchIconImageView, LayoutHelper.createFrame(36, 36, Gravity.LEFT | Gravity.TOP, 16, 11, 0, 0)); clearSearchImageView = new ImageView(context); @@ -321,7 +321,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi clearSearchImageView.setScaleX(0.1f); clearSearchImageView.setScaleY(0.1f); clearSearchImageView.setAlpha(0.0f); - clearSearchImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); + clearSearchImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchIcon), PorterDuff.Mode.MULTIPLY)); addView(clearSearchImageView, LayoutHelper.createFrame(36, 36, Gravity.RIGHT | Gravity.TOP, 14, 11, 14, 0)); clearSearchImageView.setOnClickListener(v -> { updateSearchAdapter = true; @@ -331,8 +331,8 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi searchEditText = new EditTextBoldCursor(context); searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - searchEditText.setHintTextColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchHint)); - searchEditText.setTextColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_dialogSearchText)); + searchEditText.setHintTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchPlaceholder : Theme.key_dialogSearchHint)); + searchEditText.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_dialogSearchText)); searchEditText.setBackgroundDrawable(null); searchEditText.setPadding(0, 0, 0, 0); searchEditText.setMaxLines(1); @@ -340,7 +340,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi searchEditText.setSingleLine(true); searchEditText.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI); searchEditText.setHint(LocaleController.getString("ShareSendTo", R.string.ShareSendTo)); - searchEditText.setCursorColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_featuredStickers_addedIcon)); + searchEditText.setCursorColor(getThemedColor(darkTheme ? Theme.key_voipgroup_searchText : Theme.key_featuredStickers_addedIcon)); searchEditText.setCursorSize(AndroidUtilities.dp(20)); searchEditText.setCursorWidth(1.5f); addView(searchEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 40, Gravity.LEFT | Gravity.TOP, 16 + 38, 9, 16 + 30, 0)); @@ -421,11 +421,20 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi } public ShareAlert(final Context context, ArrayList messages, final String text, boolean channel, final String copyLink, boolean fullScreen) { - this(context, null, messages, text, null, channel, copyLink, null, fullScreen, false); + this(context, messages, text, channel, copyLink, fullScreen, null); + } + + public ShareAlert(final Context context, ArrayList messages, final String text, boolean channel, final String copyLink, boolean fullScreen, Theme.ResourcesProvider resourcesProvider) { + this(context, null, messages, text, null, channel, copyLink, null, fullScreen, false, resourcesProvider); } public ShareAlert(final Context context, ChatActivity fragment, ArrayList messages, final String text, final String text2, boolean channel, final String copyLink, final String copyLink2, boolean fullScreen, boolean forCall) { - super(context, true); + this(context, fragment, messages, text, text2, channel, copyLink, copyLink2, fullScreen, forCall, null); + } + + public ShareAlert(final Context context, ChatActivity fragment, ArrayList messages, final String text, final String text2, boolean channel, final String copyLink, final String copyLink2, boolean fullScreen, boolean forCall, Theme.ResourcesProvider resourcesProvider) { + super(context, true, resourcesProvider); + this.resourcesProvider = resourcesProvider; if (context instanceof Activity) { parentActivity = (Activity) context; @@ -434,7 +443,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi parentFragment = fragment; shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); isFullscreen = fullScreen; linkToCopy[0] = copyLink; @@ -836,18 +845,18 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi shadowDrawable.draw(canvas); if (radProgress != 1.0f) { - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); rect1.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24)); canvas.drawRoundRect(rect1, AndroidUtilities.dp(12) * radProgress, AndroidUtilities.dp(12) * radProgress, Theme.dialogs_onlineCirclePaint); } int w = AndroidUtilities.dp(36); rect1.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4)); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_scrollUp : Theme.key_sheet_scrollUp)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(darkTheme ? Theme.key_voipgroup_scrollUp : Theme.key_sheet_scrollUp)); canvas.drawRoundRect(rect1, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint); if (statusBarHeight > 0) { - int color1 = Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground); + int color1 = getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground); int finalColor = Color.argb(0xff, (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); Theme.dialogs_onlineCirclePaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, AndroidUtilities.statusBarHeight - statusBarHeight, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, Theme.dialogs_onlineCirclePaint); @@ -870,7 +879,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi containerView.setPadding(backgroundPaddingLeft, 0, backgroundPaddingLeft, 0); frameLayout = new FrameLayout(context); - frameLayout.setBackgroundColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); + frameLayout.setBackgroundColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); if (darkTheme && linkToCopy[1] != null) { switchView = new SwitchView(context) { @@ -892,7 +901,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi searchView = new SearchField(context); frameLayout.addView(searchView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 58, Gravity.BOTTOM | Gravity.LEFT)); - gridView = new RecyclerListView(context) { + gridView = new RecyclerListView(context, resourcesProvider) { @Override protected boolean allowSelectChildAtPosition(float x, float y) { @@ -929,7 +938,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi }); containerView.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0)); gridView.setAdapter(listAdapter = new ShareDialogsAdapter(context)); - gridView.setGlowColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow)); + gridView.setGlowColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow)); gridView.setOnItemClickListener((view, position) -> { if (position < 0) { return; @@ -951,7 +960,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi }); - searchGridView = new RecyclerListView(context) { + searchGridView = new RecyclerListView(context, resourcesProvider) { @Override protected void dispatchDraw(Canvas canvas) { @@ -1017,13 +1026,13 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi } }); searchGridView.setAdapter(searchAdapter); - searchGridView.setGlowColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow)); + searchGridView.setGlowColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogScrollGlow)); recyclerItemsEnterAnimator = new RecyclerItemsEnterAnimator(searchGridView, true); - FlickerLoadingView flickerLoadingView = new FlickerLoadingView(context); + FlickerLoadingView flickerLoadingView = new FlickerLoadingView(context, resourcesProvider); flickerLoadingView.setViewType(FlickerLoadingView.SHARE_ALERT_TYPE); - searchEmptyView = new EmptyTextProgressView(context, flickerLoadingView); + searchEmptyView = new EmptyTextProgressView(context, flickerLoadingView, resourcesProvider); searchEmptyView.setShowAtCenter(true); searchEmptyView.showTextView(); searchEmptyView.setText(LocaleController.getString("NoChats", R.string.NoChats)); @@ -1036,7 +1045,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT); frameLayoutParams.topMargin = AndroidUtilities.dp(darkTheme && linkToCopy[1] != null ? 111 : 58); shadow[0] = new View(context); - shadow[0].setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow[0].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadow[0].setAlpha(0.0f); shadow[0].setTag(1); containerView.addView(shadow[0], frameLayoutParams); @@ -1046,13 +1055,13 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.BOTTOM | Gravity.LEFT); frameLayoutParams.bottomMargin = AndroidUtilities.dp(48); shadow[1] = new View(context); - shadow[1].setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow[1].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); containerView.addView(shadow[1], frameLayoutParams); if (isChannel || linkToCopy[0] != null) { pickerBottomLayout = new TextView(context); - pickerBottomLayout.setBackgroundDrawable(Theme.createSelectorWithBackgroundDrawable(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground), Theme.getColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector))); - pickerBottomLayout.setTextColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2)); + pickerBottomLayout.setBackgroundDrawable(Theme.createSelectorWithBackgroundDrawable(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground), getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector))); + pickerBottomLayout.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2)); pickerBottomLayout.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); pickerBottomLayout.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); pickerBottomLayout.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -1081,19 +1090,19 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi sharesCountLayout = new LinearLayout(context); sharesCountLayout.setOrientation(LinearLayout.HORIZONTAL); sharesCountLayout.setGravity(Gravity.CENTER_VERTICAL); - sharesCountLayout.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector), 2)); + sharesCountLayout.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(darkTheme ? Theme.key_voipgroup_listSelector : Theme.key_listSelector), 2)); containerView.addView(sharesCountLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.RIGHT | Gravity.BOTTOM, 6, 0, -6, 0)); sharesCountLayout.setOnClickListener(view -> parentFragment.presentFragment(new MessageStatisticActivity(messageObject))); ImageView imageView = new ImageView(context); imageView.setImageResource(R.drawable.share_arrow); - imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2), PorterDuff.Mode.MULTIPLY)); + imageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2), PorterDuff.Mode.MULTIPLY)); sharesCountLayout.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL, 20, 0, 0, 0)); TextView textView = new TextView(context); textView.setText(String.format("%d", messageObject.messageOwner.forwards)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2)); + textView.setTextColor(getThemedColor(darkTheme ? Theme.key_voipgroup_listeningText : Theme.key_dialogTextBlue2)); textView.setGravity(Gravity.CENTER_VERTICAL); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); sharesCountLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL, 8, 0, 20, 0)); @@ -1143,7 +1152,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi float alphaOffset = (frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(48)) * (1f - getAlpha()); shadow[1].setTranslationY(-(frameLayout2.getMeasuredHeight() - AndroidUtilities.dp(48)) + captionEditTextTopOffset + currentPanTranslationY + alphaOffset); - int newColor = Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground); + int newColor = getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground); if (color != newColor) { color = newColor; p.setColor(color); @@ -1165,7 +1174,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi containerView.addView(frameLayout2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM)); frameLayout2.setOnTouchListener((v, event) -> true); - commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG) { + commentTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, null, EditTextEmoji.STYLE_DIALOG, resourcesProvider) { private boolean shouldAnimateEditTextWithBounds; private int messageEditTextPredrawHeigth; @@ -1209,7 +1218,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi } }; if (forCall) { - commentTextView.getEditText().setTextColor(Theme.getColor(Theme.key_voipgroup_nameText)); + commentTextView.getEditText().setTextColor(getThemedColor(Theme.key_voipgroup_nameText)); } commentTextView.setHint(LocaleController.getString("ShareComment", R.string.ShareComment)); commentTextView.onResume(); @@ -1236,7 +1245,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi containerView.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 6, 10)); ImageView writeButton = new ImageView(context); - Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_dialogFloatingButton), Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); + Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); if (Build.VERSION.SDK_INT < 21) { Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate(); shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY)); @@ -1247,7 +1256,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi writeButton.setBackgroundDrawable(drawable); writeButton.setImageResource(R.drawable.attach_send); writeButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - writeButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); + writeButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { writeButton.setOutlineProvider(new ViewOutlineProvider() { @@ -1312,12 +1321,12 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi int cx = getMeasuredWidth() / 2; int cy = getMeasuredHeight() / 2; - textPaint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBoxCheck)); - paint.setColor(Theme.getColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); + textPaint.setColor(getThemedColor(Theme.key_dialogRoundCheckBoxCheck)); + paint.setColor(getThemedColor(darkTheme ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground)); rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight()); canvas.drawRoundRect(rect, AndroidUtilities.dp(12), AndroidUtilities.dp(12), paint); - paint.setColor(Theme.getColor(Theme.key_dialogRoundCheckBox)); + paint.setColor(getThemedColor(Theme.key_dialogRoundCheckBox)); rect.set(cx - size / 2 + AndroidUtilities.dp(2), AndroidUtilities.dp(2), cx + size / 2 - AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(2)); canvas.drawRoundRect(rect, AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint); @@ -1362,12 +1371,11 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi private void selectDialog(ShareDialogCell cell, TLRPC.Dialog dialog) { if (hasPoll != 0) { - int lowerId = (int) dialog.id; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(dialog.id)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); boolean isChannel = ChatObject.isChannel(chat) && hasPoll == 2 && !chat.megagroup; if (isChannel || !ChatObject.canSendPolls(chat)) { - AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), resourcesProvider); builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle)); if (isChannel) { builder.setMessage(LocaleController.getString("PublicPollCantForward", R.string.PublicPollCantForward)); @@ -1394,7 +1402,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi cell.setChecked(true, true); } updateSelectedCount(2); - int selfUserId = UserConfig.getInstance(currentAccount).clientUserId; + long selfUserId = UserConfig.getInstance(currentAccount).clientUserId; if (searchIsVisible) { TLRPC.Dialog existingDialog = listAdapter.dialogsMap.get(dialog.id); if (existingDialog == null) { @@ -1559,7 +1567,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi clipboard.setPrimaryClip(clip); if ((delegate == null || !delegate.didCopy()) && parentActivity instanceof LaunchActivity) { final boolean isPrivate = exportedMessageLink != null && exportedMessageLink.link.contains("/c/"); - ((LaunchActivity) parentActivity).showBulletin(factory -> factory.createCopyLinkBulletin(isPrivate)); + ((LaunchActivity) parentActivity).showBulletin(factory -> factory.createCopyLinkBulletin(isPrivate, resourcesProvider)); } } catch (Exception e) { FileLog.e(e); @@ -1675,7 +1683,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi public void fetchDialogs() { dialogs.clear(); dialogsMap.clear(); - int selfUserId = UserConfig.getInstance(currentAccount).clientUserId; + long selfUserId = UserConfig.getInstance(currentAccount).clientUserId; if (!MessagesController.getInstance(currentAccount).dialogsForward.isEmpty()) { TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogsForward.get(0); dialogs.add(dialog); @@ -1688,13 +1696,11 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi if (!(dialog instanceof TLRPC.TL_dialog)) { continue; } - int lower_id = (int) dialog.id; - if (lower_id == selfUserId) { + if (dialog.id == selfUserId) { continue; } - int high_id = (int) (dialog.id >> 32); - if (lower_id != 0 && high_id != 1) { - if (lower_id > 0) { + if (!DialogObject.isEncryptedDialog(dialog.id)) { + if (DialogObject.isUserDialog(dialog.id)) { if (dialog.folder_id == 1) { archivedDialogs.add(dialog); } else { @@ -1702,7 +1708,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi } dialogsMap.put(dialog.id, dialog); } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialog.id); if (!(chat == null || ChatObject.isNotInChat(chat) || chat.gigagroup && !ChatObject.hasAdminRights(chat) || ChatObject.isChannel(chat) && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) && !chat.megagroup)) { if (dialog.folder_id == 1) { archivedDialogs.add(dialog); @@ -1748,7 +1754,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi View view; switch (viewType) { case 0: { - view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE); + view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE, resourcesProvider); view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(100))); break; } @@ -1767,7 +1773,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi if (holder.getItemViewType() == 0) { ShareDialogCell cell = (ShareDialogCell) holder.itemView; TLRPC.Dialog dialog = getItem(position); - cell.setDialog((int) dialog.id, selectedDialogs.indexOfKey(dialog.id) >= 0, null); + cell.setDialog(dialog.id, selectedDialogs.indexOfKey(dialog.id) >= 0, null); } } @@ -1860,8 +1866,8 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi search[1] = search2; } - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); int resultCount = 0; LongSparseArray dialogsResult = new LongSparseArray<>(); @@ -1872,17 +1878,13 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi dialogSearchResult.date = cursor.intValue(1); dialogsResult.put(id, dialogSearchResult); - int lower_id = (int) id; - int high_id = (int) (id >> 32); - if (lower_id != 0 && high_id != 1) { - if (lower_id > 0) { - if (!usersToLoad.contains(lower_id)) { - usersToLoad.add(lower_id); - } - } else { - if (!chatsToLoad.contains(-lower_id)) { - chatsToLoad.add(-lower_id); - } + if (DialogObject.isUserDialog(id)) { + if (!usersToLoad.contains(id)) { + usersToLoad.add(id); + } + } else if (DialogObject.isChatDialog(id)) { + if (!chatsToLoad.contains(-id)) { + chatsToLoad.add(-id); } } } @@ -1949,7 +1951,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi TLRPC.Chat chat = TLRPC.Chat.TLdeserialize(data, data.readInt32(false), false); data.reuse(); if (!(chat == null || ChatObject.isNotInChat(chat) || ChatObject.isChannel(chat) && !chat.creator && (chat.admin_rights == null || !chat.admin_rights.post_messages) && !chat.megagroup)) { - DialogSearchResult dialogSearchResult = dialogsResult.get(-(long) chat.id); + DialogSearchResult dialogSearchResult = dialogsResult.get(-chat.id); dialogSearchResult.name = AndroidUtilities.generateSearchName(chat.title, null, q); dialogSearchResult.object = chat; dialogSearchResult.dialog.id = -chat.id; @@ -1973,7 +1975,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT u.data, u.status, u.name, u.uid FROM users as u INNER JOIN contacts as c ON u.uid = c.uid"); while (cursor.next()) { - int uid = cursor.intValue(3); + long uid = cursor.longValue(3); if (dialogsResult.indexOfKey(uid) >= 0) { continue; } @@ -2206,7 +2208,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi View view; switch (viewType) { case 0: { - view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE); + view = new ShareDialogCell(context, darkTheme ? ShareDialogCell.TYPE_CALL : ShareDialogCell.TYPE_SHARE, resourcesProvider); view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(100))); break; } @@ -2217,7 +2219,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi break; } case 2: { - RecyclerListView horizontalListView = new RecyclerListView(context) { + RecyclerListView horizontalListView = new RecyclerListView(context, resourcesProvider) { @Override public boolean onInterceptTouchEvent(MotionEvent e) { if (getParent() != null && getParent().getParent() != null) { @@ -2244,7 +2246,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi TLRPC.TL_topPeer peer = MediaDataController.getInstance(currentAccount).hints.get(position); TLRPC.Chat chat = null; TLRPC.User user = null; - int did = 0; + long did = 0; if (peer.peer.user_id != 0) { did = peer.peer.user_id; user = MessagesController.getInstance(currentAccount).getUser(peer.peer.user_id); @@ -2272,7 +2274,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi TLRPC.Dialog dialog = new TLRPC.TL_dialog(); TLRPC.Chat chat = null; TLRPC.User user = null; - int did = 0; + long did = 0; if (peer.peer.user_id != 0) { did = peer.peer.user_id; } else if (peer.peer.channel_id != 0) { @@ -2289,7 +2291,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi break; } case 3: { - GraySectionCell graySectionCell = new GraySectionCell(context); + GraySectionCell graySectionCell = new GraySectionCell(context, resourcesProvider); graySectionCell.setText(LocaleController.getString("Recent", R.string.Recent)); view = graySectionCell; break; @@ -2340,7 +2342,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi int index; if (name != null && (index = AndroidUtilities.indexOfIgnoreCase(name.toString(), foundUserName)) != -1) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(name); - spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); name = spannableStringBuilder; } } @@ -2372,12 +2374,12 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi int index; if (name != null && (index = AndroidUtilities.indexOfIgnoreCase(name.toString(), foundUserName)) != -1) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(name); - spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), index, index + foundUserName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); name = spannableStringBuilder; } } } - cell.setDialog((int) id, selectedDialogs.indexOfKey(id) >= 0, name); + cell.setDialog(id, selectedDialogs.indexOfKey(id) >= 0, name); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SharedMediaLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SharedMediaLayout.java index ac29406bc..5321c16b2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SharedMediaLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SharedMediaLayout.java @@ -49,6 +49,7 @@ import androidx.recyclerview.widget.RecyclerView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageReceiver; @@ -213,7 +214,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter sharedMediaData = new SharedMediaData[6]; for (int a = 0; a < sharedMediaData.length; a++) { sharedMediaData[a] = new SharedMediaData(); - sharedMediaData[a].setMaxId(0, (int) dialogId == 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); + sharedMediaData[a].setMaxId(0, DialogObject.isEncryptedDialog(dialogId) ? Integer.MIN_VALUE : Integer.MAX_VALUE); } loadMediaCounts(); @@ -316,7 +317,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter return; } if (dialogId == (Long) args[0]) { - boolean enc = ((int) dialogId) == 0; + boolean enc = DialogObject.isEncryptedDialog(dialogId); ArrayList arr = (ArrayList) args[1]; for (int a = 0; a < arr.size(); a++) { MessageObject obj = arr.get(a); @@ -348,7 +349,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter int type = (Integer) args[4]; sharedMediaData[type].setTotalCount((Integer) args[1]); ArrayList arr = (ArrayList) args[2]; - boolean enc = ((int) did) == 0; + boolean enc = DialogObject.isEncryptedDialog(did); int loadIndex = did == dialogId ? 0 : 1; if (!arr.isEmpty()) { sharedMediaData[type].setEndReached(loadIndex, (Boolean) args[5]); @@ -363,11 +364,10 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter if (scheduled) { return; } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; TLRPC.Chat currentChat; - int lowerId = (int) dialogId; - if (lowerId < 0) { - currentChat = parentFragment.getMessagesController().getChat(-lowerId); + if (DialogObject.isChatDialog(dialogId)) { + currentChat = parentFragment.getMessagesController().getChat(-dialogId); } else { currentChat = null; } @@ -733,7 +733,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter dialog_id = did; for (int a = 0; a < sharedMediaData.length; a++) { sharedMediaData[a] = new SharedMediaData(); - sharedMediaData[a].max_id[0] = ((int) dialog_id) == 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; + sharedMediaData[a].max_id[0] = DialogObject.isEncryptedDialog(dialog_id) ? Integer.MIN_VALUE : Integer.MAX_VALUE; fillMediaData(a); if (mergeDialogId != 0 && info != null) { sharedMediaData[a].max_id[1] = info.migrated_from_max_id; @@ -888,7 +888,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter actionModeLayout.addView(selectedMessagesCountTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 18, 0, 0, 0)); actionModeViews.add(selectedMessagesCountTextView); - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialog_id)) { gotoItem = new ActionBarMenuItem(context, null, Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2), false); gotoItem.setIcon(R.drawable.msg_message); gotoItem.setContentDescription(LocaleController.getString("AccDescrGoToMessage", R.string.AccDescrGoToMessage)); @@ -1128,7 +1128,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter } onMemberClick(participant, false); } else if (mediaPage.listView.getAdapter() == groupUsersSearchAdapter) { - int user_id; + long user_id; TLObject object = groupUsersSearchAdapter.getItem(position); if (object instanceof TLRPC.ChannelParticipant) { TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) object; @@ -1144,13 +1144,13 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter return; } Bundle args = new Bundle(); - args.putInt("user_id", user_id); + args.putLong("user_id", user_id); profileActivity.presentFragment(new ProfileActivity(args)); } } else if (mediaPage.selectedType == 6 && view instanceof ProfileSearchCell) { TLRPC.Chat chat = ((ProfileSearchCell) view).getChat(); Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); if (!profileActivity.getMessagesController().checkCanOpenChat(args, profileActivity)) { return; } @@ -1283,7 +1283,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter floatingDateView.setTranslationY(-AndroidUtilities.dp(48)); addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 48 + 4, 0, 0)); - addView(fragmentContextView = new FragmentContextView(context, parent, this, false), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0)); + addView(fragmentContextView = new FragmentContextView(context, parent, this, false, null), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0)); fragmentContextView.setDelegate((start, show) -> { if (!start) { requestLayout(); @@ -1640,21 +1640,18 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter TLRPC.Chat currentChat = null; TLRPC.User currentUser = null; TLRPC.EncryptedChat currentEncryptedChat = null; - int lower_id = (int) dialog_id; - if (lower_id != 0) { - if (lower_id > 0) { - currentUser = profileActivity.getMessagesController().getUser(lower_id); - } else { - currentChat = profileActivity.getMessagesController().getChat(-lower_id); - } + if (DialogObject.isEncryptedDialog(dialog_id)) { + currentEncryptedChat = profileActivity.getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialog_id)); + } else if (DialogObject.isUserDialog(dialog_id)) { + currentUser = profileActivity.getMessagesController().getUser(dialog_id); } else { - currentEncryptedChat = profileActivity.getMessagesController().getEncryptedChat((int) (dialog_id >> 32)); + currentChat = profileActivity.getMessagesController().getChat(-dialog_id); } AlertsCreator.createDeleteMessagesAlert(profileActivity, currentUser, currentChat, currentEncryptedChat, null, mergeDialogId, null, selectedFiles, null, false, 1, () -> { showActionMode(false); actionBar.closeSearchField(); cantDeleteMessagesCount = 0; - }); + }, null); } else if (id == forward) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); @@ -1690,20 +1687,16 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter fragment1.finishFragment(); } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); } else { - args1.putInt("enc_id", high_part); - } - if (lower_part != 0) { + if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); + } else { + args1.putLong("chat_id", -did); + } if (!profileActivity.getMessagesController().checkCanOpenChat(args1, fragment1)) { return; } @@ -1723,21 +1716,18 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter } MessageObject messageObject = selectedFiles[selectedFiles[0].size() == 1 ? 0 : 1].valueAt(0); Bundle args = new Bundle(); - int lower_part = (int) messageObject.getDialogId(); - int high_id = (int) (messageObject.getDialogId() >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - TLRPC.Chat chat = profileActivity.getMessagesController().getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - args.putInt("chat_id", -lower_part); - } + long dialogId = messageObject.getDialogId(); + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + TLRPC.Chat chat = profileActivity.getMessagesController().getChat(-dialogId); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", dialogId); + dialogId = -chat.migrated_to.channel_id; + } + args.putLong("chat_id", -dialogId); } args.putInt("message_id", messageObject.getId()); args.putBoolean("need_remove_previous_same_chat_activity", false); @@ -2108,7 +2098,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter if (guid == profileActivity.getClassGuid()) { sharedMediaData[type].totalCount = (Integer) args[1]; ArrayList arr = (ArrayList) args[2]; - boolean enc = ((int) dialog_id) == 0; + boolean enc = DialogObject.isEncryptedDialog(dialog_id); int loadIndex = uid == dialog_id ? 0 : 1; RecyclerListView.Adapter adapter = null; @@ -2200,10 +2190,10 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter return; } TLRPC.Chat currentChat = null; - if ((int) dialog_id < 0) { - currentChat = profileActivity.getMessagesController().getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialog_id)) { + currentChat = profileActivity.getMessagesController().getChat(-dialog_id); } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; int loadIndex = 0; if (ChatObject.isChannel(currentChat)) { if (channelId == 0 && mergeDialogId != 0) { @@ -2254,7 +2244,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter long uid = (Long) args[0]; if (uid == dialog_id) { ArrayList arr = (ArrayList) args[1]; - boolean enc = ((int) dialog_id) == 0; + boolean enc = DialogObject.isEncryptedDialog(dialog_id); boolean updated = false; for (int a = 0; a < arr.size(); a++) { MessageObject obj = arr.get(a); @@ -2522,7 +2512,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter if ((hasMedia[1] <= 0) == scrollSlidingTextTabStrip.hasTab(1)) { changed++; } - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialog_id)) { if ((hasMedia[3] <= 0) == scrollSlidingTextTabStrip.hasTab(3)) { changed++; } @@ -2600,7 +2590,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter scrollSlidingTextTabStrip.addTextTab(1, LocaleController.getString("SharedFilesTab2", R.string.SharedFilesTab2), idToView); } } - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialog_id)) { if (hasMedia[3] > 0) { if (!scrollSlidingTextTabStrip.hasTab(3)) { scrollSlidingTextTabStrip.addTextTab(3, LocaleController.getString("SharedLinksTab2", R.string.SharedLinksTab2), idToView); @@ -3414,42 +3404,42 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter EmptyStubView emptyStubView = new EmptyStubView(context); if (currentType == 0) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip1); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoMediaSecret", R.string.NoMediaSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoMedia", R.string.NoMedia)); } } else if (currentType == 1) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip2); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedFilesSecret", R.string.NoSharedFilesSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedFiles", R.string.NoSharedFiles)); } } else if (currentType == 2) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip5); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedVoiceSecret", R.string.NoSharedVoiceSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedVoice", R.string.NoSharedVoice)); } } else if (currentType == 3) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip3); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedLinksSecret", R.string.NoSharedLinksSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedLinks", R.string.NoSharedLinks)); } } else if (currentType == 4) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip4); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedAudioSecret", R.string.NoSharedAudioSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedAudio", R.string.NoSharedAudio)); } } else if (currentType == 5) { emptyStubView.emptyImageView.setImageResource(R.drawable.tip1); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialog_id)) { emptyStubView.emptyTextView.setText(LocaleController.getString("NoSharedGifSecret", R.string.NoSharedGifSecret)); } else { emptyStubView.emptyTextView.setText(LocaleController.getString("NoGIFs", R.string.NoGIFs)); @@ -3658,8 +3648,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter } public void queryServerSearch(final String query, final int max_id, long did) { - int uid = (int) did; - if (uid == 0) { + if (DialogObject.isEncryptedDialog(did)) { return; } if (reqId != 0) { @@ -3684,7 +3673,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter req.filter = new TLRPC.TL_inputMessagesFilterMusic(); } req.q = query; - req.peer = profileActivity.getMessagesController().getInputPeer(uid); + req.peer = profileActivity.getMessagesController().getInputPeer(did); if (req.peer == null) { return; } @@ -4062,19 +4051,17 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter mContext = context; } - private void getChats(int max_id, final int count) { + private void getChats(long max_id, final int count) { if (loading) { return; } TLRPC.TL_messages_getCommonChats req = new TLRPC.TL_messages_getCommonChats(); - int uid; - int lowerId = (int) dialog_id; - int hightId = (int) (dialog_id >> 32); - if (lowerId != 0) { - uid = lowerId; - } else { - TLRPC.EncryptedChat encryptedChat = profileActivity.getMessagesController().getEncryptedChat(hightId); + long uid; + if (DialogObject.isEncryptedDialog(dialog_id)) { + TLRPC.EncryptedChat encryptedChat = profileActivity.getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialog_id)); uid = encryptedChat.user_id; + } else { + uid = dialog_id; } req.user_id = profileActivity.getMessagesController().getInputUser(uid); if (req.user_id instanceof TLRPC.TL_inputUserEmpty) { @@ -4356,7 +4343,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter ArrayList resultArray2 = new ArrayList<>(); for (int a = 0, N = participantsCopy.size(); a < N; a++) { - int userId; + long userId; TLObject o = participantsCopy.get(a); if (o instanceof TLRPC.ChatParticipant) { userId = ((TLRPC.ChatParticipant) o).user_id; @@ -4452,7 +4439,7 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter super.notifyDataSetChanged(); } - public void removeUserId(int userId) { + public void removeUserId(long userId) { searchAdapterHelper.removeUserId(userId); notifyDataSetChanged(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SharingLocationsAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SharingLocationsAlert.java index 416d14b12..ffc21a0d5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SharingLocationsAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SharingLocationsAlert.java @@ -58,13 +58,13 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe void didSelectLocation(LocationController.SharingLocationInfo info); } - public SharingLocationsAlert(Context context, SharingLocationsAlertDelegate sharingLocationsAlertDelegate) { - super(context, false); + public SharingLocationsAlert(Context context, SharingLocationsAlertDelegate sharingLocationsAlertDelegate, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.liveLocationsChanged); delegate = sharingLocationsAlertDelegate; shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); - shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); + shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY)); containerView = new FrameLayout(context) { @@ -135,7 +135,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe listView = new RecyclerListView(context) { @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, 0, null); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, listView, 0, null, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } @@ -152,7 +152,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe listView.setVerticalScrollBarEnabled(false); listView.setClipToPadding(false); listView.setEnabled(true); - listView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); + listView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); listView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { @@ -174,10 +174,10 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe containerView.addView(shadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.BOTTOM | Gravity.LEFT, 0, 0, 0, 48)); PickerBottomLayout pickerBottomLayout = new PickerBottomLayout(context, false); - pickerBottomLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + pickerBottomLayout.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); containerView.addView(pickerBottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM)); pickerBottomLayout.cancelButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); - pickerBottomLayout.cancelButton.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); + pickerBottomLayout.cancelButton.setTextColor(getThemedColor(Theme.key_dialogTextRed)); pickerBottomLayout.cancelButton.setText(LocaleController.getString("StopAllLocationSharings", R.string.StopAllLocationSharings)); pickerBottomLayout.cancelButton.setOnClickListener(view -> { for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { @@ -185,7 +185,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe } dismiss(); }); - pickerBottomLayout.doneButtonTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2)); + pickerBottomLayout.doneButtonTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlue2)); pickerBottomLayout.doneButtonTextView.setText(LocaleController.getString("Close", R.string.Close).toUpperCase()); pickerBottomLayout.doneButton.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); pickerBottomLayout.doneButton.setOnClickListener(view -> dismiss()); @@ -276,7 +276,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe View view; switch (viewType) { case 0: - view = new SharingLiveLocationCell(context, false, 54); + view = new SharingLiveLocationCell(context, false, 54, resourcesProvider); //view.setBackgroundDrawable(Theme.getSelectorDrawable(false)); break; case 1: @@ -294,7 +294,7 @@ public class SharingLocationsAlert extends BottomSheet implements NotificationCe }; frameLayout.setWillNotDraw(false); textView = new TextView(context); - textView.setTextColor(Theme.getColor(Theme.key_dialogIcon)); + textView.setTextColor(getThemedColor(Theme.key_dialogIcon)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setGravity(Gravity.CENTER); textView.setPadding(0, 0, 0, AndroidUtilities.dp(8)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierFrameLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierFrameLayout.java index da6b1f43c..cf96d6e1a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierFrameLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SizeNotifierFrameLayout.java @@ -219,7 +219,7 @@ public class SizeNotifierFrameLayout extends FrameLayout { return; } //int kbHeight = SharedConfig.smoothKeyboard ? 0 : keyboardHeight; - Drawable newDrawable = Theme.getCachedWallpaperNonBlocking(); + Drawable newDrawable = getNewDrawable(); if (newDrawable != backgroundDrawable && newDrawable != null) { if (Theme.isAnimatingColor()) { oldBackgroundDrawable = backgroundDrawable; @@ -341,4 +341,13 @@ public class SizeNotifierFrameLayout extends FrameLayout { this.skipBackgroundDrawing = skipBackgroundDrawing; invalidate(); } + + protected Drawable getNewDrawable() { + return Theme.getCachedWallpaperNonBlocking(); + } + + @Override + protected boolean verifyDrawable(Drawable who) { + return who == getBackgroundImage() || super.verifyDrawable(who); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideChooseView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideChooseView.java index 23cfc4c14..35a9c6249 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideChooseView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SlideChooseView.java @@ -41,9 +41,15 @@ public class SlideChooseView extends View { private int selectedIndex; private Callback callback; + private final Theme.ResourcesProvider resourcesProvider; public SlideChooseView(Context context) { + this(context, null); + } + + public SlideChooseView(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; paint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); @@ -170,17 +176,17 @@ public class SlideChooseView extends View { @Override protected void onDraw(Canvas canvas) { - textPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + textPaint.setColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); int cy = getMeasuredHeight() / 2 + AndroidUtilities.dp(11); for (int a = 0; a < optionsStr.length; a++) { int cx = sideSide + (lineSize + gapSize * 2 + circleSize) * a + circleSize / 2; if (a <= selectedIndex) { - int color = Theme.getColor(Theme.key_switchTrackChecked); + int color = getThemedColor(Theme.key_switchTrackChecked); paint.setColor(color); linePaint.setColor(color); } else { - int color = Theme.getColor(Theme.key_switchTrack); + int color = getThemedColor(Theme.key_switchTrack); paint.setColor(color); linePaint.setColor(color); } @@ -236,6 +242,12 @@ public class SlideChooseView extends View { return selectedIndex; } + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } + + public interface Callback { void onOptionSelected(int index); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerEmptyView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerEmptyView.java index 0dcafe720..394bf576c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerEmptyView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerEmptyView.java @@ -31,8 +31,8 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. private RadialProgressView progressBar; public final TextView title; public final TextView subtitle; - private final String stickerSetName = "tg_placeholders"; private boolean progressShowing; + private final Theme.ResourcesProvider resourcesProvider; private int stickerType; @@ -62,7 +62,12 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. private boolean animateLayoutChange; public StickerEmptyView(@NonNull Context context, View progressView, int type) { + this(context, progressView, type, null); + } + + public StickerEmptyView(@NonNull Context context, View progressView, int type, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; this.progressView = progressView; stickerType = type; @@ -98,13 +103,13 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. title.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); title.setTag(Theme.key_windowBackgroundWhiteBlackText); - title.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + title.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); title.setGravity(Gravity.CENTER); subtitle = new TextView(context); subtitle.setTag(Theme.key_windowBackgroundWhiteGrayText); - subtitle.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + subtitle.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText)); subtitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitle.setGravity(Gravity.CENTER); @@ -114,7 +119,7 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 56, 0, 56, 30)); if (progressView == null) { - progressBar = new RadialProgressView(context); + progressBar = new RadialProgressView(context, resourcesProvider); progressBar.setAlpha(0); progressBar.setScaleY(0.5f); progressBar.setScaleX(0.5f); @@ -145,10 +150,10 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. public void setColors(String titleKey, String subtitleKey, String key1, String key2) { title.setTag(titleKey); - title.setTextColor(Theme.getColor(titleKey)); + title.setTextColor(getThemedColor(titleKey)); subtitle.setTag(subtitleKey); - subtitle.setTextColor(Theme.getColor(subtitleKey)); + subtitle.setTextColor(getThemedColor(subtitleKey)); stubDrawable.setColors(key1, key2); } @@ -222,9 +227,9 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. } private void setSticker() { - TLRPC.TL_messages_stickerSet set = MediaDataController.getInstance(currentAccount).getStickerSetByName(stickerSetName); + TLRPC.TL_messages_stickerSet set = MediaDataController.getInstance(currentAccount).getStickerSetByName(AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME); if (set == null) { - set = MediaDataController.getInstance(currentAccount).getStickerSetByEmojiOrName(stickerSetName); + set = MediaDataController.getInstance(currentAccount).getStickerSetByEmojiOrName(AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME); } if (set != null && set.documents.size() >= 2) { TLRPC.Document document = set.documents.get(stickerType); @@ -232,7 +237,7 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. stickerView.setImage(imageLocation, "130_130", "tgs", stubDrawable, set); stickerView.getImageReceiver().setAutoRepeat(2); } else { - MediaDataController.getInstance(currentAccount).loadStickersByEmojiOrName(stickerSetName, false, set == null); + MediaDataController.getInstance(currentAccount).loadStickersByEmojiOrName(AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME, false, set == null); stickerView.setImageDrawable(stubDrawable); } } @@ -242,7 +247,7 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. public void didReceivedNotification(int id, int account, Object... args) { if (id == NotificationCenter.diceStickersDidLoad) { String name = (String) args[0]; - if (stickerSetName.equals(name) && getVisibility() == VISIBLE) { + if (AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME.equals(name) && getVisibility() == VISIBLE) { setSticker(); } } @@ -344,4 +349,9 @@ public class StickerEmptyView extends FrameLayout implements NotificationCenter. } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerMasksAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerMasksAlert.java index f937b639d..7a13375b5 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerMasksAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerMasksAlert.java @@ -281,8 +281,8 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter } } - public StickerMasksAlert(Context context, boolean isVideo) { - super(context, true); + public StickerMasksAlert(Context context, boolean isVideo, Theme.ResourcesProvider resourcesProvider) { + super(context, true, resourcesProvider); behindKeyboardColorKey = null; behindKeyboardColor = 0xff252525; useLightStatusBar = false; @@ -460,7 +460,7 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, containerView.getMeasuredHeight(), contentPreviewViewerDelegate); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, containerView.getMeasuredHeight(), contentPreviewViewerDelegate, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } }; @@ -517,7 +517,7 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter gridView.setGlowColor(0xff252525); stickersSearchGridAdapter = new StickersSearchGridAdapter(context); gridView.setAdapter(stickersGridAdapter = new StickersGridAdapter(context)); - gridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gridView, containerView.getMeasuredHeight(), stickersOnItemClickListener, contentPreviewViewerDelegate)); + gridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gridView, containerView.getMeasuredHeight(), stickersOnItemClickListener, contentPreviewViewerDelegate, resourcesProvider)); stickersOnItemClickListener = (view, position) -> { if (!(view instanceof StickerEmojiCell)) { return; @@ -530,7 +530,7 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter gridView.setOnItemClickListener(stickersOnItemClickListener); containerView.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - stickersTab = new ScrollSlidingTabStrip(context) { + stickersTab = new ScrollSlidingTabStrip(context, resourcesProvider) { @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (getParent() != null) { @@ -1057,7 +1057,7 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter view = new EmptyCell(context); break; case 2: - StickerSetNameCell cell = new StickerSetNameCell(context, false); + StickerSetNameCell cell = new StickerSetNameCell(context, false, resourcesProvider); cell.setTitleColor(0xff888888); view = cell; break; @@ -1464,7 +1464,7 @@ public class StickerMasksAlert extends BottomSheet implements NotificationCenter view = new EmptyCell(context); break; case 2: - view = new StickerSetNameCell(context, false); + view = new StickerSetNameCell(context, false, resourcesProvider); break; case 4: view = new View(context); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerSetBulletinLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerSetBulletinLayout.java index ddc7b8026..d0429aced 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerSetBulletinLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickerSetBulletinLayout.java @@ -14,12 +14,14 @@ import org.telegram.messenger.MessageObject; import org.telegram.messenger.R; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; +import org.telegram.ui.ActionBar.Theme; import java.util.ArrayList; @SuppressLint("ViewConstructor") public class StickerSetBulletinLayout extends Bulletin.TwoLineLayout { + public static final int TYPE_EMPTY = -1; public static final int TYPE_REMOVED = 0; public static final int TYPE_ARCHIVED = 1; public static final int TYPE_ADDED = 2; @@ -27,15 +29,15 @@ public class StickerSetBulletinLayout extends Bulletin.TwoLineLayout { public static final int TYPE_REMOVED_FROM_FAVORITES = 4; public static final int TYPE_ADDED_TO_FAVORITES = 5; - @IntDef(value = {TYPE_REMOVED, TYPE_ARCHIVED, TYPE_ADDED, TYPE_REMOVED_FROM_RECENT, TYPE_REMOVED_FROM_FAVORITES, TYPE_ADDED_TO_FAVORITES}) + @IntDef(value = {TYPE_EMPTY, TYPE_REMOVED, TYPE_ARCHIVED, TYPE_ADDED, TYPE_REMOVED_FROM_RECENT, TYPE_REMOVED_FROM_FAVORITES, TYPE_ADDED_TO_FAVORITES}) public @interface Type {} public StickerSetBulletinLayout(@NonNull Context context, TLObject setObject, @Type int type) { - this(context, setObject, type, null); + this(context, setObject, type, null, null); } - public StickerSetBulletinLayout(@NonNull Context context, TLObject setObject, @Type int type, TLRPC.Document sticker) { - super(context); + public StickerSetBulletinLayout(@NonNull Context context, TLObject setObject, @Type int type, TLRPC.Document sticker, Theme.ResourcesProvider resourcesProvider) { + super(context, resourcesProvider); final TLRPC.StickerSet stickerSet; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java index 13ff32582..e0d608d15 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java @@ -212,9 +212,10 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not return 0; } }; - - public StickersAlert(Context context, Object parentObject, TLObject object) { - super(context, false); + + public StickersAlert(Context context, Object parentObject, TLObject object, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); + this.resourcesProvider = resourcesProvider; parentActivity = (Activity) context; final TLRPC.TL_messages_getAttachedStickers req = new TLRPC.TL_messages_getAttachedStickers(); if (object instanceof TLRPC.Photo) { @@ -277,8 +278,8 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not init(context); } - public StickersAlert(Context context, String software, ArrayList uris, ArrayList emoji) { - super(context, false); + public StickersAlert(Context context, String software, ArrayList uris, ArrayList emoji, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); parentActivity = (Activity) context; importingStickers = uris; importingSoftware = software; @@ -354,7 +355,11 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } public StickersAlert(Context context, BaseFragment baseFragment, TLRPC.InputStickerSet set, TLRPC.TL_messages_stickerSet loadedSet, StickersAlertDelegate stickersAlertDelegate) { - super(context, false); + this(context, baseFragment, set, loadedSet, stickersAlertDelegate, null); + } + + public StickersAlert(Context context, BaseFragment baseFragment, TLRPC.InputStickerSet set, TLRPC.TL_messages_stickerSet loadedSet, StickersAlertDelegate stickersAlertDelegate, Theme.ResourcesProvider resourcesProvider) { + super(context, false, resourcesProvider); delegate = stickersAlertDelegate; inputStickerSet = set; stickerSet = loadedSet; @@ -556,18 +561,18 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not shadowDrawable.draw(canvas); if (radProgress != 1.0f) { - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_dialogBackground)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(Theme.key_dialogBackground)); rect.set(backgroundPaddingLeft, backgroundPaddingTop + top, getMeasuredWidth() - backgroundPaddingLeft, backgroundPaddingTop + top + AndroidUtilities.dp(24)); canvas.drawRoundRect(rect, AndroidUtilities.dp(12) * radProgress, AndroidUtilities.dp(12) * radProgress, Theme.dialogs_onlineCirclePaint); } int w = AndroidUtilities.dp(36); rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4)); - Theme.dialogs_onlineCirclePaint.setColor(Theme.getColor(Theme.key_sheet_scrollUp)); + Theme.dialogs_onlineCirclePaint.setColor(getThemedColor(Theme.key_sheet_scrollUp)); canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint); if (statusBarHeight > 0) { - int color1 = Theme.getColor(Theme.key_dialogBackground); + int color1 = getThemedColor(Theme.key_dialogBackground); int finalColor = Color.argb(0xff, (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f)); Theme.dialogs_onlineCirclePaint.setColor(finalColor); canvas.drawRect(backgroundPaddingLeft, AndroidUtilities.statusBarHeight - statusBarHeight, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, Theme.dialogs_onlineCirclePaint); @@ -580,7 +585,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.TOP | Gravity.LEFT); frameLayoutParams.topMargin = AndroidUtilities.dp(48); shadow[0] = new View(context); - shadow[0].setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow[0].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadow[0].setAlpha(0.0f); shadow[0].setVisibility(View.INVISIBLE); shadow[0].setTag(1); @@ -589,7 +594,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not gridView = new RecyclerListView(context) { @Override public boolean onInterceptTouchEvent(MotionEvent event) { - boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, 0, previewDelegate); + boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, 0, previewDelegate, resourcesProvider); return super.onInterceptTouchEvent(event) || result; } @@ -631,8 +636,8 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not gridView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0); gridView.setClipToPadding(false); gridView.setEnabled(true); - gridView.setGlowColor(Theme.getColor(Theme.key_dialogScrollGlow)); - gridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gridView, 0, stickersOnItemClickListener, previewDelegate)); + gridView.setGlowColor(getThemedColor(Theme.key_dialogScrollGlow)); + gridView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, gridView, 0, stickersOnItemClickListener, previewDelegate, resourcesProvider)); gridView.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { @@ -647,7 +652,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not TLRPC.TL_inputStickerSetID inputStickerSetID = new TLRPC.TL_inputStickerSetID(); inputStickerSetID.access_hash = pack.set.access_hash; inputStickerSetID.id = pack.set.id; - StickersAlert alert = new StickersAlert(parentActivity, parentFragment, inputStickerSetID, null, null); + StickersAlert alert = new StickersAlert(parentActivity, parentFragment, inputStickerSetID, null, null, resourcesProvider); alert.show(); } } else if (importingStickersPaths != null) { @@ -720,20 +725,20 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not titleTextView = new TextView(context); titleTextView.setLines(1); titleTextView.setSingleLine(true); - titleTextView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + titleTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); - titleTextView.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink)); + titleTextView.setLinkTextColor(getThemedColor(Theme.key_dialogTextLink)); titleTextView.setEllipsize(TextUtils.TruncateAt.END); titleTextView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); titleTextView.setGravity(Gravity.CENTER_VERTICAL); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); containerView.addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.LEFT | Gravity.TOP, 0, 0, 40, 0)); - optionsButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_sheet_other)); + optionsButton = new ActionBarMenuItem(context, null, 0, getThemedColor(Theme.key_sheet_other), resourcesProvider); optionsButton.setLongClickEnabled(false); optionsButton.setSubMenuOpenSide(2); optionsButton.setIcon(R.drawable.ic_ab_other); - optionsButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_player_actionBarSelector), 1)); + optionsButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_player_actionBarSelector), 1)); containerView.addView(optionsButton, LayoutHelper.createFrame(40, 40, Gravity.TOP | Gravity.RIGHT, 0, 5, 5, 0)); optionsButton.addSubItem(1, R.drawable.msg_share, LocaleController.getString("StickersShare", R.string.StickersShare)); optionsButton.addSubItem(2, R.drawable.msg_link, LocaleController.getString("CopyLink", R.string.CopyLink)); @@ -748,12 +753,12 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.BOTTOM | Gravity.LEFT); frameLayoutParams.bottomMargin = AndroidUtilities.dp(48); shadow[1] = new View(context); - shadow[1].setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadow[1].setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); containerView.addView(shadow[1], frameLayoutParams); pickerBottomLayout = new TextView(context); - pickerBottomLayout.setBackgroundDrawable(Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_dialogBackground), Theme.getColor(Theme.key_listSelector))); - pickerBottomLayout.setTextColor(Theme.getColor(buttonTextColorKey = Theme.key_dialogTextBlue2)); + pickerBottomLayout.setBackgroundDrawable(Theme.createSelectorWithBackgroundDrawable(getThemedColor(Theme.key_dialogBackground), getThemedColor(Theme.key_listSelector))); + pickerBottomLayout.setTextColor(getThemedColor(buttonTextColorKey = Theme.key_dialogTextBlue2)); pickerBottomLayout.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); pickerBottomLayout.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); pickerBottomLayout.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -778,8 +783,8 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not previewSendButton = new TextView(context); previewSendButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - previewSendButton.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2)); - previewSendButton.setBackground(Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_dialogBackground), Theme.getColor(Theme.key_listSelector))); + previewSendButton.setTextColor(getThemedColor(Theme.key_dialogTextBlue2)); + previewSendButton.setBackground(Theme.createSelectorWithBackgroundDrawable(getThemedColor(Theme.key_dialogBackground), getThemedColor(Theme.key_listSelector))); previewSendButton.setGravity(Gravity.CENTER); previewSendButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0); previewSendButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); @@ -798,7 +803,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not frameLayoutParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight(), Gravity.BOTTOM | Gravity.LEFT); frameLayoutParams.bottomMargin = AndroidUtilities.dp(48); previewSendButtonShadow = new View(context); - previewSendButtonShadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + previewSendButtonShadow.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); stickerPreviewLayout.addView(previewSendButtonShadow, frameLayoutParams); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded); @@ -817,7 +822,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not int size = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) / 2 / AndroidUtilities.density); if (importingStickers != null) { previewSendButton.setText(LocaleController.getString("ImportStickersRemove", R.string.ImportStickersRemove).toUpperCase()); - previewSendButton.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); + previewSendButton.setTextColor(getThemedColor(Theme.key_dialogTextRed)); stickerImageView.setLayoutParams(LayoutHelper.createFrame(size, size, Gravity.CENTER, 0, 0, 0, 30)); stickerEmojiTextView.setLayoutParams(LayoutHelper.createFrame(size, size, Gravity.CENTER, 0, 0, 0, 30)); previewSendButton.setVisibility(View.VISIBLE); @@ -867,7 +872,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not if (context == null) { context = getContext(); } - ShareAlert alert = new ShareAlert(context, null, stickersUrl, false, stickersUrl, false); + ShareAlert alert = new ShareAlert(context, null, stickersUrl, false, stickersUrl, false, resourcesProvider); if (parentFragment != null) { parentFragment.showDialog(alert); } else { @@ -876,7 +881,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } else if (id == 2) { try { AndroidUtilities.addToClipboard(stickersUrl); - BulletinFactory.of((FrameLayout) containerView).createCopyLinkBulletin().show(); + BulletinFactory.of((FrameLayout) containerView, resourcesProvider).createCopyLinkBulletin().show(); } catch (Exception e) { FileLog.e(e); } @@ -940,7 +945,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not try { if (error == null) { if (showTooltipWhenToggle) { - Bulletin.make(parentFragment, new StickerSetBulletinLayout(pickerBottomLayout.getContext(), stickerSet, StickerSetBulletinLayout.TYPE_ADDED), Bulletin.DURATION_SHORT).show(); + Bulletin.make(parentFragment, new StickerSetBulletinLayout(pickerBottomLayout.getContext(), stickerSet, StickerSetBulletinLayout.TYPE_ADDED, null, resourcesProvider), Bulletin.DURATION_SHORT).show(); } if (response instanceof TLRPC.TL_messages_stickerSetInstallResultArchive) { MediaDataController.getInstance(currentAccount).processStickerSetInstallResultArchive(parentFragment, true, type, (TLRPC.TL_messages_stickerSetInstallResultArchive) response); @@ -1017,7 +1022,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not TextView textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - textView.setTextColor(Theme.getColor(Theme.key_dialogTextHint)); + textView.setTextColor(getThemedColor(Theme.key_dialogTextHint)); textView.setMaxLines(1); textView.setLines(1); textView.setText("t.me/addstickers/"); @@ -1032,14 +1037,14 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not EditTextBoldCursor editText = new EditTextBoldCursor(context); editText.setBackgroundDrawable(Theme.createEditTextDrawable(context, true)); editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); - editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); + editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack)); editText.setMaxLines(1); editText.setLines(1); editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); editText.setGravity(Gravity.LEFT | Gravity.TOP); editText.setSingleLine(true); editText.setImeOptions(EditorInfo.IME_ACTION_NEXT); - editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + editText.setCursorColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText)); editText.setCursorSize(AndroidUtilities.dp(20)); editText.setCursorWidth(1.5f); editText.setPadding(0, AndroidUtilities.dp(4), 0, 0); @@ -1077,7 +1082,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not message.setText(AndroidUtilities.replaceTags(LocaleController.getString("ImportStickersEnterNameInfo", R.string.ImportStickersEnterNameInfo))); message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); message.setPadding(AndroidUtilities.dp(23), AndroidUtilities.dp(12), AndroidUtilities.dp(23), AndroidUtilities.dp(6)); - message.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + message.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); linearLayout.addView(message, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); final AlertDialog alertDialog = builder.create(); @@ -1121,7 +1126,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } AndroidUtilities.hideKeyboard(editText); SendMessagesHelper.getInstance(currentAccount).prepareImportStickers(setTitle, lastCheckName, importingSoftware, importingStickersPaths, (param) -> { - ImportingAlert importingAlert = new ImportingAlert(getContext(), lastCheckName, null); + ImportingAlert importingAlert = new ImportingAlert(getContext(), lastCheckName, null, resourcesProvider); importingAlert.show(); }); builder.getDismissRunnable().run(); @@ -1138,7 +1143,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not private void checkUrlAvailable(TextView message, String text, boolean forceAvailable) { if (forceAvailable) { message.setText(LocaleController.getString("ImportStickersLinkAvailable", R.string.ImportStickersLinkAvailable)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGreenText)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGreenText)); lastNameAvailable = true; lastCheckName = text; return; @@ -1153,38 +1158,38 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } if (TextUtils.isEmpty(text)) { message.setText(LocaleController.getString("ImportStickersEnterUrlInfo", R.string.ImportStickersEnterUrlInfo)); - message.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); + message.setTextColor(getThemedColor(Theme.key_dialogTextGray2)); return; } lastNameAvailable = false; if (text != null) { if (text.startsWith("_") || text.endsWith("_")) { message.setText(LocaleController.getString("ImportStickersLinkInvalid", R.string.ImportStickersLinkInvalid)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)); return; } for (int a = 0, N = text.length(); a < N; a++) { char ch = text.charAt(a); if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) { message.setText(LocaleController.getString("ImportStickersEnterUrlInfo", R.string.ImportStickersEnterUrlInfo)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)); return; } } } if (text == null || text.length() < 5) { message.setText(LocaleController.getString("ImportStickersLinkInvalidShort", R.string.ImportStickersLinkInvalidShort)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)); return; } if (text.length() > 32) { message.setText(LocaleController.getString("ImportStickersLinkInvalidLong", R.string.ImportStickersLinkInvalidLong)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)); return; } message.setText(LocaleController.getString("ImportStickersLinkChecking", R.string.ImportStickersLinkChecking)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText8)); lastCheckName = text; checkRunnable = () -> { TLRPC.TL_stickers_checkShortName req = new TLRPC.TL_stickers_checkShortName(); @@ -1194,11 +1199,11 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not if (lastCheckName != null && lastCheckName.equals(text)) { if (error == null && response instanceof TLRPC.TL_boolTrue) { message.setText(LocaleController.getString("ImportStickersLinkAvailable", R.string.ImportStickersLinkAvailable)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGreenText)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGreenText)); lastNameAvailable = true; } else { message.setText(LocaleController.getString("ImportStickersLinkTaken", R.string.ImportStickersLinkTaken)); - message.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4)); + message.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)); lastNameAvailable = false; } } @@ -1334,7 +1339,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not super.onStart(); Bulletin.addDelegate((FrameLayout) containerView, new Bulletin.Delegate() { @Override - public int getBottomOffset() { + public int getBottomOffset(int tag) { return pickerBottomLayout != null ? pickerBottomLayout.getHeight() : 0; } }); @@ -1406,7 +1411,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } private void setButton(View.OnClickListener onClickListener, String title, String colorKey) { - pickerBottomLayout.setTextColor(Theme.getColor(buttonTextColorKey = colorKey)); + pickerBottomLayout.setTextColor(getThemedColor(buttonTextColorKey = colorKey)); pickerBottomLayout.setText(title.toUpperCase()); pickerBottomLayout.setOnClickListener(onClickListener); } @@ -1428,14 +1433,14 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not public void updateColors(boolean applyDescriptions) { adapter.updateColors(); - titleTextView.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection)); - stickerPreviewLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground) & 0xdfffffff); + titleTextView.setHighlightColor(getThemedColor(Theme.key_dialogLinkSelection)); + stickerPreviewLayout.setBackgroundColor(getThemedColor(Theme.key_dialogBackground) & 0xdfffffff); - optionsButton.setIconColor(Theme.getColor(Theme.key_sheet_other)); - optionsButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem), false); - optionsButton.setPopupItemsColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon), true); - optionsButton.setPopupItemsSelectorColor(Theme.getColor(Theme.key_dialogButtonSelector)); - optionsButton.redrawPopup(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground)); + optionsButton.setIconColor(getThemedColor(Theme.key_sheet_other)); + optionsButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem), false); + optionsButton.setPopupItemsColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon), true); + optionsButton.setPopupItemsSelectorColor(getThemedColor(Theme.key_dialogButtonSelector)); + optionsButton.redrawPopup(getThemedColor(Theme.key_actionBarDefaultSubmenuBackground)); if (applyDescriptions) { if (Theme.isAnimatingColor() && animatingDescriptions == null) { @@ -1446,7 +1451,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } for (int i = 0, N = animatingDescriptions.size(); i < N; i++) { final ThemeDescription description = animatingDescriptions.get(i); - description.setColor(Theme.getColor(description.getCurrentKey()), false, false); + description.setColor(getThemedColor(description.getCurrentKey()), false, false); } } @@ -1547,7 +1552,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not view = new EmptyCell(context); break; case 2: - view = new FeaturedStickerSetInfoCell(context, 8, true, false); + view = new FeaturedStickerSetInfoCell(context, 8, true, false, resourcesProvider); break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/StorageDiagramView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StorageDiagramView.java similarity index 95% rename from TMessagesProj/src/main/java/org/telegram/ui/StorageDiagramView.java rename to TMessagesProj/src/main/java/org/telegram/ui/Components/StorageDiagramView.java index 4defbeec4..a637011e0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/StorageDiagramView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StorageDiagramView.java @@ -1,4 +1,4 @@ -package org.telegram.ui; +package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -12,13 +12,11 @@ import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.view.View; -import android.view.animation.LinearInterpolator; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; import org.telegram.messenger.AndroidUtilities; import org.telegram.ui.ActionBar.Theme; -import org.telegram.ui.Components.CubicBezierInterpolator; public class StorageDiagramView extends View { @@ -182,9 +180,9 @@ public class StorageDiagramView extends View { public String color; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - boolean clear = true; + public boolean clear = true; boolean firstDraw = false; - long size; + public long size; private final StorageDiagramView parentView; @@ -223,7 +221,6 @@ public class StorageDiagramView extends View { float k = 0; float max= 0; - int maxIndex = 0; enabledCount = 0; for (int i = 0; i < data.length; i++) { @@ -243,7 +240,6 @@ public class StorageDiagramView extends View { k += percent; if (percent > max && data[i].clear) { max = percent; - maxIndex = i; } animateToPercentage[i] = percent; } @@ -258,13 +254,9 @@ public class StorageDiagramView extends View { } if (!animate) { - for (int i = 0; i < data.length; i++) { - drawingPercentage[i] = animateToPercentage[i]; - } + System.arraycopy(animateToPercentage, 0, drawingPercentage, 0, data.length); } else { - for (int i = 0; i < data.length; i++) { - startFromPercentage[i] = drawingPercentage[i]; - } + System.arraycopy(drawingPercentage, 0, startFromPercentage, 0, data.length); if (valueAnimator != null) { valueAnimator.removeAllListeners(); @@ -306,10 +298,9 @@ public class StorageDiagramView extends View { total += data[i].size; } String[] str = AndroidUtilities.formatFileSize(total).split(" "); - if (str != null & str.length > 1) { + if (str.length > 1) { layout1 = new StaticLayout(total == 0 ? " " : str[0], textPaint, getMeasuredWidth(), Layout.Alignment.ALIGN_CENTER, 1f, 0, false); layout2 = new StaticLayout(total == 0 ? " " : str[1], textPaint2, getMeasuredWidth(), Layout.Alignment.ALIGN_CENTER, 1f, 0, false); } - } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/StroageUsageView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StroageUsageView.java similarity index 98% rename from TMessagesProj/src/main/java/org/telegram/ui/StroageUsageView.java rename to TMessagesProj/src/main/java/org/telegram/ui/Components/StroageUsageView.java index 601e1fd48..b36e36e5b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/StroageUsageView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StroageUsageView.java @@ -1,9 +1,8 @@ -package org.telegram.ui; +package org.telegram.ui.Components; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; -import android.graphics.Color; import android.graphics.Paint; import android.text.SpannableString; import android.view.View; @@ -19,11 +18,9 @@ import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Cells.TextSettingsCell; -import org.telegram.ui.Components.EllipsizeSpanAnimator; -import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.voip.CellFlickerDrawable; -class StroageUsageView extends FrameLayout { +public class StroageUsageView extends FrameLayout { private Paint paintFill = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint paintCalculcating = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -51,7 +48,7 @@ class StroageUsageView extends FrameLayout { float progress2; ValueAnimator valueAnimator; ValueAnimator valueAnimator2; - ViewGroup legendLayout; + public ViewGroup legendLayout; EllipsizeSpanAnimator ellipsizeSpanAnimator; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SwipeGestureSettingsView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/SwipeGestureSettingsView.java similarity index 96% rename from TMessagesProj/src/main/java/org/telegram/ui/SwipeGestureSettingsView.java rename to TMessagesProj/src/main/java/org/telegram/ui/Components/SwipeGestureSettingsView.java index 267dac05e..556e86df3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SwipeGestureSettingsView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/SwipeGestureSettingsView.java @@ -1,4 +1,4 @@ -package org.telegram.ui; +package org.telegram.ui.Components; import android.content.Context; import android.graphics.Canvas; @@ -19,10 +19,6 @@ import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.ui.ActionBar.Theme; -import org.telegram.ui.Components.LayoutHelper; -import org.telegram.ui.Components.NumberPicker; -import org.telegram.ui.Components.RLottieDrawable; -import org.telegram.ui.Components.RLottieImageView; public class SwipeGestureSettingsView extends FrameLayout { @@ -158,12 +154,9 @@ public class SwipeGestureSettingsView extends FrameLayout { AndroidUtilities.updateViewVisibilityAnimated(iconViews[nextIconIndex], true, 0.5f, true); currentIconIndex = nextIconIndex; - AndroidUtilities.runOnUIThread(swapIconRunnable = new Runnable() { - @Override - public void run() { - swapIconRunnable = null; - swapIcons(); - } + AndroidUtilities.runOnUIThread(swapIconRunnable = () -> { + swapIconRunnable = null; + swapIcons(); }, 150); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/TextSelectionHint.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/TextSelectionHint.java similarity index 95% rename from TMessagesProj/src/main/java/org/telegram/ui/TextSelectionHint.java rename to TMessagesProj/src/main/java/org/telegram/ui/Components/TextSelectionHint.java index aa89b0abb..0986a7c78 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/TextSelectionHint.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/TextSelectionHint.java @@ -1,4 +1,4 @@ -package org.telegram.ui; +package org.telegram.ui.Components; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -21,12 +21,11 @@ import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.Theme; -import org.telegram.ui.Components.CubicBezierInterpolator; import java.util.regex.Matcher; import java.util.regex.Pattern; -class TextSelectionHint extends View { +public class TextSelectionHint extends View { StaticLayout textLayout; TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); @@ -35,6 +34,7 @@ class TextSelectionHint extends View { int padding = AndroidUtilities.dp(24); private Interpolator interpolator = new OvershootInterpolator(); + private final Theme.ResourcesProvider resourcesProvider; float enterValue; int start; @@ -53,23 +53,19 @@ class TextSelectionHint extends View { float prepareProgress; Animator a; - Runnable dismissTunnable = new Runnable() { - @Override - public void run() { - hideInternal(); - } - }; + Runnable dismissTunnable = this::hideInternal; private boolean showOnMeasure; - public TextSelectionHint(Context context) { + public TextSelectionHint(Context context, Theme.ResourcesProvider resourcesProvider) { super(context); - int textColor = Theme.getColor(Theme.key_undo_infoColor); + this.resourcesProvider = resourcesProvider; + int textColor = getThemedColor(Theme.key_undo_infoColor); int alpha = Color.alpha(textColor); textPaint.setTextSize(AndroidUtilities.dp(15)); textPaint.setColor(textColor); selectionPaint.setColor(textColor); selectionPaint.setAlpha((int) (alpha * 0.14)); - setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_undo_background))); + setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(6), getThemedColor(Theme.key_undo_background))); } @@ -366,4 +362,9 @@ class TextSelectionHint extends View { public float getPrepareProgress() { return prepareProgress; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ThemePreviewDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ThemePreviewDrawable.java index d45f61cd5..dfe165374 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ThemePreviewDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ThemePreviewDrawable.java @@ -94,25 +94,28 @@ public class ThemePreviewDrawable extends BitmapDrawable { boolean hasBackground = false; if (backgroundColor != null) { - Drawable wallpaperDrawable; + Drawable wallpaperDrawable = null; + MotionBackgroundDrawable motionBackgroundDrawable = null; int patternColor; if (gradientToColor1 == null) { wallpaperDrawable = new ColorDrawable(backgroundColor); patternColor = AndroidUtilities.getPatternColor(backgroundColor); } else { if (gradientToColor2 != 0) { - wallpaperDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, true); + motionBackgroundDrawable = new MotionBackgroundDrawable(backgroundColor, gradientToColor1, gradientToColor2, gradientToColor3, true); } else { final int[] gradientColors = {backgroundColor, gradientToColor1}; wallpaperDrawable = BackgroundGradientDrawable.createDitheredGradientBitmapDrawable(gradientRotation, gradientColors, bitmap.getWidth(), bitmap.getHeight() - 120); } patternColor = AndroidUtilities.getPatternColor(AndroidUtilities.getAverageColor(backgroundColor, gradientToColor1)); } - wallpaperDrawable.setBounds(0, 120, bitmap.getWidth(), bitmap.getHeight() - 120); - wallpaperDrawable.draw(canvas); + if (wallpaperDrawable != null) { + wallpaperDrawable.setBounds(0, 120, bitmap.getWidth(), bitmap.getHeight() - 120); + wallpaperDrawable.draw(canvas); + } + Bitmap patternBitmap = null; if (pattern != null) { - Bitmap patternBitmap; if ("application/x-tgwallpattern".equals(themeDocument.mime_type)) { patternBitmap = SvgHelper.getBitmap(pattern, 560, 678, false); } else { @@ -146,24 +149,35 @@ public class ThemePreviewDrawable extends BitmapDrawable { patternBitmap = BitmapFactory.decodeFile(pattern.getAbsolutePath(), opts); } if (patternBitmap != null) { - Paint backgroundPaint = new Paint(Paint.FILTER_BITMAP_FLAG); - if (themeDocument.accent.patternIntensity >= 0) { - backgroundPaint.setColorFilter(new PorterDuffColorFilter(patternColor, PorterDuff.Mode.SRC_IN)); + if (motionBackgroundDrawable != null) { + motionBackgroundDrawable.setPatternBitmap((int) (themeDocument.accent.patternIntensity * 100), patternBitmap); + motionBackgroundDrawable.setBounds(0, 120, bitmap.getWidth(), bitmap.getHeight() - 120); + motionBackgroundDrawable.draw(canvas); + } else { + Paint backgroundPaint = new Paint(Paint.FILTER_BITMAP_FLAG); + if (themeDocument.accent.patternIntensity >= 0) { + backgroundPaint.setColorFilter(new PorterDuffColorFilter(patternColor, PorterDuff.Mode.SRC_IN)); + } + backgroundPaint.setAlpha(255); + float scale = Math.max(560.0f / patternBitmap.getWidth(), 678.0f / patternBitmap.getHeight()); + int w = (int) (patternBitmap.getWidth() * scale); + int h = (int) (patternBitmap.getHeight() * scale); + int x = (560 - w) / 2; + int y = (678 - h) / 2; + canvas.save(); + canvas.translate(x, y); + canvas.scale(scale, scale); + canvas.drawBitmap(patternBitmap, 0, 0, backgroundPaint); + canvas.restore(); } - backgroundPaint.setAlpha((int) (255 * Math.abs(themeDocument.accent.patternIntensity))); - float scale = Math.max(560.0f / patternBitmap.getWidth(), 678.0f / patternBitmap.getHeight()); - int w = (int) (patternBitmap.getWidth() * scale); - int h = (int) (patternBitmap.getHeight() * scale); - int x = (560 - w) / 2; - int y = (678 - h) / 2; - canvas.save(); - canvas.translate(x, y); - canvas.scale(scale, scale); - canvas.drawBitmap(patternBitmap, 0, 0, backgroundPaint); - canvas.restore(); } } + if (patternBitmap == null && motionBackgroundDrawable != null) { + motionBackgroundDrawable.setBounds(0, 120, bitmap.getWidth(), bitmap.getHeight() - 120); + motionBackgroundDrawable.draw(canvas); + } + hasBackground = true; } if (!hasBackground) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersAlert.java index 053f1127f..024b40bd3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersAlert.java @@ -35,8 +35,8 @@ public class TrendingStickersAlert extends BottomSheet { private int scrollOffsetY; - public TrendingStickersAlert(@NonNull Context context, BaseFragment parentFragment, TrendingStickersLayout trendingStickersLayout) { - super(context, true); + public TrendingStickersAlert(@NonNull Context context, BaseFragment parentFragment, TrendingStickersLayout trendingStickersLayout, Theme.ResourcesProvider resourcesProvider) { + super(context, true, resourcesProvider); alertContainerView = new AlertContainerView(context); alertContainerView.addView(trendingStickersLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); @@ -230,7 +230,7 @@ public class TrendingStickersAlert extends BottomSheet { // mutable top corners if (fraction > 0f && fraction < 1f) { final float radius = AndroidUtilities.dp(12) * fraction; - shapeDrawable.setColor(Theme.getColor(Theme.key_dialogBackground)); + shapeDrawable.setColor(getThemedColor(Theme.key_dialogBackground)); radii[0] = radii[1] = radii[2] = radii[3] = radius; shapeDrawable.setCornerRadii(radii); shapeDrawable.setBounds(backgroundPaddingLeft, scrollOffsetY + offset, getWidth() - backgroundPaddingLeft, scrollOffsetY + offset + AndroidUtilities.dp(24)); @@ -254,7 +254,7 @@ public class TrendingStickersAlert extends BottomSheet { final int h = AndroidUtilities.dp(4); final int offset = (int) (h * 2f * (1f - fraction)); shapeDrawable.setCornerRadius(AndroidUtilities.dp(2)); - final int sheetScrollUpColor = Theme.getColor(Theme.key_sheet_scrollUp); + final int sheetScrollUpColor = getThemedColor(Theme.key_sheet_scrollUp); shapeDrawable.setColor(ColorUtils.setAlphaComponent(sheetScrollUpColor, (int) (Color.alpha(sheetScrollUpColor) * fraction))); shapeDrawable.setBounds((getWidth() - w) / 2, scrollOffsetY + AndroidUtilities.dp(10) + offset, (getWidth() + w) / 2, scrollOffsetY + AndroidUtilities.dp(10) + offset + h); shapeDrawable.draw(canvas); @@ -264,7 +264,7 @@ public class TrendingStickersAlert extends BottomSheet { // status bar setStatusBarVisible(fraction == 0f && Build.VERSION.SDK_INT >= 21 && !isDismissed(), true); if (statusBarAlpha > 0f) { - final int color = Theme.getColor(Theme.key_dialogBackground); + final int color = getThemedColor(Theme.key_dialogBackground); paint.setColor(Color.argb((int) (0xff * statusBarAlpha), (int) (Color.red(color) * 0.8f), (int) (Color.green(color) * 0.8f), (int) (Color.blue(color) * 0.8f))); canvas.drawRect(backgroundPaddingLeft, 0, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, paint); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersLayout.java index 0c8aac490..fd8cd6f08 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/TrendingStickersLayout.java @@ -111,23 +111,25 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC private boolean ignoreLayout; private boolean wasLayout; private boolean loaded; - private int hash; + private long hash; ValueAnimator glueToTopAnimator; private boolean gluedToTop; private boolean scrollFromAnimator; private TLRPC.StickerSetCovered scrollToSet; + private final Theme.ResourcesProvider resourcesProvider; public TrendingStickersLayout(@NonNull Context context, Delegate delegate) { - this(context, delegate, new TLRPC.StickerSetCovered[10], new LongSparseArray<>(), new LongSparseArray<>(), null); + this(context, delegate, new TLRPC.StickerSetCovered[10], new LongSparseArray<>(), new LongSparseArray<>(), null, null); } - public TrendingStickersLayout(@NonNull Context context, Delegate delegate, TLRPC.StickerSetCovered[] primaryInstallingStickerSets, LongSparseArray installingStickerSets, LongSparseArray removingStickerSets, TLRPC.StickerSetCovered scrollToSet) { + public TrendingStickersLayout(@NonNull Context context, Delegate delegate, TLRPC.StickerSetCovered[] primaryInstallingStickerSets, LongSparseArray installingStickerSets, LongSparseArray removingStickerSets, TLRPC.StickerSetCovered scrollToSet, Theme.ResourcesProvider resourcesProvider) { super(context); this.delegate = delegate; this.primaryInstallingStickerSets = primaryInstallingStickerSets; this.installingStickerSets = installingStickerSets; this.removingStickerSets = removingStickerSets; this.scrollToSet = scrollToSet; + this.resourcesProvider = resourcesProvider; this.adapter = new TrendingStickersAdapter(context); final StickersSearchAdapter.Delegate searchAdapterDelegate = new StickersSearchAdapter.Delegate() { @@ -181,12 +183,12 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC delegate.setLastSearchKeyboardLanguage(language); } }; - searchAdapter = new StickersSearchAdapter(context, searchAdapterDelegate, primaryInstallingStickerSets, installingStickerSets, removingStickerSets); + searchAdapter = new StickersSearchAdapter(context, searchAdapterDelegate, primaryInstallingStickerSets, installingStickerSets, removingStickerSets, resourcesProvider); searchLayout = new FrameLayout(context); - searchLayout.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground)); + searchLayout.setBackgroundColor(getThemedColor(Theme.key_dialogBackground)); - searchView = new SearchField(context, true) { + searchView = new SearchField(context, true, resourcesProvider) { @Override public void onTextChange(String text) { searchAdapter.search(text); @@ -330,7 +332,7 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 0)); shadowView = new View(context); - shadowView.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine)); + shadowView.setBackgroundColor(getThemedColor(Theme.key_dialogShadowLine)); shadowView.setAlpha(0.0f); final FrameLayout.LayoutParams shadowViewParams = new FrameLayout.LayoutParams(LayoutHelper.MATCH_PARENT, AndroidUtilities.getShadowHeight()); shadowViewParams.topMargin = AndroidUtilities.dp(58); @@ -458,7 +460,7 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC } else { stickersAlertDelegate = null; } - final StickersAlert stickersAlert = new StickersAlert(getContext(), parentFragment, inputStickerSet, null, stickersAlertDelegate); + final StickersAlert stickersAlert = new StickersAlert(getContext(), parentFragment, inputStickerSet, null, stickersAlertDelegate, resourcesProvider); stickersAlert.setShowTooltipWhenToggle(false); stickersAlert.setInstallDelegate(new StickersAlert.StickersAlertInstallDelegate() { @Override @@ -702,7 +704,7 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC view = new EmptyCell(context); break; case 2: - view = new FeaturedStickerSetInfoCell(context, 17, true); + view = new FeaturedStickerSetInfoCell(context, 17, true, true, resourcesProvider); ((FeaturedStickerSetInfoCell) view).setAddOnClickListener(v -> { final FeaturedStickerSetInfoCell cell = (FeaturedStickerSetInfoCell) v.getParent(); TLRPC.StickerSetCovered pack = cell.getStickerSet(); @@ -721,10 +723,10 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC view = new View(context); break; case 4: - view = new GraySectionCell(context); + view = new GraySectionCell(context, resourcesProvider); break; case 5: - final FeaturedStickerSetCell2 stickerSetCell = new FeaturedStickerSetCell2(context); + final FeaturedStickerSetCell2 stickerSetCell = new FeaturedStickerSetCell2(context, resourcesProvider); stickerSetCell.setAddOnClickListener(v -> { final FeaturedStickerSetCell2 cell = (FeaturedStickerSetCell2) v.getParent(); TLRPC.StickerSetCovered pack = cell.getStickerSet(); @@ -998,4 +1000,9 @@ public class TrendingStickersLayout extends FrameLayout implements NotificationC GraySectionCell.createThemeDescriptions(descriptions, listView); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java index d2177ffd3..5f416711d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/UndoView.java @@ -40,6 +40,7 @@ import androidx.annotation.Keep; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; @@ -174,6 +175,7 @@ public class UndoView extends FrameLayout { private CharSequence infoText; private int hideAnimationType = 1; Drawable backgroundDrawable; + private final Theme.ResourcesProvider resourcesProvider; public class LinkMovementMethodMy extends LinkMovementMethod { @Override @@ -205,29 +207,30 @@ public class UndoView extends FrameLayout { } public UndoView(Context context) { - this(context, null, false); + this(context, null, false, null); } public UndoView(Context context, BaseFragment parent) { - this(context, parent, false); + this(context, parent, false, null); } - public UndoView(Context context, BaseFragment parent, boolean top) { + public UndoView(Context context, BaseFragment parent, boolean top, Theme.ResourcesProvider resourcesProvider) { super(context); + this.resourcesProvider = resourcesProvider; parentFragment = parent; fromTop = top; infoTextView = new TextView(context); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); - infoTextView.setTextColor(Theme.getColor(Theme.key_undo_infoColor)); - infoTextView.setLinkTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + infoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); + infoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); infoTextView.setMovementMethod(new LinkMovementMethodMy()); addView(infoTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 45, 13, 0, 0)); subinfoTextView = new TextView(context); subinfoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); - subinfoTextView.setTextColor(Theme.getColor(Theme.key_undo_infoColor)); - subinfoTextView.setLinkTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + subinfoTextView.setTextColor(getThemedColor(Theme.key_undo_infoColor)); + subinfoTextView.setLinkTextColor(getThemedColor(Theme.key_undo_cancelColor)); subinfoTextView.setHighlightColor(0); subinfoTextView.setSingleLine(true); subinfoTextView.setEllipsize(TextUtils.TruncateAt.END); @@ -236,21 +239,21 @@ public class UndoView extends FrameLayout { leftImageView = new RLottieImageView(context); leftImageView.setScaleType(ImageView.ScaleType.CENTER); - leftImageView.setLayerColor("info1.**", Theme.getColor(Theme.key_undo_background) | 0xff000000); - leftImageView.setLayerColor("info2.**", Theme.getColor(Theme.key_undo_background) | 0xff000000); - leftImageView.setLayerColor("luc12.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc11.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc10.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc9.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc8.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc7.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc6.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc5.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc4.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc3.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc2.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("luc1.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Oval.**", Theme.getColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("info1.**", getThemedColor(Theme.key_undo_background) | 0xff000000); + leftImageView.setLayerColor("info2.**", getThemedColor(Theme.key_undo_background) | 0xff000000); + leftImageView.setLayerColor("luc12.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc11.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc10.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc9.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc8.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc7.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc6.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc5.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc4.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc3.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc2.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("luc1.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Oval.**", getThemedColor(Theme.key_undo_infoColor)); addView(leftImageView, LayoutHelper.createFrame(54, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 3, 0, 0, 0)); avatarImageView = new BackupImageView(context); @@ -269,13 +272,13 @@ public class UndoView extends FrameLayout { undoImageView = new ImageView(context); undoImageView.setImageResource(R.drawable.chats_undo); - undoImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); + undoImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_undo_cancelColor), PorterDuff.Mode.MULTIPLY)); undoButton.addView(undoImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT)); undoTextView = new TextView(context); undoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); undoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - undoTextView.setTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoTextView.setText(LocaleController.getString("Undo", R.string.Undo)); undoButton.addView(undoTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.LEFT, 6, 0, 0, 0)); @@ -285,15 +288,15 @@ public class UndoView extends FrameLayout { progressPaint.setStyle(Paint.Style.STROKE); progressPaint.setStrokeWidth(AndroidUtilities.dp(2)); progressPaint.setStrokeCap(Paint.Cap.ROUND); - progressPaint.setColor(Theme.getColor(Theme.key_undo_infoColor)); + progressPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(AndroidUtilities.dp(12)); textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - textPaint.setColor(Theme.getColor(Theme.key_undo_infoColor)); + textPaint.setColor(getThemedColor(Theme.key_undo_infoColor)); setWillNotDraw(false); - backgroundDrawable = Theme.createRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_undo_background)); + backgroundDrawable = Theme.createRoundRectDrawable(AndroidUtilities.dp(6), getThemedColor(Theme.key_undo_background)); setOnTouchListener((v, event) -> true); @@ -714,14 +717,14 @@ public class UndoView extends FrameLayout { subInfoText = null; icon = R.raw.contact_check; } else if (action == ACTION_PROFILE_PHOTO_CHANGED) { - if (did > 0) { + if (DialogObject.isUserDialog(did)) { if (infoObject == null) { infoText = LocaleController.getString("MainProfilePhotoSetHint", R.string.MainProfilePhotoSetHint); } else { infoText = LocaleController.getString("MainProfileVideoSetHint", R.string.MainProfileVideoSetHint); } } else { - TLRPC.Chat chat = MessagesController.getInstance(UserConfig.selectedAccount).getChat((int) -did); + TLRPC.Chat chat = MessagesController.getInstance(UserConfig.selectedAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { if (infoObject == null) { infoText = LocaleController.getString("MainChannelProfilePhotoSetHint", R.string.MainChannelProfilePhotoSetHint); @@ -768,20 +771,20 @@ public class UndoView extends FrameLayout { } else if (action == ACTION_ADDED_TO_FOLDER || action == ACTION_REMOVED_FROM_FOLDER) { MessagesController.DialogFilter filter = (MessagesController.DialogFilter) infoObject2; if (did != 0) { - int lowerId = (int) did; - if (lowerId == 0) { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat((int) (did >> 32)); - lowerId = encryptedChat.user_id; + long dialogId = did; + if (DialogObject.isEncryptedDialog(did)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); + dialogId = encryptedChat.user_id; } - if (lowerId > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserAddedToExisting", R.string.FilterUserAddedToExisting, UserObject.getFirstName(user), filter.name)); } else { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterUserRemovedFrom", R.string.FilterUserRemovedFrom, UserObject.getFirstName(user), filter.name)); } } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (action == ACTION_ADDED_TO_FOLDER) { infoText = AndroidUtilities.replaceTags(LocaleController.formatString("FilterChatAddedToExisting", R.string.FilterChatAddedToExisting, chat.title, filter.name)); } else { @@ -979,12 +982,11 @@ public class UndoView extends FrameLayout { if (did == UserConfig.getInstance(currentAccount).clientUserId) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("InvLinkToSavedMessages", R.string.InvLinkToSavedMessages))); } else { - int lowerId = (int) did; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToGroup", R.string.InvLinkToGroup, chat.title))); } else { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lowerId); + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("InvLinkToUser", R.string.InvLinkToUser, UserObject.getFirstName(user)))); } } @@ -1005,16 +1007,15 @@ public class UndoView extends FrameLayout { } leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { - int lowerId = (int) did; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToGroup", R.string.FwdMessageToGroup, chat.title))); } else { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessagesToGroup", R.string.FwdMessagesToGroup, chat.title))); } } else { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lowerId); + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); if (count == 1) { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("FwdMessageToUser", R.string.FwdMessageToUser, UserObject.getFirstName(user)))); } else { @@ -1042,12 +1043,11 @@ public class UndoView extends FrameLayout { infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.getString("BackgroundToSavedMessages", R.string.BackgroundToSavedMessages))); leftImageView.setAnimation(R.raw.saved_messages, 30, 30); } else { - int lowerId = (int) did; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToGroup", R.string.BackgroundToGroup, chat.title))); } else { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lowerId); + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); infoTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("BackgroundToUser", R.string.BackgroundToUser, UserObject.getFirstName(user)))); } leftImageView.setAnimation(R.raw.forward, 30, 30); @@ -1060,7 +1060,7 @@ public class UndoView extends FrameLayout { timeLeft = 3000; } subinfoTextView.setVisibility(GONE); - undoTextView.setTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(GONE); layoutParams.leftMargin = AndroidUtilities.dp(58); @@ -1084,10 +1084,10 @@ public class UndoView extends FrameLayout { infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); leftImageView.clearLayerColors(); - leftImageView.setLayerColor("BODY.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Wibe Big.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Wibe Big 3.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Wibe Small.**", Theme.getColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("BODY.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Wibe Big.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Wibe Big 3.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Wibe Small.**", getThemedColor(Theme.key_undo_infoColor)); infoTextView.setText(LocaleController.getString("ProximityAlertSet", R.string.ProximityAlertSet)); leftImageView.setAnimation(R.raw.ic_unmute, 28, 28); @@ -1107,18 +1107,18 @@ public class UndoView extends FrameLayout { infoTextView.setTypeface(Typeface.DEFAULT); infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15); leftImageView.clearLayerColors(); - leftImageView.setLayerColor("Body Main.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Body Top.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Line.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Curve Big.**", Theme.getColor(Theme.key_undo_infoColor)); - leftImageView.setLayerColor("Curve Small.**", Theme.getColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Body Main.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Body Top.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Line.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Curve Big.**", getThemedColor(Theme.key_undo_infoColor)); + leftImageView.setLayerColor("Curve Small.**", getThemedColor(Theme.key_undo_infoColor)); layoutParams.topMargin = AndroidUtilities.dp(14); infoTextView.setText(LocaleController.getString("ProximityAlertCancelled", R.string.ProximityAlertCancelled)); leftImageView.setAnimation(R.raw.ic_mute, 28, 28); subinfoTextView.setVisibility(GONE); - undoTextView.setTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoButton.setVisibility(VISIBLE); } @@ -1139,7 +1139,7 @@ public class UndoView extends FrameLayout { infoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); infoTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); - undoTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText2)); + undoTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteRedText2)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); leftImageView.setVisibility(VISIBLE); @@ -1213,7 +1213,7 @@ public class UndoView extends FrameLayout { if (currentAction == ACTION_DICE_INFO) { margin = (int) Math.ceil(undoTextView.getPaint().measureText(undoTextView.getText().toString())) + AndroidUtilities.dp(26); undoTextView.setVisibility(VISIBLE); - undoTextView.setTextColor(Theme.getColor(Theme.key_undo_cancelColor)); + undoTextView.setTextColor(getThemedColor(Theme.key_undo_cancelColor)); undoImageView.setVisibility(GONE); undoButton.setVisibility(VISIBLE); } else { @@ -1315,9 +1315,8 @@ public class UndoView extends FrameLayout { } else if (currentAction == ACTION_DELETE_FEW) { infoTextView.setText(LocaleController.getString("ChatsDeletedUndo", R.string.ChatsDeletedUndo)); } else { - int lowerId = (int) did; - if (lowerId < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lowerId); + if (DialogObject.isChatDialog(did)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); if (ChatObject.isChannel(chat) && !chat.megagroup) { infoTextView.setText(LocaleController.getString("ChannelDeletedUndo", R.string.ChannelDeletedUndo)); } else { @@ -1524,4 +1523,9 @@ public class UndoView extends FrameLayout { public Drawable getBackground() { return backgroundDrawable; } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/UsersAlertBase.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/UsersAlertBase.java index b3bdff4cb..288663e4a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/UsersAlertBase.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/UsersAlertBase.java @@ -80,8 +80,8 @@ public class UsersAlertBase extends BottomSheet { protected final FillLastLinearLayoutManager layoutManager; - public UsersAlertBase(Context context, boolean needFocus, int account) { - super(context, needFocus); + public UsersAlertBase(Context context, boolean needFocus, int account, Theme.ResourcesProvider resourcesProvider) { + super(context, needFocus, resourcesProvider); updateColorKeys(); setDimBehindAlpha(75); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallGridCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallGridCell.java index 199b29c3b..8ae069680 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallGridCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallGridCell.java @@ -55,7 +55,7 @@ public class GroupCallGridCell extends FrameLayout { } } - public void setData(AccountInstance accountInstance, ChatObject.VideoParticipant participant, ChatObject.Call call, int selfPeerId) { + public void setData(AccountInstance accountInstance, ChatObject.VideoParticipant participant, ChatObject.Call call, long selfPeerId) { this.participant = participant; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallMiniTextureView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallMiniTextureView.java index b6745d826..4dad159a4 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallMiniTextureView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallMiniTextureView.java @@ -39,6 +39,7 @@ import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; @@ -1022,11 +1023,11 @@ public class GroupCallMiniTextureView extends FrameLayout implements GroupCallSt if (!ChatObject.Call.videoIsActive(participant.participant, participant.presentation, call) || !call.canStreamVideo && participant != call.videoNotAvailableParticipant) { noVideoStubLayout.avatarImageReceiver.setCurrentAccount(currentAccount); - int peerId = MessageObject.getPeerId(participant.participant.peer); + long peerId = MessageObject.getPeerId(participant.participant.peer); ImageLocation imageLocation; ImageLocation thumbLocation; Object parentObject; - if (peerId > 0) { + if (DialogObject.isUserDialog(peerId)) { TLRPC.User currentUser = AccountInstance.getInstance(currentAccount).getMessagesController().getUser(peerId); noVideoStubLayout.avatarDrawable.setInfo(currentUser); imageLocation = ImageLocation.getForUser(currentUser, ImageLocation.TYPE_BIG); @@ -1162,7 +1163,7 @@ public class GroupCallMiniTextureView extends FrameLayout implements GroupCallSt textureView.setThumb(thumb); if (thumb == null) { - int peerId = MessageObject.getPeerId(participant.participant.peer); + long peerId = MessageObject.getPeerId(participant.participant.peer); if (participant.participant.self && participant.presentation) { imageReceiver.setImageBitmap(new MotionBackgroundDrawable(0xff212E3A, 0xff2B5B4D, 0xff245863, 0xff274558, true)); @@ -1192,8 +1193,8 @@ public class GroupCallMiniTextureView extends FrameLayout implements GroupCallSt String name = null; - int peerId = MessageObject.getPeerId(participant.participant.peer); - if (peerId > 0) { + long peerId = MessageObject.getPeerId(participant.participant.peer); + if (DialogObject.isUserDialog(peerId)) { TLRPC.User currentUser = AccountInstance.getInstance(currentAccount).getMessagesController().getUser(peerId); name = UserObject.getUserName(currentUser); } else { @@ -1706,8 +1707,8 @@ public class GroupCallMiniTextureView extends FrameLayout implements GroupCallSt } public String getName() { - int peerId = MessageObject.getPeerId(participant.participant.peer); - if (peerId > 0) { + long peerId = MessageObject.getPeerId(participant.participant.peer); + if (DialogObject.isUserDialog(peerId)) { TLRPC.User currentUser = AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController().getUser(peerId); return UserObject.getUserName(currentUser); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallRenderersContainer.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallRenderersContainer.java index a36d2da13..fd88eead9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallRenderersContainer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/GroupCallRenderersContainer.java @@ -14,7 +14,6 @@ import android.os.Build; import android.os.SystemClock; import android.text.SpannableStringBuilder; import android.text.TextUtils; -import android.util.SparseIntArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -37,6 +36,7 @@ import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; import org.telegram.messenger.UserObject; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; @@ -62,7 +62,7 @@ public class GroupCallRenderersContainer extends FrameLayout { private final int touchSlop; public boolean inFullscreenMode; public float progressToFullscreenMode; - public int fullscreenPeerId; + public long fullscreenPeerId; public ChatObject.VideoParticipant fullscreenParticipant; public boolean hasPinnedVideo; public long lastUpdateTime; @@ -71,7 +71,7 @@ public class GroupCallRenderersContainer extends FrameLayout { ValueAnimator fullscreenAnimator; public boolean inLayout; - private SparseIntArray attachedPeerIds = new SparseIntArray(); + private LongSparseIntArray attachedPeerIds = new LongSparseIntArray(); int animationIndex; @@ -85,7 +85,7 @@ public class GroupCallRenderersContainer extends FrameLayout { private final AvatarsImageView speakingMembersAvatars; private final TextView speakingMembersText; private boolean showSpeakingMembersToast; - private int speakingToastPeerId; + private long speakingToastPeerId; private float showSpeakingMembersToastProgress; private float speakingMembersToastChangeProgress = 1f; @@ -586,7 +586,7 @@ public class GroupCallRenderersContainer extends FrameLayout { // return; // } // } - int peerId = videoParticipant == null ? 0 : MessageObject.getPeerId(videoParticipant.participant.peer); + long peerId = videoParticipant == null ? 0 : MessageObject.getPeerId(videoParticipant.participant.peer); if (fullscreenTextureView != null) { fullscreenTextureView.runDelayedAnimations(); } @@ -1306,12 +1306,12 @@ public class GroupCallRenderersContainer extends FrameLayout { lastUpdateTooltipTime = System.currentTimeMillis(); SpannableStringBuilder spannableStringBuilder = null; for (int i = 0; i < call.currentSpeakingPeers.size(); i++) { - int key = call.currentSpeakingPeers.keyAt(i); + long key = call.currentSpeakingPeers.keyAt(i); TLRPC.TL_groupCallParticipant participant = call.currentSpeakingPeers.get(key); if (participant.self || participant.muted_by_you || MessageObject.getPeerId(fullscreenParticipant.participant.peer) == MessageObject.getPeerId(participant.peer)) { continue; } - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); long diff = SystemClock.uptimeMillis() - participant.lastSpeakTime; boolean newSpeaking = diff < 500; if (newSpeaking) { @@ -1419,19 +1419,19 @@ public class GroupCallRenderersContainer extends FrameLayout { } public boolean isVisible(TLRPC.TL_groupCallParticipant participant) { - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); return attachedPeerIds.get(peerId) > 0; } public void attach(GroupCallMiniTextureView view) { attachedRenderers.add(view); - int peerId = MessageObject.getPeerId(view.participant.participant.peer); + long peerId = MessageObject.getPeerId(view.participant.participant.peer); attachedPeerIds.put(peerId, attachedPeerIds.get(peerId, 0) + 1); } public void detach(GroupCallMiniTextureView view) { attachedRenderers.remove(view); - int peerId = MessageObject.getPeerId(view.participant.participant.peer); + long peerId = MessageObject.getPeerId(view.participant.participant.peer); attachedPeerIds.put(peerId, attachedPeerIds.get(peerId, 0) - 1); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/VoIPHelper.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/VoIPHelper.java index 24e6d5312..3f57493cf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/VoIPHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/voip/VoIPHelper.java @@ -161,8 +161,8 @@ public class VoIPHelper { } VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService != null) { - int newId = user != null ? user.id : -chat.id; - int callerId = VoIPService.getSharedInstance().getCallerId(); + long newId = user != null ? user.id : -chat.id; + long callerId = VoIPService.getSharedInstance().getCallerId(); if (callerId != newId || voIPService.getAccount() != accountInstance.getCurrentAccount()) { String newName; String oldName; @@ -235,7 +235,7 @@ public class VoIPHelper { if (checkJoiner && chat != null && !createCall) { TLRPC.ChatFull chatFull = accountInstance.getMessagesController().getChatFull(chat.id); if (chatFull != null && chatFull.groupcall_default_join_as != null) { - int did = MessageObject.getPeerId(chatFull.groupcall_default_join_as); + long did = MessageObject.getPeerId(chatFull.groupcall_default_join_as); TLRPC.InputPeer inputPeer = accountInstance.getMessagesController().getInputPeer(did); JoinCallAlert.checkFewUsers(activity, -chat.id, accountInstance, param -> { if (!param && hash != null) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java index 4536c96e5..78a597e7d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactAddActivity.java @@ -57,7 +57,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent private TextView infoTextView; private CheckBoxCell checkBoxCell; - private int user_id; + private long user_id; private boolean addContact; private boolean needAddException; private String phone; @@ -77,7 +77,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent @Override public boolean onFragmentCreate() { getNotificationCenter().addObserver(this, NotificationCenter.updateInterfaces); - user_id = getArguments().getInt("user_id", 0); + user_id = getArguments().getLong("user_id", 0); phone = getArguments().getString("phone"); addContact = getArguments().getBoolean("addContact", false); needAddException = MessagesController.getNotificationsSettings(currentAccount).getBoolean("dialog_bar_exception" + user_id, false); @@ -114,7 +114,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); preferences.edit().putInt("dialog_bar_vis3" + user_id, 3).commit(); getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME); - getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, (long) user_id); + getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, user_id); finishFragment(); if (delegate != null) { delegate.didAddToContacts(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java index ba1c498d7..d809412d2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContactsActivity.java @@ -39,7 +39,6 @@ import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; -import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.View; @@ -52,8 +51,8 @@ import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; -import android.widget.Toast; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -64,7 +63,6 @@ import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; @@ -83,7 +81,6 @@ import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Adapters.ContactsAdapter; -import org.telegram.ui.Adapters.DialogsAdapter; import org.telegram.ui.Adapters.SearchAdapter; import org.telegram.ui.Cells.GraySectionCell; import org.telegram.ui.Cells.LetterSectionCell; @@ -136,10 +133,10 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter private boolean needForwardCount = true; private boolean needFinishFragment = true; private boolean resetDelegate = true; - private int channelId; - private int chatId; + private long channelId; + private long chatId; private String selectAlertString = null; - private SparseArray ignoreUsers; + private LongSparseArray ignoreUsers; private boolean allowUsernameSearch = true; private ContactsActivityDelegate delegate; private String initialSearchString; @@ -184,9 +181,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter needForwardCount = arguments.getBoolean("needForwardCount", true); allowBots = arguments.getBoolean("allowBots", true); allowSelf = arguments.getBoolean("allowSelf", true); - channelId = arguments.getInt("channelId", 0); + channelId = arguments.getLong("channelId", 0); needFinishFragment = arguments.getBoolean("needFinishFragment", true); - chatId = arguments.getInt("chat_id", 0); + chatId = arguments.getLong("chat_id", 0); disableSections = arguments.getBoolean("disableSections", false); resetDelegate = arguments.getBoolean("resetDelegate", false); } else { @@ -335,10 +332,10 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter }; int inviteViaLink; if (chatId != 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId); + TLRPC.Chat chat = getMessagesController().getChat(chatId); inviteViaLink = ChatObject.canUserDoAdminAction(chat, ChatObject.ACTION_INVITE) ? 1 : 0; } else if (channelId != 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(channelId); + TLRPC.Chat chat = getMessagesController().getChat(channelId); inviteViaLink = ChatObject.canUserDoAdminAction(chat, ChatObject.ACTION_INVITE) && TextUtils.isEmpty(chat.username) ? 2 : 0; } else { inviteViaLink = 0; @@ -421,7 +418,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter if (searchListViewAdapter.isGlobalSearch(position)) { ArrayList users = new ArrayList<>(); users.add(user); - MessagesController.getInstance(currentAccount).putUsers(users, false); + getMessagesController().putUsers(users, false); MessagesStorage.getInstance(currentAccount).putUsersAndChats(users, null, false, true); } if (returnAsResult) { @@ -438,8 +435,8 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter SecretChatHelper.getInstance(currentAccount).startSecretChat(getParentActivity(), user); } else { Bundle args = new Bundle(); - args.putInt("user_id", user.id); - if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ContactsActivity.this)) { + args.putLong("user_id", user.id); + if (getMessagesController().checkCanOpenChat(args, ContactsActivity.this)) { presentFragment(new ChatActivity(args), true); } } @@ -534,8 +531,8 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter SecretChatHelper.getInstance(currentAccount).startSecretChat(getParentActivity(), user); } else { Bundle args = new Bundle(); - args.putInt("user_id", user.id); - if (MessagesController.getInstance(currentAccount).checkCanOpenChat(args, ContactsActivity.this)) { + args.putLong("user_id", user.id); + if (getMessagesController().checkCanOpenChat(args, ContactsActivity.this)) { presentFragment(new ChatActivity(args), true); } } @@ -675,7 +672,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter return; } if (channelId != 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(channelId); + TLRPC.Chat chat = getMessagesController().getChat(channelId); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); if (ChatObject.canAddAdmins(chat)) { builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); @@ -962,7 +959,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter this.delegate = delegate; } - public void setIgnoreUsers(SparseArray users) { + public void setIgnoreUsers(LongSparseArray users) { ignoreUsers = users; } @@ -1015,7 +1012,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter if (previousFab.getParent() != null) { previousFabContainer = (View) previousFab.getParent(); } - if (previousFab == null || floatingButtonContainer == null || previousFabContainer == null || previousFab.getVisibility() != View.VISIBLE || Math.abs(previousFabContainer.getTranslationY()) > AndroidUtilities.dp(4) || Math.abs(floatingButtonContainer.getTranslationY()) > AndroidUtilities.dp(4)) { + if (floatingButtonContainer == null || previousFabContainer == null || previousFab.getVisibility() != View.VISIBLE || Math.abs(previousFabContainer.getTranslationY()) > AndroidUtilities.dp(4) || Math.abs(floatingButtonContainer.getTranslationY()) > AndroidUtilities.dp(4)) { return null; } previousFab.setVisibility(View.GONE); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ContentPreviewViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/ContentPreviewViewer.java index 2105fdaec..3e02e7d9f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ContentPreviewViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ContentPreviewViewer.java @@ -55,6 +55,7 @@ import org.telegram.ui.Cells.ContextLinkCell; import org.telegram.ui.Cells.StickerCell; import org.telegram.ui.Cells.StickerEmojiCell; import org.telegram.ui.Components.AlertsCreator; +import org.telegram.ui.Components.EmojiView; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RecyclerListView; @@ -159,7 +160,7 @@ public class ContentPreviewViewer { } if (currentContentType == CONTENT_TYPE_STICKER) { final boolean inFavs = MediaDataController.getInstance(currentAccount).isStickerInFavorites(currentDocument); - BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity); + BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity, true, resourcesProvider); ArrayList items = new ArrayList<>(); final ArrayList actions = new ArrayList<>(); ArrayList icons = new ArrayList<>(); @@ -169,6 +170,11 @@ public class ContentPreviewViewer { icons.add(R.drawable.outline_send); actions.add(0); } + if (!delegate.isInScheduleMode()) { + items.add(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound)); + icons.add(R.drawable.input_notify_off); + actions.add(6); + } if (delegate.canSchedule()) { items.add(LocaleController.getString("Schedule", R.string.Schedule)); icons.add(R.drawable.msg_timer); @@ -206,9 +212,9 @@ public class ContentPreviewViewer { if (parentActivity == null) { return; } - if (actions.get(which) == 0) { + if (actions.get(which) == 0 || actions.get(which) == 6) { if (delegate != null) { - delegate.sendSticker(currentDocument, currentQuery, parentObject, true, 0); + delegate.sendSticker(currentDocument, currentQuery, parentObject, actions.get(which) == 0, 0); } } else if (actions.get(which) == 1) { if (delegate != null) { @@ -238,8 +244,8 @@ public class ContentPreviewViewer { containerView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); if (delegate != null && delegate.needRemove()) { BottomSheet.BottomSheetCell cell = visibleDialog.getItemViews().get(0); - cell.setTextColor(Theme.getColor(Theme.key_dialogTextRed)); - cell.setIconColor(Theme.getColor(Theme.key_dialogRedIcon)); + cell.setTextColor(getThemedColor(Theme.key_dialogTextRed)); + cell.setIconColor(getThemedColor(Theme.key_dialogRedIcon)); } } else if (delegate != null) { animateY = true; @@ -313,7 +319,7 @@ public class ContentPreviewViewer { TLRPC.BotInlineResult result = inlineResult; Object parent = parentObject; ContentPreviewViewerDelegate stickerPreviewViewerDelegate = delegate; - AlertsCreator.createScheduleDatePickerDialog(parentActivity, stickerPreviewViewerDelegate.getDialogId(), (notify, scheduleDate) -> stickerPreviewViewerDelegate.sendGif(document != null ? document : result, parent, notify, scheduleDate)); + AlertsCreator.createScheduleDatePickerDialog(parentActivity, stickerPreviewViewerDelegate.getDialogId(), (notify, scheduleDate) -> stickerPreviewViewerDelegate.sendGif(document != null ? document : result, parent, notify, scheduleDate), resourcesProvider); } }); visibleDialog.setDimBehind(false); @@ -324,7 +330,7 @@ public class ContentPreviewViewer { visibleDialog.show(); containerView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); if (canDelete) { - visibleDialog.setItemColor(items.size() - 1, Theme.getColor(Theme.key_dialogTextRed2), Theme.getColor(Theme.key_dialogRedIcon)); + visibleDialog.setItemColor(items.size() - 1, getThemedColor(Theme.key_dialogTextRed2), getThemedColor(Theme.key_dialogRedIcon)); } } } @@ -337,6 +343,7 @@ public class ContentPreviewViewer { private TLRPC.BotInlineResult inlineResult; private TLRPC.InputStickerSet currentStickerSet; private Object parentObject; + private Theme.ResourcesProvider resourcesProvider; @SuppressLint("StaticFieldLeak") private static volatile ContentPreviewViewer Instance = null; @@ -374,8 +381,9 @@ public class ContentPreviewViewer { } } - public boolean onTouch(MotionEvent event, final RecyclerListView listView, final int height, final Object listener, ContentPreviewViewerDelegate contentPreviewViewerDelegate) { + public boolean onTouch(MotionEvent event, final RecyclerListView listView, final int height, final Object listener, ContentPreviewViewerDelegate contentPreviewViewerDelegate, Theme.ResourcesProvider resourcesProvider) { delegate = contentPreviewViewerDelegate; + this.resourcesProvider = resourcesProvider; if (openPreviewRunnable != null || isVisible()) { if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) { AndroidUtilities.runOnUIThread(() -> { @@ -478,16 +486,16 @@ public class ContentPreviewViewer { clearsInputField = false; if (currentPreviewCell instanceof StickerEmojiCell) { StickerEmojiCell stickerEmojiCell = (StickerEmojiCell) currentPreviewCell; - open(stickerEmojiCell.getSticker(), stickerEmojiCell.getStickerPath(), stickerEmojiCell.getEmoji(), delegate != null ? delegate.getQuery(false) : null, null, contentType, stickerEmojiCell.isRecent(), stickerEmojiCell.getParentObject()); + open(stickerEmojiCell.getSticker(), stickerEmojiCell.getStickerPath(), stickerEmojiCell.getEmoji(), delegate != null ? delegate.getQuery(false) : null, null, contentType, stickerEmojiCell.isRecent(), stickerEmojiCell.getParentObject(), resourcesProvider); stickerEmojiCell.setScaled(true); } else if (currentPreviewCell instanceof StickerCell) { StickerCell stickerCell = (StickerCell) currentPreviewCell; - open(stickerCell.getSticker(), null, null, delegate != null ? delegate.getQuery(false) : null, null, contentType, false, stickerCell.getParentObject()); + open(stickerCell.getSticker(), null, null, delegate != null ? delegate.getQuery(false) : null, null, contentType, false, stickerCell.getParentObject(), resourcesProvider); stickerCell.setScaled(true); clearsInputField = stickerCell.isClearsInputField(); } else if (currentPreviewCell instanceof ContextLinkCell) { ContextLinkCell contextLinkCell = (ContextLinkCell) currentPreviewCell; - open(contextLinkCell.getDocument(), null, null, delegate != null ? delegate.getQuery(true) : null, contextLinkCell.getBotInlineResult(), contentType, false, contextLinkCell.getBotInlineResult() != null ? contextLinkCell.getInlineBot() : contextLinkCell.getParentObject()); + open(contextLinkCell.getDocument(), null, null, delegate != null ? delegate.getQuery(true) : null, contextLinkCell.getBotInlineResult(), contentType, false, contextLinkCell.getBotInlineResult() != null ? contextLinkCell.getInlineBot() : contextLinkCell.getParentObject(), resourcesProvider); if (contentType != CONTENT_TYPE_GIF) { contextLinkCell.setScaled(true); } @@ -528,8 +536,9 @@ public class ContentPreviewViewer { } } - public boolean onInterceptTouchEvent(MotionEvent event, final RecyclerListView listView, final int height, ContentPreviewViewerDelegate contentPreviewViewerDelegate) { + public boolean onInterceptTouchEvent(MotionEvent event, final RecyclerListView listView, final int height, ContentPreviewViewerDelegate contentPreviewViewerDelegate, Theme.ResourcesProvider resourcesProvider) { delegate = contentPreviewViewerDelegate; + this.resourcesProvider = resourcesProvider; if (event.getAction() == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); @@ -591,16 +600,16 @@ public class ContentPreviewViewer { clearsInputField = false; if (currentPreviewCell instanceof StickerEmojiCell) { StickerEmojiCell stickerEmojiCell = (StickerEmojiCell) currentPreviewCell; - open(stickerEmojiCell.getSticker(), stickerEmojiCell.getStickerPath(), stickerEmojiCell.getEmoji(), delegate != null ? delegate.getQuery(false) : null, null, contentTypeFinal, stickerEmojiCell.isRecent(), stickerEmojiCell.getParentObject()); + open(stickerEmojiCell.getSticker(), stickerEmojiCell.getStickerPath(), stickerEmojiCell.getEmoji(), delegate != null ? delegate.getQuery(false) : null, null, contentTypeFinal, stickerEmojiCell.isRecent(), stickerEmojiCell.getParentObject(), resourcesProvider); stickerEmojiCell.setScaled(true); } else if (currentPreviewCell instanceof StickerCell) { StickerCell stickerCell = (StickerCell) currentPreviewCell; - open(stickerCell.getSticker(), null, null, delegate != null ? delegate.getQuery(false) : null, null, contentTypeFinal, false, stickerCell.getParentObject()); + open(stickerCell.getSticker(), null, null, delegate != null ? delegate.getQuery(false) : null, null, contentTypeFinal, false, stickerCell.getParentObject(), resourcesProvider); stickerCell.setScaled(true); clearsInputField = stickerCell.isClearsInputField(); } else if (currentPreviewCell instanceof ContextLinkCell) { ContextLinkCell contextLinkCell = (ContextLinkCell) currentPreviewCell; - open(contextLinkCell.getDocument(), null, null, delegate != null ? delegate.getQuery(true) : null, contextLinkCell.getBotInlineResult(), contentTypeFinal, false, contextLinkCell.getBotInlineResult() != null ? contextLinkCell.getInlineBot() : contextLinkCell.getParentObject()); + open(contextLinkCell.getDocument(), null, null, delegate != null ? delegate.getQuery(true) : null, contextLinkCell.getBotInlineResult(), contentTypeFinal, false, contextLinkCell.getBotInlineResult() != null ? contextLinkCell.getInlineBot() : contextLinkCell.getParentObject(), resourcesProvider); if (contentTypeFinal != CONTENT_TYPE_GIF) { contextLinkCell.setScaled(true); } @@ -670,10 +679,11 @@ public class ContentPreviewViewer { keyboardHeight = height; } - public void open(TLRPC.Document document, SendMessagesHelper.ImportingSticker sticker, String emojiPath, String query, TLRPC.BotInlineResult botInlineResult, int contentType, boolean isRecent, Object parent) { + public void open(TLRPC.Document document, SendMessagesHelper.ImportingSticker sticker, String emojiPath, String query, TLRPC.BotInlineResult botInlineResult, int contentType, boolean isRecent, Object parent, Theme.ResourcesProvider resourcesProvider) { if (parentActivity == null || windowView == null) { return; } + this.resourcesProvider = resourcesProvider; isRecentSticker = isRecent; stickerEmojiLayout = null; if (contentType == CONTENT_TYPE_STICKER) { @@ -773,6 +783,7 @@ public class ContentPreviewViewer { currentQuery = query; inlineResult = botInlineResult; parentObject = parent; + this.resourcesProvider = resourcesProvider; containerView.invalidate(); if (!isVisible) { @@ -943,4 +954,9 @@ public class ContentPreviewViewer { } } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java index 33408725a..71d1cc112 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/CountrySelectActivity.java @@ -39,6 +39,7 @@ import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.Objects; import java.util.Timer; import java.util.TimerTask; @@ -48,7 +49,7 @@ import androidx.recyclerview.widget.RecyclerView; public class CountrySelectActivity extends BaseFragment { public interface CountrySelectActivityDelegate { - void didSelectCountry(String name, String shortName); + void didSelectCountry(Country country); } private RecyclerListView listView; @@ -61,9 +62,16 @@ public class CountrySelectActivity extends BaseFragment { private boolean needPhoneCode; private CountrySelectActivityDelegate delegate; + private ArrayList existingCountries; public CountrySelectActivity(boolean phoneCode) { + this(phoneCode, null); + } + public CountrySelectActivity(boolean phoneCode, ArrayList existingCountries) { super(); + if (existingCountries != null && !existingCountries.isEmpty()) { + this.existingCountries = new ArrayList<>(existingCountries); + } needPhoneCode = phoneCode; } @@ -122,7 +130,7 @@ public class CountrySelectActivity extends BaseFragment { searching = false; searchWas = false; - listViewAdapter = new CountryAdapter(context); + listViewAdapter = new CountryAdapter(context, existingCountries); searchListViewAdapter = new CountrySearchAdapter(context, listViewAdapter.getCountries()); fragmentView = new FrameLayout(context); @@ -161,7 +169,7 @@ public class CountrySelectActivity extends BaseFragment { } finishFragment(); if (country != null && delegate != null) { - delegate.didSelectCountry(country.name, country.shortname); + delegate.didSelectCountry(country); } }); @@ -193,6 +201,19 @@ public class CountrySelectActivity extends BaseFragment { public String name; public String code; public String shortname; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Country that = (Country) o; + return Objects.equals(name, that.name) && Objects.equals(code, that.code); + } + + @Override + public int hashCode() { + return Objects.hash(name, code); + } } public class CountryAdapter extends RecyclerListView.SectionsAdapter { @@ -201,19 +222,12 @@ public class CountrySelectActivity extends BaseFragment { private HashMap> countries = new HashMap<>(); private ArrayList sortedCountries = new ArrayList<>(); - public CountryAdapter(Context context) { + public CountryAdapter(Context context, ArrayList exisitingCountries) { mContext = context; - try { - InputStream stream = ApplicationLoader.applicationContext.getResources().getAssets().open("countries.txt"); - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String line; - while ((line = reader.readLine()) != null) { - String[] args = line.split(";"); - Country c = new Country(); - c.name = args[2]; - c.code = args[0]; - c.shortname = args[1]; + if (exisitingCountries != null) { + for (int i = 0; i < exisitingCountries.size(); i++) { + Country c = exisitingCountries.get(i); String n = c.name.substring(0, 1).toUpperCase(); ArrayList arr = countries.get(n); if (arr == null) { @@ -223,12 +237,32 @@ public class CountrySelectActivity extends BaseFragment { } arr.add(c); } - reader.close(); - stream.close(); - } catch (Exception e) { - FileLog.e(e); + } else { + try { + InputStream stream = ApplicationLoader.applicationContext.getResources().getAssets().open("countries.txt"); + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + String line; + while ((line = reader.readLine()) != null) { + String[] args = line.split(";"); + Country c = new Country(); + c.name = args[2]; + c.code = args[0]; + c.shortname = args[1]; + String n = c.name.substring(0, 1).toUpperCase(); + ArrayList arr = countries.get(n); + if (arr == null) { + arr = new ArrayList<>(); + countries.put(n, arr); + sortedCountries.add(n); + } + arr.add(c); + } + reader.close(); + stream.close(); + } catch (Exception e) { + FileLog.e(e); + } } - Collections.sort(sortedCountries, String::compareTo); for (ArrayList arr : countries.values()) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DataAutoDownloadActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DataAutoDownloadActivity.java index 8722d6f6b..f9b494991 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DataAutoDownloadActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DataAutoDownloadActivity.java @@ -323,7 +323,7 @@ public class DataAutoDownloadActivity extends BaseFragment { cells[a].setTextAndCheck(LocaleController.getString("AutodownloadPrivateChats", R.string.AutodownloadPrivateChats), (currentPreset.mask[DownloadController.PRESET_NUM_PM] & type) != 0, true); } else if (a == 2) { cells[a].setTextAndCheck(LocaleController.getString("AutodownloadGroupChats", R.string.AutodownloadGroupChats), (currentPreset.mask[DownloadController.PRESET_NUM_GROUP] & type) != 0, true); - } else if (a == 3) { + } else { cells[a].setTextAndCheck(LocaleController.getString("AutodownloadChannels", R.string.AutodownloadChannels), (currentPreset.mask[DownloadController.PRESET_NUM_CHANNEL] & type) != 0, position != photosRow); } cells[a].setBackgroundDrawable(Theme.getSelectorDrawable(false)); @@ -439,8 +439,8 @@ public class DataAutoDownloadActivity extends BaseFragment { } } if (!hasAny) { - sizeCell[0].setEnabled(hasAny, null); - checkCell[0].setEnabled(hasAny, null); + sizeCell[0].setEnabled(false, null); + checkCell[0].setEnabled(false, null); } if (currentPreset.sizes[index] <= 2 * 1024 * 1024) { checkCell[0].setEnabled(false, null); @@ -787,7 +787,7 @@ public class DataAutoDownloadActivity extends BaseFragment { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: { TextCheckCell cell = new TextCheckCell(mContext); @@ -847,7 +847,8 @@ public class DataAutoDownloadActivity extends BaseFragment { view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; } - case 5: { + case 5: + default: { view = new TextInfoPrivacyCell(mContext); view.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java index 2b3f2ca99..80b8c1a22 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java @@ -822,7 +822,7 @@ public class DataUsageActivity extends BaseFragment { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new ShadowSectionCell(mContext); @@ -836,6 +836,7 @@ public class DataUsageActivity extends BaseFragment { view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; case 3: + default: view = new TextInfoPrivacyCell(mContext); break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DatabaseMigrationHint.java b/TMessagesProj/src/main/java/org/telegram/ui/DatabaseMigrationHint.java new file mode 100644 index 000000000..438bdf84c --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/DatabaseMigrationHint.java @@ -0,0 +1,65 @@ +package org.telegram.ui; + +import android.content.Context; +import android.util.TypedValue; +import android.view.Gravity; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.R; +import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.Components.LayoutHelper; +import org.telegram.ui.Components.RLottieImageView; + +public class DatabaseMigrationHint extends FrameLayout { + + LinearLayout container; + RLottieImageView stickerView; + TextView title; + TextView description1; + TextView description2; + + private final int currentAccount; + + public DatabaseMigrationHint(Context context, int currentAccount) { + super(context); + this.currentAccount = currentAccount; + container = new LinearLayout(context); + container.setOrientation(LinearLayout.VERTICAL); + + stickerView = new RLottieImageView(context); + stickerView.setAnimation(R.raw.db_migration_placeholder, 150, 150); + stickerView.getAnimatedDrawable().setAutoRepeat(1); + stickerView.playAnimation(); + container.addView(stickerView, LayoutHelper.createLinear(150, 150, Gravity.CENTER_HORIZONTAL)); + + title = new TextView(context); + title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24); + title.setText(LocaleController.getString("OptimizingTelegram", R.string.OptimizingTelegram)); + title.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + title.setGravity(Gravity.CENTER_HORIZONTAL); + container.addView(title, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 50, 32, 50, 0)); + + description1 = new TextView(context); + description1.setLineSpacing(AndroidUtilities.dp(2), 1.0f); + description1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + description1.setText(LocaleController.getString("OptimizingTelegramDescription1", R.string.OptimizingTelegramDescription1)); + description1.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + description1.setGravity(Gravity.CENTER_HORIZONTAL); + container.addView(description1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 36, 20, 36, 0)); + + description2 = new TextView(context); + description2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + description2.setText(LocaleController.getString("OptimizingTelegramDescription2", R.string.OptimizingTelegramDescription2)); + description2.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + description2.setGravity(Gravity.CENTER_HORIZONTAL); + container.addView(description2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 36, 24, 36, 0)); + + addView(container, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL)); + setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DialogOrContactPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DialogOrContactPickerActivity.java index 57fe76abb..804147f39 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DialogOrContactPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DialogOrContactPickerActivity.java @@ -22,6 +22,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.R; @@ -93,11 +94,10 @@ public class DialogOrContactPickerActivity extends BaseFragment { return; } long did = dids.get(0); - int lowerId = (int) did; - if (did <= 0) { + if (!DialogObject.isUserDialog(did)) { return; } - TLRPC.User user = getMessagesController().getUser(lowerId); + TLRPC.User user = getMessagesController().getUser(did); showBlockAlert(user); }); dialogsActivity.onFragmentCreate(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java index c64a16ece..68bee2345 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java @@ -169,6 +169,7 @@ import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SearchViewPager; import org.telegram.ui.Components.SizeNotifierFrameLayout; import org.telegram.ui.Components.StickersAlert; +import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.ui.Components.UndoView; import org.telegram.ui.Components.ViewPagerFixed; import org.telegram.ui.Components.RecyclerItemsEnterAnimator; @@ -427,12 +428,6 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. private Paint windowBackgroundPaint = new Paint(); private int inputFieldHeight; - @Override - public void setTranslationX(float translationX) { - Log.d("kek", "content view set translationX" + translationX); - super.setTranslationX(translationX); - } - public ContentView(Context context) { super(context); } @@ -1820,6 +1815,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. getNotificationCenter().addObserver(this, NotificationCenter.fileLoaded); getNotificationCenter().addObserver(this, NotificationCenter.fileLoadFailed); getNotificationCenter().addObserver(this, NotificationCenter.fileLoadProgressChanged); + getNotificationCenter().addObserver(this, NotificationCenter.onDatabaseMigration); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.didSetPasscode); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.appUpdateAvailable); @@ -2744,9 +2740,8 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } else if ((initialDialogsType == 11 || initialDialogsType == 13) && position == 1) { Bundle args = new Bundle(); args.putBoolean("forImport", true); - ArrayList result = new ArrayList<>(); - result.add(getUserConfig().getClientUserId()); - args.putIntegerArrayList("result", result); + long[] array = new long[]{getUserConfig().getClientUserId()}; + args.putLongArray("result", array); args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP); String title = arguments.getString("importTitle"); if (title != null) { @@ -2760,9 +2755,9 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } @Override - public void didFinishChatCreation(GroupCreateFinalActivity fragment, int chatId) { + public void didFinishChatCreation(GroupCreateFinalActivity fragment, long chatId) { ArrayList arrayList = new ArrayList<>(); - arrayList.add((long) -chatId); + arrayList.add(-chatId); DialogsActivityDelegate dialogsActivityDelegate = delegate; removeSelfFromStack(); dialogsActivityDelegate.didSelectDialogs(DialogsActivity.this, arrayList, null, true); @@ -3003,12 +2998,11 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. didSelectResult(did, true, false); } } else { - int lower_id = (int) did; Bundle args = new Bundle(); - if (lower_id > 0) { - args.putInt("user_id", lower_id); + if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); } else { - args.putInt("chat_id", -lower_id); + args.putLong("chat_id", -did); } closeSearch(); if (AndroidUtilities.isTablet() && viewPages != null) { @@ -3031,7 +3025,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } @Override - public void needRemoveHint(final int did) { + public void needRemoveHint(long did) { if (getParentActivity() == null) { return; } @@ -3113,7 +3107,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. searchViewPager.setFilteredSearchViewDelegate((showMediaFilters, users, dates, archive) -> DialogsActivity.this.updateFiltersView(showMediaFilters, users, dates, archive,true)); searchViewPager.setVisibility(View.GONE); - filtersView = new FiltersView(getParentActivity()); + filtersView = new FiltersView(getParentActivity(), null); filtersView.setOnItemClickListener((view, position) -> { filtersView.cancelClickRunnables(true); addSearchFilter(filtersView.getFilterAt(position)); @@ -3770,7 +3764,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } else if (id == add_to_folder) { FiltersListBottomSheet sheet = new FiltersListBottomSheet(DialogsActivity.this, selectedDialogs); sheet.setDelegate(filter -> { - ArrayList alwaysShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, true, false); + ArrayList alwaysShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, true, false); int currentCount; if (filter != null) { currentCount = filter.alwaysShow.size(); @@ -3804,7 +3798,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. showDialog(sheet); } else if (id == remove_from_folder) { MessagesController.DialogFilter filter = getMessagesController().dialogFilters.get(viewPages[0].selectedType); - ArrayList neverShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, false, false); + ArrayList neverShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, false, false); int currentCount; if (filter != null) { @@ -3819,9 +3813,9 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (!neverShow.isEmpty()) { filter.neverShow.addAll(neverShow); for (int a = 0; a < neverShow.size(); a++) { - Integer did = neverShow.get(a); + Long did = neverShow.get(a); filter.alwaysShow.remove(did); - filter.pinnedDialogs.remove((long) did); + filter.pinnedDialogs.delete(did); } FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.name, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, false, false, DialogsActivity.this, null); } @@ -4783,7 +4777,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. searchObject = (TLRPC.Chat) obj; } } else if (obj instanceof TLRPC.EncryptedChat) { - dialogId = ((long) ((TLRPC.EncryptedChat) obj).id) << 32; + dialogId = DialogObject.makeEncryptedDialogId(((TLRPC.EncryptedChat) obj).id); if (!onlySelect) { searchDialogId = dialogId; searchObject = (TLRPC.EncryptedChat) obj; @@ -4832,23 +4826,20 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } } else { Bundle args = new Bundle(); - int lower_part = (int) dialogId; - int high_id = (int) (dialogId >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - if (message_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - } - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + long did = dialogId; + if (message_id != 0) { + TLRPC.Chat chat = getMessagesController().getChat(-did); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", did); + did = -chat.migrated_to.channel_id; + } + } + args.putLong("chat_id", -did); } if (message_id != 0) { args.putInt("message_id", message_id); @@ -4884,7 +4875,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } else { if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) { ChatActivity chatActivity = new ChatActivity(args); - if (adapter instanceof DialogsAdapter && lower_part > 0 && (getMessagesController().dialogs_dict.get(dialogId) == null)) { + if (adapter instanceof DialogsAdapter && DialogObject.isUserDialog(dialogId) && (getMessagesController().dialogs_dict.get(dialogId) == null)) { TLRPC.Document sticker = getMediaDataController().getGreetingsSticker(); if (sticker != null) { chatActivity.setPreloadedSticker(sticker, true); @@ -4928,7 +4919,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. TLRPC.EncryptedChat encryptedChat = (TLRPC.EncryptedChat) item; TLRPC.User user = getMessagesController().getUser(encryptedChat.user_id); builder.setMessage(LocaleController.formatString("ClearSearchSingleUserAlertText", R.string.ClearSearchSingleUserAlertText, ContactsController.formatName(user.first_name, user.last_name))); - did = ((long) encryptedChat.id) << 32; + did = DialogObject.makeEncryptedDialogId(encryptedChat.id); } else { return false; } @@ -5020,28 +5011,26 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } private boolean showChatPreview(DialogCell cell) { - long dialog_id = cell.getDialogId(); + long dialogId = cell.getDialogId(); Bundle args = new Bundle(); - int lower_part = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); int message_id = cell.getMessageId(); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { + return false; + } else { + if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); + } else { + long did = dialogId; if (message_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lower_part); + TLRPC.Chat chat = getMessagesController().getChat(-did); if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; + args.putLong("migrated_to", did); + did = -chat.migrated_to.channel_id; } } - args.putInt("chat_id", -lower_part); + args.putLong("chat_id", -did); } - } else { - return false; } - if (message_id != 0) { args.putInt("message_id", message_id); } @@ -5219,7 +5208,6 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (dialog instanceof TLRPC.TL_dialogFolder) { continue; } - int lower_id = (int) dialog.id; if (isDialogPinned(dialog)) { pinnedCount++; } else if (!getMessagesController().isPromoDialog(dialog.id, false)) { @@ -5293,9 +5281,8 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (dialog instanceof TLRPC.TL_dialogFolder) { continue; } - int lower_id = (int) dialog.id; if (isDialogPinned(dialog)) { - if (lower_id == 0) { + if (DialogObject.isEncryptedDialog(dialog.id)) { pinnedSecretCount++; } else { pinnedCount++; @@ -5311,13 +5298,12 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (dialog == null || isDialogPinned(dialog)) { continue; } - int lower_id = (int) selectedDialog; - if (lower_id == 0) { + if (DialogObject.isEncryptedDialog(selectedDialog)) { newPinnedSecretCount++; } else { newPinnedCount++; } - if (filter != null && filter.alwaysShow.contains(lower_id)) { + if (filter != null && filter.alwaysShow.contains(selectedDialog)) { alreadyAdded++; } } @@ -5397,22 +5383,21 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. TLRPC.User user; if (count == 1) { long did = selectedDialogs.get(0); - user = getMessagesController().getUser((int) did); + user = getMessagesController().getUser(did); } else { user = null; } AlertsCreator.createBlockDialogAlert(DialogsActivity.this, count, canReportSpamCount != 0, user, (report, delete) -> { for (int a = 0, N = selectedDialogs.size(); a < N; a++) { long did = selectedDialogs.get(a); - int lowerId = (int) did; if (report) { - TLRPC.User u = getMessagesController().getUser(lowerId); + TLRPC.User u = getMessagesController().getUser(did); getMessagesController().reportSpam(did, u, null, null, false); } if (delete) { getMessagesController().deleteDialog(did, 0, true); } - getMessagesController().blockPeer(lowerId); + getMessagesController().blockPeer(did); } hideActionMode(false); }); @@ -5434,24 +5419,21 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } TLRPC.Chat chat; TLRPC.User user = null; - int lower_id = (int) selectedDialog; - int high_id = (int) (selectedDialog >> 32); + TLRPC.EncryptedChat encryptedChat = null; - if (lower_id != 0) { - if (lower_id > 0) { - user = getMessagesController().getUser(lower_id); - chat = null; - } else { - chat = getMessagesController().getChat(-lower_id); - } - } else { - encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(selectedDialog)) { + encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(selectedDialog)); chat = null; if (encryptedChat != null) { user = getMessagesController().getUser(encryptedChat.user_id); } else { user = new TLRPC.TL_userEmpty(); } + } else if (DialogObject.isUserDialog(selectedDialog)) { + user = getMessagesController().getUser(selectedDialog); + chat = null; + } else { + chat = getMessagesController().getChat(-selectedDialog); } if (chat == null && user == null) { continue; @@ -5471,8 +5453,8 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. filter.alwaysShow.add(encryptedChat.user_id); } } else { - if (!filter.alwaysShow.contains(lower_id)) { - filter.alwaysShow.add(lower_id); + if (!filter.alwaysShow.contains(dialog.id)) { + filter.alwaysShow.add(dialog.id); } } } @@ -5527,7 +5509,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else { - AlertsCreator.createClearOrDeleteDialogAlert(DialogsActivity.this, action == clear, chat, user, lower_id == 0, action == delete, (param) -> { + AlertsCreator.createClearOrDeleteDialogAlert(DialogsActivity.this, action == clear, chat, user, DialogObject.isEncryptedDialog(dialog.id), action == delete, (param) -> { hideActionMode(false); if (action == clear && ChatObject.isChannel(chat) && (!chat.megagroup || !TextUtils.isEmpty(chat.username))) { getMessagesController().deleteDialog(selectedDialog, 2, param); @@ -5549,6 +5531,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } } } + getUndoView().showWithAction(selectedDialog, action == clear ? UndoView.ACTION_CLEAR : UndoView.ACTION_DELETE, () -> performDeleteOrClearDialogAction(action, selectedDialog, chat, isBot, param)); ArrayList currentDialogs = new ArrayList<>(getDialogsArray(currentAccount, viewPages[0].dialogsType, folderId, false)); @@ -5587,7 +5570,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } } else if (action == mute) { if (count == 1 && canMuteCount == 1) { - showDialog(AlertsCreator.createMuteAlert(this, selectedDialog), dialog12 -> hideActionMode(true)); + showDialog(AlertsCreator.createMuteAlert(this, selectedDialog, null), dialog12 -> hideActionMode(true)); return; } else { if (canUnmuteCount != 0) { @@ -5605,7 +5588,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } } if (action == mute && !(count == 1 && canMuteCount == 1)) { - BulletinFactory.createMuteBulletin(this, canUnmuteCount == 0).show(); + BulletinFactory.createMuteBulletin(this, canUnmuteCount == 0, null).show(); } if (action == pin || action == pin2) { if (filter != null) { @@ -5687,7 +5670,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (pin) { filter.pinnedDialogs.put(selectedDialog, minPinnedNum); } else { - filter.pinnedDialogs.remove(selectedDialog); + filter.pinnedDialogs.delete(selectedDialog); } if (animated) { @@ -5775,7 +5758,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. return; } int count = selectedDialogs.size(); - int selfUserId = getUserConfig().getClientUserId(); + long selfUserId = getUserConfig().getClientUserId(); SharedPreferences preferences = getNotificationsSettings(); for (int a = 0; a < count; a++) { TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(selectedDialogs.get(a)); @@ -5802,13 +5785,10 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. canArchiveCount++; } - int lower_id = (int) selectedDialog; - int high_id = (int) (selectedDialog >> 32); - - if (lower_id <= 0 || lower_id == selfUserId) { + if (!DialogObject.isUserDialog(selectedDialog) || selectedDialog == selfUserId) { cantBlockCount++; } else { - TLRPC.User user = getMessagesController().getUser(lower_id); + TLRPC.User user = getMessagesController().getUser(selectedDialog); if (MessagesController.isSupportUser(user)) { cantBlockCount++; } else { @@ -5819,7 +5799,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } if (DialogObject.isChannel(dialog)) { - final TLRPC.Chat chat = getMessagesController().getChat(-lower_id); + final TLRPC.Chat chat = getMessagesController().getChat(-selectedDialog); CharSequence[] items; if (getMessagesController().isPromoDialog(dialog.id, true)) { canClearCacheCount++; @@ -5845,18 +5825,18 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. canDeleteCount++; } } else { - final boolean isChat = lower_id < 0 && high_id != 1; + final boolean isChat = DialogObject.isChatDialog(dialog.id); TLRPC.User user; - TLRPC.Chat chat = isChat ? getMessagesController().getChat(-lower_id) : null; - if (lower_id == 0) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + TLRPC.Chat chat = isChat ? getMessagesController().getChat(-dialog.id) : null; + if (DialogObject.isEncryptedDialog(dialog.id)) { + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialog.id)); if (encryptedChat != null) { user = getMessagesController().getUser(encryptedChat.user_id); } else { user = new TLRPC.TL_userEmpty(); } } else { - user = !isChat && lower_id > 0 && high_id != 1 ? getMessagesController().getUser(lower_id) : null; + user = !isChat && DialogObject.isUserDialog(dialog.id) ? getMessagesController().getUser(dialog.id) : null; } final boolean isBot = user != null && user.bot && !MessagesController.isSupportUser(user); @@ -5998,11 +5978,10 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (messagesCount <= 1 && (commentView == null || commentView.getVisibility() != View.VISIBLE || TextUtils.isEmpty(commentView.getFieldText()))) { return true; } - int lowerId = (int) dialogId; - if (lowerId >= 0) { + if (!DialogObject.isChatDialog(dialogId)) { return true; } - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (chat != null && !ChatObject.hasAdminRights(chat) && chat.slowmode_enabled) { AlertsCreator.showSimpleAlert(DialogsActivity.this, LocaleController.getString("Slowmode", R.string.Slowmode), LocaleController.getString("SlowmodeSendError", R.string.SlowmodeSendError)); return false; @@ -6502,7 +6481,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (ChatObject.isNotInChat(chat)) { getMessagesController().deleteDialog(dialogId, 0, revoke); } else { - getMessagesController().deleteParticipantFromChat((int) -dialogId, getMessagesController().getUser(getUserConfig().getClientUserId()), null, null, revoke, revoke); + getMessagesController().deleteParticipantFromChat(-dialogId, getMessagesController().getUser(getUserConfig().getClientUserId()), null, null, revoke, revoke); } } else { getMessagesController().deleteDialog(dialogId, 0, revoke); @@ -6531,7 +6510,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. } else if (id == NotificationCenter.messagesDeleted) { if (searchIsShowed && searchViewPager != null) { ArrayList markAsDeletedMessages = (ArrayList) args[0]; - int channelId = (int) args[1]; + long channelId = (Long) args[1]; searchViewPager.messagesDeleted(channelId, markAsDeletedMessages); } } else if (id == NotificationCenter.didClearDatabase) { @@ -6550,9 +6529,40 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. updateMenuButton(true); } } + } else if (id == NotificationCenter.onDatabaseMigration) { + boolean startMigration = (boolean) args[0]; + if (fragmentView != null) { + if (startMigration) { + if (databaseMigrationHint == null) { + databaseMigrationHint = new DatabaseMigrationHint(fragmentView.getContext(), currentAccount); + databaseMigrationHint.setAlpha(0f); + ((ContentView) fragmentView).addView(databaseMigrationHint); + databaseMigrationHint.animate().alpha(1).setDuration(300).setStartDelay(1000).start(); + } + } else { + if (databaseMigrationHint != null) { + View localView = databaseMigrationHint; + localView.animate().setListener(null).cancel(); + localView.animate().setListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + if (localView.getParent() != null) { + ((ContentView) fragmentView).removeView(localView); + } + + } + }).alpha(0f).setDuration(150).start(); + + databaseMigrationHint = null; + + } + } + } } } + View databaseMigrationHint; + private void updateMenuButton(boolean animated) { if (menuDrawable == null || updateLayout == null) { return; @@ -6852,12 +6862,11 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. this.initialSearchType = type; } - private void didSelectResult(final long dialog_id, boolean useAlert, final boolean param) { + private void didSelectResult(final long dialogId, boolean useAlert, final boolean param) { if (addToGroupAlertString == null && checkCanWrite) { - int lowerId = (int) dialog_id; - if (lowerId < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); - if (ChatObject.isChannel(chat) && !chat.megagroup && ((cantSendToChannels || !ChatObject.isCanWriteToChannel(-lowerId, currentAccount)) || hasPoll == 2)) { + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); + if (ChatObject.isChannel(chat) && !chat.megagroup && ((cantSendToChannels || !ChatObject.isCanWriteToChannel(-dialogId, currentAccount)) || hasPoll == 2)) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle)); if (hasPoll == 2) { @@ -6869,7 +6878,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. showDialog(builder.create()); return; } - } else if (lowerId == 0 && (hasPoll != 0 || hasInvoice)) { + } else if (DialogObject.isEncryptedDialog(dialogId) && (hasPoll != 0 || hasInvoice)) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle)); if (hasPoll != 0) { @@ -6886,27 +6895,26 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. if (checkingImportDialog) { return; } - int lowerId = (int) dialog_id; TLRPC.User user; TLRPC.Chat chat; - if (lowerId > 0) { - user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); chat = null; if (!user.mutual_contact) { - getUndoView().showWithAction(dialog_id, UndoView.ACTION_IMPORT_NOT_MUTUAL, null); + getUndoView().showWithAction(dialogId, UndoView.ACTION_IMPORT_NOT_MUTUAL, null); return; } } else { user = null; - chat = getMessagesController().getChat(-lowerId); + chat = getMessagesController().getChat(-dialogId); if (!ChatObject.hasAdminRights(chat) || !ChatObject.canChangeChatInfo(chat)) { - getUndoView().showWithAction(dialog_id, UndoView.ACTION_IMPORT_GROUP_NOT_ADMIN, null); + getUndoView().showWithAction(dialogId, UndoView.ACTION_IMPORT_GROUP_NOT_ADMIN, null); return; } } final AlertDialog progressDialog = new AlertDialog(getParentActivity(), 3); TLRPC.TL_messages_checkHistoryImportPeer req = new TLRPC.TL_messages_checkHistoryImportPeer(); - req.peer = getMessagesController().getInputPeer(lowerId); + req.peer = getMessagesController().getInputPeer(dialogId); getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { try { progressDialog.dismiss(); @@ -6919,12 +6927,12 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. AlertsCreator.createImportDialogAlert(this, arguments.getString("importTitle"), res.confirm_text, user, chat, () -> { setDialogsListFrozen(true); ArrayList dids = new ArrayList<>(); - dids.add(dialog_id); + dids.add(dialogId); delegate.didSelectDialogs(DialogsActivity.this, dids, null, param); }); } else { AlertsCreator.processError(currentAccount, error, this, req); - getNotificationCenter().postNotificationName(NotificationCenter.historyImportProgressChanged, dialog_id, req, error); + getNotificationCenter().postNotificationName(NotificationCenter.historyImportProgressChanged, dialogId, req, error); } })); try { @@ -6937,41 +6945,11 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - int lower_part = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); String title; String message; String buttonText; - if (lower_part != 0) { - if (lower_part == getUserConfig().getClientUserId()) { - title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); - message = LocaleController.formatStringSimple(selectAlertStringGroup, LocaleController.getString("SavedMessages", R.string.SavedMessages)); - buttonText = LocaleController.getString("Send", R.string.Send); - } else if (lower_part > 0) { - TLRPC.User user = getMessagesController().getUser(lower_part); - if (user == null || selectAlertString == null) { - return; - } - title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); - message = LocaleController.formatStringSimple(selectAlertString, UserObject.getUserName(user)); - buttonText = LocaleController.getString("Send", R.string.Send); - } else { - TLRPC.Chat chat = getMessagesController().getChat(-lower_part); - if (chat == null) { - return; - } - if (addToGroupAlertString != null) { - title = LocaleController.getString("AddToTheGroupAlertTitle", R.string.AddToTheGroupAlertTitle); - message = LocaleController.formatStringSimple(addToGroupAlertString, chat.title); - buttonText = LocaleController.getString("Add", R.string.Add); - } else { - title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); - message = LocaleController.formatStringSimple(selectAlertStringGroup, chat.title); - buttonText = LocaleController.getString("Send", R.string.Send); - } - } - } else { - TLRPC.EncryptedChat chat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(dialogId)) { + TLRPC.EncryptedChat chat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); TLRPC.User user = getMessagesController().getUser(chat.user_id); if (user == null) { return; @@ -6979,16 +6957,44 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter. title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); message = LocaleController.formatStringSimple(selectAlertString, UserObject.getUserName(user)); buttonText = LocaleController.getString("Send", R.string.Send); + } else if (DialogObject.isUserDialog(dialogId)) { + if (dialogId == getUserConfig().getClientUserId()) { + title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); + message = LocaleController.formatStringSimple(selectAlertStringGroup, LocaleController.getString("SavedMessages", R.string.SavedMessages)); + buttonText = LocaleController.getString("Send", R.string.Send); + } else { + TLRPC.User user = getMessagesController().getUser(dialogId); + if (user == null || selectAlertString == null) { + return; + } + title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); + message = LocaleController.formatStringSimple(selectAlertString, UserObject.getUserName(user)); + buttonText = LocaleController.getString("Send", R.string.Send); + } + } else { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); + if (chat == null) { + return; + } + if (addToGroupAlertString != null) { + title = LocaleController.getString("AddToTheGroupAlertTitle", R.string.AddToTheGroupAlertTitle); + message = LocaleController.formatStringSimple(addToGroupAlertString, chat.title); + buttonText = LocaleController.getString("Add", R.string.Add); + } else { + title = LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle); + message = LocaleController.formatStringSimple(selectAlertStringGroup, chat.title); + buttonText = LocaleController.getString("Send", R.string.Send); + } } builder.setTitle(title); builder.setMessage(AndroidUtilities.replaceTags(message)); - builder.setPositiveButton(buttonText, (dialogInterface, i) -> didSelectResult(dialog_id, false, false)); + builder.setPositiveButton(buttonText, (dialogInterface, i) -> didSelectResult(dialogId, false, false)); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else { if (delegate != null) { ArrayList dids = new ArrayList<>(); - dids.add(dialog_id); + dids.add(dialogId); delegate.didSelectDialogs(DialogsActivity.this, dids, null, param); if (resetDelegate) { delegate = null; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/EditWidgetActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/EditWidgetActivity.java index 9b68adf27..f2dd0d4c1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/EditWidgetActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/EditWidgetActivity.java @@ -52,6 +52,7 @@ import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatsWidgetProvider; import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsWidgetProvider; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; @@ -260,9 +261,8 @@ public class EditWidgetActivity extends BaseFragment { TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; - int lowerId = (int) dialog.id; - if (lowerId > 0) { - user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialog.id)) { + user = getMessagesController().getUser(dialog.id); if (user != null) { if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); @@ -273,12 +273,12 @@ public class EditWidgetActivity extends BaseFragment { } else { name = ContactsController.formatName(user.first_name, user.last_name); } - if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user != null && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { + if (!UserObject.isReplyUser(user) && !UserObject.isUserSelf(user) && user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) { photoPath = user.photo.photo_small; } } } else { - chat = getMessagesController().getChat(-lowerId); + chat = getMessagesController().getChat(-dialog.id); if (chat != null) { name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { @@ -337,7 +337,7 @@ public class EditWidgetActivity extends BaseFragment { if (message != null) { TLRPC.User fromUser = null; TLRPC.Chat fromChat = null; - int fromId = message.getFromChatId(); + long fromId = message.getFromChatId(); if (fromId > 0) { fromUser = getMessagesController().getUser(fromId); } else { @@ -461,7 +461,7 @@ public class EditWidgetActivity extends BaseFragment { messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); } else { messageString = message.messageText; - AndroidUtilities.highlightText(messageString, message.highlightedWords); + AndroidUtilities.highlightText(messageString, message.highlightedWords, null); } if (message.messageOwner.media != null && !message.isMediaEmpty()) { textColor = getContext().getResources().getColor(R.color.widget_action_text); @@ -474,14 +474,14 @@ public class EditWidgetActivity extends BaseFragment { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setText(messageString.toString()); ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setTextColor(textColor); } else { - if (dialog != null && dialog.last_message_date != 0) { + if (dialog.last_message_date != 0) { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_time)).setText(LocaleController.stringForMessageListDate(dialog.last_message_date)); } else { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_time)).setText(""); } ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_message)).setText(""); } - if (dialog != null && dialog.unread_count > 0) { + if (dialog.unread_count > 0) { ((TextView) cells[a].findViewById(R.id.shortcut_widget_item_badge)).setText(String.format("%d", dialog.unread_count)); cells[a].findViewById(R.id.shortcut_widget_item_badge).setVisibility(VISIBLE); if (getMessagesController().isDialogMuted(dialog.id)) { @@ -502,7 +502,7 @@ public class EditWidgetActivity extends BaseFragment { TLRPC.Dialog dialog; if (selectedDialogs.isEmpty()) { if (num < getMediaDataController().hints.size()) { - int userId = getMediaDataController().hints.get(num).peer.user_id; + long userId = getMediaDataController().hints.get(num).peer.user_id; dialog = getMessagesController().dialogs_dict.get(userId); if (dialog == null) { dialog = new TLRPC.TL_dialog(); @@ -536,12 +536,11 @@ public class EditWidgetActivity extends BaseFragment { String name; - int lowerId = (int) dialog.id; TLRPC.FileLocation photoPath = null; TLRPC.User user = null; TLRPC.Chat chat = null; - if (lowerId > 0) { - user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialog.id)) { + user = getMessagesController().getUser(dialog.id); if (UserObject.isUserSelf(user)) { name = LocaleController.getString("SavedMessages", R.string.SavedMessages); } else if (UserObject.isReplyUser(user)) { @@ -555,7 +554,7 @@ public class EditWidgetActivity extends BaseFragment { photoPath = user.photo.photo_small; } } else { - chat = getMessagesController().getChat(-lowerId); + chat = getMessagesController().getChat(-dialog.id); name = chat.title; if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { photoPath = chat.photo.photo_small; @@ -603,7 +602,7 @@ public class EditWidgetActivity extends BaseFragment { FileLog.e(e); } - if (dialog != null && dialog.unread_count > 0) { + if (dialog.unread_count > 0) { String count; if (dialog.unread_count > 99) { count = String.format("%d+", 99); @@ -842,7 +841,7 @@ public class EditWidgetActivity extends BaseFragment { itemTouchHelper.attachToRecyclerView(listView); listView.setOnItemClickListener((view, position) -> { if (position == selectChatsRow) { - InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, null, 0, EditWidgetActivity.this); + InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, null, 0, EditWidgetActivity.this, null); bottomSheet.setDelegate(dids -> { selectedDialogs.clear(); selectedDialogs.addAll(dids); @@ -995,12 +994,11 @@ public class EditWidgetActivity extends BaseFragment { case 3: { GroupCreateUserCell cell = (GroupCreateUserCell) holder.itemView; long did = selectedDialogs.get(position - chatsStartRow); - int lowerId = (int) did; - if (lowerId > 0) { - TLRPC.User user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(did)) { + TLRPC.User user = getMessagesController().getUser(did); cell.setObject(user, null, null, position != chatsEndRow - 1); } else { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + TLRPC.Chat chat = getMessagesController().getChat(-did); cell.setObject(chat, null, null, position != chatsEndRow - 1); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/EmojiAnimationsOverlay.java b/TMessagesProj/src/main/java/org/telegram/ui/EmojiAnimationsOverlay.java new file mode 100644 index 000000000..d7ea010f5 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/EmojiAnimationsOverlay.java @@ -0,0 +1,448 @@ +package org.telegram.ui; + +import android.graphics.Canvas; +import android.util.Log; +import android.view.HapticFeedbackConstants; +import android.view.View; +import android.widget.FrameLayout; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.Emoji; +import org.telegram.messenger.EmojiData; +import org.telegram.messenger.FileLog; +import org.telegram.messenger.ImageLocation; +import org.telegram.messenger.ImageReceiver; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.MediaDataController; +import org.telegram.messenger.MessagesController; +import org.telegram.messenger.NotificationCenter; +import org.telegram.messenger.R; +import org.telegram.messenger.SharedConfig; +import org.telegram.tgnet.ConnectionsManager; +import org.telegram.tgnet.TLRPC; +import org.telegram.ui.Cells.ChatMessageCell; +import org.telegram.ui.Components.Bulletin; +import org.telegram.ui.Components.BulletinFactory; +import org.telegram.ui.Components.RecyclerListView; +import org.telegram.ui.Components.StickerSetBulletinLayout; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Random; + +public class EmojiAnimationsOverlay implements NotificationCenter.NotificationCenterDelegate { + + private final int ANIMATION_JSON_VERSION = 1; + private final String INTERACTIONS_STICKER_PACK = "EmojiAnimations"; + + ChatActivity chatActivity; + int currentAccount; + TLRPC.TL_messages_stickerSet set; + boolean inited = false; + HashMap> emojiInteractionsStickersMap = new HashMap<>(); + HashMap lastAnimationIndex = new HashMap<>(); + Random random = new Random(); + private boolean attached; + + int lastTappedMsgId = -1; + long lastTappedTime = 0; + String lastTappedEmoji; + ArrayList timeIntervals = new ArrayList<>(); + ArrayList animationIndexes = new ArrayList<>(); + Runnable sentInteractionsRunnable; + + private final static HashSet supportedEmoji = new HashSet<>(); + private final static HashSet excludeEmojiFromPack = new HashSet<>(); + static { + // 1️⃣, 2️⃣, 3️⃣... etc + excludeEmojiFromPack.add("\u0030\u20E3"); + excludeEmojiFromPack.add("\u0031\u20E3"); + excludeEmojiFromPack.add("\u0032\u20E3"); + excludeEmojiFromPack.add("\u0033\u20E3"); + excludeEmojiFromPack.add("\u0034\u20E3"); + excludeEmojiFromPack.add("\u0035\u20E3"); + excludeEmojiFromPack.add("\u0036\u20E3"); + excludeEmojiFromPack.add("\u0037\u20E3"); + excludeEmojiFromPack.add("\u0038\u20E3"); + excludeEmojiFromPack.add("\u0039\u20E3"); + } + + ArrayList drawingObjects = new ArrayList<>(); + + FrameLayout contentLayout; + RecyclerListView listView; + long dialogId; + int threadMsgId; + + + public EmojiAnimationsOverlay(ChatActivity chatActivity, FrameLayout frameLayout, RecyclerListView chatListView, int currentAccount, long dialogId, int threadMsgId) { + this.chatActivity = chatActivity; + this.contentLayout = frameLayout; + this.listView = chatListView; + this.currentAccount = currentAccount; + this.dialogId = dialogId; + this.threadMsgId = threadMsgId; + } + + protected void onAttachedToWindow() { + attached = true; + checkStickerPack(); + NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.diceStickersDidLoad); + NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.onEmojiInteractionsReceived); + } + + protected void onDetachedFromWindow() { + attached = false; + NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.diceStickersDidLoad); + NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.onEmojiInteractionsReceived); + } + + public void checkStickerPack() { + if (inited) { + return; + } + set = MediaDataController.getInstance(currentAccount).getStickerSetByName(INTERACTIONS_STICKER_PACK); + if (set == null) { + set = MediaDataController.getInstance(currentAccount).getStickerSetByEmojiOrName(INTERACTIONS_STICKER_PACK); + } + if (set == null) { + MediaDataController.getInstance(currentAccount).loadStickersByEmojiOrName(INTERACTIONS_STICKER_PACK, false, true); + } + if (set != null) { + HashMap stickersMap = new HashMap<>(); + for (int i = 0; i < set.documents.size(); i++) { + stickersMap.put(set.documents.get(i).id, set.documents.get(i)); + } + for (int i = 0; i < set.packs.size(); i++) { + TLRPC.TL_stickerPack pack = set.packs.get(i); + if (!excludeEmojiFromPack.contains(pack.emoticon) && pack.documents.size() > 0) { + supportedEmoji.add(pack.emoticon); + ArrayList stickers = new ArrayList<>(); + emojiInteractionsStickersMap.put(pack.emoticon, stickers); + for (int j = 0; j < pack.documents.size(); j++) { + stickers.add(stickersMap.get(pack.documents.get(j))); + } + + if (pack.emoticon.equals("❤")) { + String[] heartEmojies = new String[]{"🧡", "💛", "💚", "💙", "💜", "🖤", "🤍", "🤎"}; + for (String heart : heartEmojies) { + supportedEmoji.add(heart); + emojiInteractionsStickersMap.put(heart, stickers); + } + } + } + } + inited = true; + } + } + + + @Override + public void didReceivedNotification(int id, int account, Object... args) { + if (id == NotificationCenter.diceStickersDidLoad) { + String name = (String) args[0]; + if (INTERACTIONS_STICKER_PACK.equals(name)) { + checkStickerPack(); + } + } else if (id == NotificationCenter.onEmojiInteractionsReceived) { + long dialogId = (long) args[0]; + TLRPC.TL_sendMessageEmojiInteraction action = (TLRPC.TL_sendMessageEmojiInteraction) args[1]; + if (dialogId == this.dialogId && supportedEmoji.contains(action.emoticon)) { + int messageId = action.msg_id; + if (action.interaction.data != null) { + try { + JSONObject jsonObject = new JSONObject(action.interaction.data); + JSONArray array = jsonObject.getJSONArray("a"); + for (int i = 0; i < array.length(); i++) { + JSONObject actionObject = array.getJSONObject(i); + int animation = actionObject.optInt("i", 1) - 1; + double time = actionObject.optDouble("t", 0.0); + AndroidUtilities.runOnUIThread(new Runnable() { + @Override + public void run() { + findViewAndShowAnimation(messageId, animation); + } + }, (long) (time * 1000)); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + } + } + } + + private void findViewAndShowAnimation(int messageId, int animation) { + if (!attached) { + return; + } + ChatMessageCell bestView = null; + for (int i = 0; i < listView.getChildCount(); i++) { + View child = listView.getChildAt(i); + if (child instanceof ChatMessageCell) { + ChatMessageCell cell = (ChatMessageCell) child; + if (cell.getPhotoImage().hasNotThumb() && cell.getMessageObject().getStickerEmoji() != null) { + if (cell.getMessageObject().getId() == messageId) { + bestView = cell; + break; + } + } + } + } + + if (bestView != null) { + chatActivity.restartSticker(bestView); + if (!EmojiData.hasEmojiSupportVibration(bestView.getMessageObject().getStickerEmoji())) { + bestView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); + } + showAnimationForCell(bestView, animation, false, true); + } + } + + public void draw(Canvas canvas) { + if (!drawingObjects.isEmpty()) { + for (int i = 0; i < drawingObjects.size(); i++) { + DrawingObject drawingObject = drawingObjects.get(i); + drawingObject.viewFound = false; + for (int k = 0; k < listView.getChildCount(); k++) { + View child = listView.getChildAt(k); + if (child instanceof ChatMessageCell) { + ChatMessageCell cell = (ChatMessageCell) child; + if (cell.getMessageObject().getId() == drawingObject.messageId) { + drawingObject.viewFound = true; + float viewX = listView.getX() + child.getX() + cell.getPhotoImage().getImageX(); + float viewY = listView.getY() + child.getY() + cell.getPhotoImage().getImageY(); + if (drawingObject.isOut) { + viewX += -cell.getPhotoImage().getImageWidth() * 2 + AndroidUtilities.dp(24); + } else { + viewX += -AndroidUtilities.dp(24); + } + viewY -= cell.getPhotoImage().getImageWidth(); + drawingObject.lastX = viewX; + drawingObject.lastY = viewY; + drawingObject.lastW = cell.getPhotoImage().getImageWidth(); + break; + } + } + } + + drawingObject.imageReceiver.setImageCoords(drawingObject.lastX + drawingObject.randomOffsetX, drawingObject.lastY + drawingObject.randomOffsetY, drawingObject.lastW * 3, drawingObject.lastW * 3); + if (!drawingObject.isOut) { + canvas.save(); + canvas.scale(-1f, 1, drawingObject.imageReceiver.getCenterX(), drawingObject.imageReceiver.getCenterY()); + drawingObject.imageReceiver.draw(canvas); + canvas.restore(); + } else { + drawingObject.imageReceiver.draw(canvas); + } + if (drawingObject.wasPlayed && drawingObject.imageReceiver.getLottieAnimation() != null && drawingObject.imageReceiver.getLottieAnimation().getCurrentFrame() == drawingObject.imageReceiver.getLottieAnimation().getFramesCount() - 2) { + drawingObjects.remove(i); + i--; + } else if (drawingObject.imageReceiver.getLottieAnimation() != null && drawingObject.imageReceiver.getLottieAnimation().isRunning()) { + drawingObject.wasPlayed = true; + } else if (drawingObject.imageReceiver.getLottieAnimation() != null && !drawingObject.imageReceiver.getLottieAnimation().isRunning()) { + drawingObject.imageReceiver.getLottieAnimation().setCurrentFrame(0, true); + drawingObject.imageReceiver.getLottieAnimation().start(); + } + } + contentLayout.invalidate(); + } + } + + public void onTapItem(ChatMessageCell view, ChatActivity chatActivity) { + if (chatActivity.currentUser == null || chatActivity.isSecretChat()) { + return; + } + boolean show = showAnimationForCell(view, -1, true, false); + if (show && !EmojiData.hasEmojiSupportVibration(view.getMessageObject().getStickerEmoji())) { + view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); + } + if ((Bulletin.getVisibleBulletin() == null || !Bulletin.getVisibleBulletin().isShowing()) && SharedConfig.emojiInteractionsHintCount > 0) { + SharedConfig.updateEmojiInteractionsHintCount(SharedConfig.emojiInteractionsHintCount - 1); + TLRPC.Document document = MediaDataController.getInstance(currentAccount).getEmojiAnimatedSticker(view.getMessageObject().getStickerEmoji()); + StickerSetBulletinLayout layout = new StickerSetBulletinLayout(chatActivity.getParentActivity(), null, StickerSetBulletinLayout.TYPE_EMPTY, document, chatActivity.getResourceProvider()); + layout.subtitleTextView.setVisibility(View.GONE); + layout.titleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("EmojiInteractionTapHint", R.string.EmojiInteractionTapHint, chatActivity.currentUser.first_name))); + layout.titleTextView.setTypeface(null); + layout.titleTextView.setMaxLines(3); + layout.titleTextView.setSingleLine(false); + Bulletin.make(chatActivity, layout, Bulletin.DURATION_LONG).show(); + } + } + + private boolean showAnimationForCell(ChatMessageCell view, int animation, boolean sendTap, boolean sendSeen) { + if (drawingObjects.size() > 12) { + return false; + } + if (!view.getPhotoImage().hasNotThumb()) { + return false; + } + String emoji = view.getMessageObject().getStickerEmoji(); + if (emoji == null) { + return false; + } + float imageH = view.getPhotoImage().getImageHeight(); + float imageW = view.getPhotoImage().getImageWidth(); + if (imageH <= 0 || imageW <= 0) { + return false; + } + + if (supportedEmoji.contains(emoji)) { + ArrayList arrayList = emojiInteractionsStickersMap.get(view.getMessageObject().getStickerEmoji()); + if (arrayList != null && !arrayList.isEmpty()) { + int sameAnimationsCount = 0; + for (int i = 0; i < drawingObjects.size(); i++) { + if (drawingObjects.get(i).messageId == view.getMessageObject().getId()) { + sameAnimationsCount++; + if (drawingObjects.get(i).imageReceiver.getLottieAnimation() == null || drawingObjects.get(i).imageReceiver.getLottieAnimation().isGeneratingCache()) { + return false; + } + } + } + if (sameAnimationsCount >= 4) { + return false; + } + if (animation < 0 || animation > arrayList.size() - 1) { + animation = Math.abs(random.nextInt()) % arrayList.size(); + } + TLRPC.Document document = arrayList.get(animation); + + DrawingObject drawingObject = new DrawingObject(); + drawingObject.randomOffsetX = imageW / 4 * ((random.nextInt() % 101) / 100f); + drawingObject.randomOffsetY = imageH / 4 * ((random.nextInt() % 101) / 100f); + drawingObject.messageId = view.getMessageObject().getId(); + drawingObject.document = document; + drawingObject.isOut = view.getMessageObject().isOutOwner(); + + Integer lastIndex = lastAnimationIndex.get(document.id); + int currentIndex = lastIndex == null ? 0 : lastIndex; + lastAnimationIndex.put(document.id, (currentIndex + 1) % 4); + + + ImageLocation imageLocation = ImageLocation.getForDocument(document); + drawingObject.imageReceiver.setUniqKeyPrefix(currentIndex + "_" + drawingObject.messageId + "_"); + int w = (int) (2f * imageW / AndroidUtilities.density); + drawingObject.imageReceiver.setImage(imageLocation, w + "_" + w + "_pcache", null, "tgs", set, 1); + drawingObject.imageReceiver.setLayerNum(Integer.MAX_VALUE); + drawingObject.imageReceiver.setAllowStartAnimation(true); + drawingObject.imageReceiver.setAutoRepeat(0); + if (drawingObject.imageReceiver.getLottieAnimation() != null) { + drawingObject.imageReceiver.getLottieAnimation().start(); + } + drawingObjects.add(drawingObject); + drawingObject.imageReceiver.onAttachedToWindow(); + drawingObject.imageReceiver.setParentView(contentLayout); + contentLayout.invalidate(); + + if (sendTap) { + if (lastTappedMsgId != 0 && lastTappedMsgId != view.getMessageObject().getId()) { + if (sentInteractionsRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(sentInteractionsRunnable); + sentInteractionsRunnable.run(); + } + } + lastTappedMsgId = view.getMessageObject().getId(); + lastTappedEmoji = emoji; + if (lastTappedTime == 0) { + lastTappedTime = System.currentTimeMillis(); + timeIntervals.clear(); + animationIndexes.clear();; + timeIntervals.add(0L); + animationIndexes.add(animation); + } else { + timeIntervals.add(System.currentTimeMillis() - lastTappedTime); + animationIndexes.add(animation); + } + if (sentInteractionsRunnable != null) { + AndroidUtilities.cancelRunOnUIThread(sentInteractionsRunnable); + sentInteractionsRunnable = null; + } + AndroidUtilities.runOnUIThread(sentInteractionsRunnable = () -> { + sendCurrentTaps(); + sentInteractionsRunnable = null; + }, 500); + } + + if (sendSeen) { + MessagesController.getInstance(currentAccount).sendTyping(dialogId, threadMsgId, 11, emoji, 0); + } + return true; + } + } + return false; + } + + private void sendCurrentTaps() { + if (lastTappedMsgId == 0) { + return; + } + TLRPC.TL_sendMessageEmojiInteraction interaction = new TLRPC.TL_sendMessageEmojiInteraction(); + interaction.msg_id = lastTappedMsgId; + interaction.emoticon = lastTappedEmoji; + interaction.interaction = new TLRPC.TL_dataJSON(); + JSONObject jsonObject = new JSONObject(); + try { + jsonObject.put("v", ANIMATION_JSON_VERSION); + JSONArray array = new JSONArray(); + + for (int i = 0; i < timeIntervals.size(); i++) { + JSONObject action = new JSONObject(); + action.put("i", animationIndexes.get(i) + 1); + action.put("t", timeIntervals.get(i) / 1000f); + array.put(i, action); + } + + jsonObject.put("a", array); + } catch (JSONException e) { + clearSendingInfo(); + FileLog.e(e); + return; + } + interaction.interaction.data = jsonObject.toString(); + + TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping(); + if (threadMsgId != 0) { + req.top_msg_id = threadMsgId; + req.flags |= 1; + } + req.action = interaction; + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); + ConnectionsManager.getInstance(currentAccount).sendRequest(req, null); + clearSendingInfo(); + } + + private void clearSendingInfo() { + lastTappedMsgId = 0; + lastTappedEmoji = null; + lastTappedTime = 0; + timeIntervals.clear(); + animationIndexes.clear(); + } + + public void onScrolled(int dy) { + for (int i = 0; i < drawingObjects.size(); i++) { + if (!drawingObjects.get(i).viewFound) { + drawingObjects.get(i).lastY -= dy; + } + } + } + + private class DrawingObject { + public float lastX; + public float lastY; + public boolean viewFound; + public float lastW; + public float randomOffsetX; + public float randomOffsetY; + boolean wasPlayed; + boolean isOut; + int messageId; + TLRPC.Document document; + ImageReceiver imageReceiver = new ImageReceiver(); + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ExternalActionActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ExternalActionActivity.java index 4a0cfb7fc..6a1b478a9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ExternalActionActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ExternalActionActivity.java @@ -306,7 +306,7 @@ public class ExternalActionActivity extends Activity implements ActionBarLayout. } } - final int bot_id = intent.getIntExtra("bot_id", 0); + final long bot_id = intent.getLongExtra("bot_id", 0); final String nonce = intent.getStringExtra("nonce"); final String payload = intent.getStringExtra("payload"); final TLRPC.TL_account_getAuthorizationForm req = new TLRPC.TL_account_getAuthorizationForm(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/FeaturedStickersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/FeaturedStickersActivity.java index 191f11f82..ddf69f8d8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/FeaturedStickersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/FeaturedStickersActivity.java @@ -228,7 +228,7 @@ public class FeaturedStickersActivity extends BaseFragment implements Notificati @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new FeaturedStickerSetCell(mContext); @@ -245,6 +245,7 @@ public class FeaturedStickersActivity extends BaseFragment implements Notificati }); break; case 1: + default: view = new TextInfoPrivacyCell(mContext); view.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); break; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/FilterCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/FilterCreateActivity.java index 40851a138..b0d73bd16 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/FilterCreateActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/FilterCreateActivity.java @@ -8,7 +8,6 @@ import android.text.Editable; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; -import android.util.LongSparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; @@ -19,12 +18,14 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; @@ -95,9 +96,9 @@ public class FilterCreateActivity extends BaseFragment { private boolean creatingNew; private String newFilterName; private int newFilterFlags; - private ArrayList newAlwaysShow; - private ArrayList newNeverShow; - private LongSparseArray newPinned; + private ArrayList newAlwaysShow; + private ArrayList newNeverShow; + private LongSparseIntArray newPinned; private static final int MAX_NAME_LENGTH = 12; @@ -138,7 +139,7 @@ public class FilterCreateActivity extends BaseFragment { this(dialogFilter, null); } - public FilterCreateActivity(MessagesController.DialogFilter dialogFilter, ArrayList alwaysShow) { + public FilterCreateActivity(MessagesController.DialogFilter dialogFilter, ArrayList alwaysShow) { super(); filter = dialogFilter; if (filter == null) { @@ -320,35 +321,35 @@ public class FilterCreateActivity extends BaseFragment { excludeExpanded = true; updateRows(); } else if (position == includeAddRow || position == excludeAddRow) { - ArrayList arrayList = position == excludeAddRow ? newNeverShow : newAlwaysShow; + ArrayList arrayList = position == excludeAddRow ? newNeverShow : newAlwaysShow; FilterUsersActivity fragment = new FilterUsersActivity(position == includeAddRow, arrayList, newFilterFlags); fragment.setDelegate((ids, flags) -> { newFilterFlags = flags; if (position == excludeAddRow) { newNeverShow = ids; for (int a = 0; a < newNeverShow.size(); a++) { - Integer id = newNeverShow.get(a); + Long id = newNeverShow.get(a); newAlwaysShow.remove(id); - newPinned.remove((long) id); + newPinned.delete(id); } } else { newAlwaysShow = ids; for (int a = 0; a < newAlwaysShow.size(); a++) { newNeverShow.remove(newAlwaysShow.get(a)); } - ArrayList toRemove = new ArrayList<>(); + ArrayList toRemove = new ArrayList<>(); for (int a = 0, N = newPinned.size(); a < N; a++) { - Integer lowerId = (int) newPinned.keyAt(a); - if (lowerId == 0) { + Long did = newPinned.keyAt(a); + if (DialogObject.isEncryptedDialog(did)) { continue; } - if (newAlwaysShow.contains(lowerId)) { + if (newAlwaysShow.contains(did)) { continue; } - toRemove.add(lowerId); + toRemove.add(did); } for (int a = 0, N = toRemove.size(); a < N; a++) { - newPinned.remove(toRemove.get(a)); + newPinned.delete(toRemove.get(a)); } } fillFilterName(); @@ -557,7 +558,7 @@ public class FilterCreateActivity extends BaseFragment { }); } - private static void processAddFilter(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList newAlwaysShow, ArrayList newNeverShow, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, BaseFragment fragment, Runnable onFinish) { + private static void processAddFilter(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList newAlwaysShow, ArrayList newNeverShow, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, BaseFragment fragment, Runnable onFinish) { if (filter.flags != newFilterFlags || hasUserChanged) { filter.pendingUnreadCount = -1; if (resetUnreadCounter) { @@ -579,7 +580,7 @@ public class FilterCreateActivity extends BaseFragment { } } - public static void saveFilterToServer(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList newAlwaysShow, ArrayList newNeverShow, LongSparseArray newPinned, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, boolean progress, BaseFragment fragment, Runnable onFinish) { + public static void saveFilterToServer(MessagesController.DialogFilter filter, int newFilterFlags, String newFilterName, ArrayList newAlwaysShow, ArrayList newNeverShow, LongSparseIntArray newPinned, boolean creatingNew, boolean atBegin, boolean hasUserChanged, boolean resetUnreadCounter, boolean progress, BaseFragment fragment, Runnable onFinish) { if (fragment == null || fragment.getParentActivity() == null) { return; } @@ -606,11 +607,11 @@ public class FilterCreateActivity extends BaseFragment { req.filter.id = filter.id; req.filter.title = newFilterName; MessagesController messagesController = fragment.getMessagesController(); - ArrayList pinArray = new ArrayList<>(); + ArrayList pinArray = new ArrayList<>(); if (newPinned.size() != 0) { for (int a = 0, N = newPinned.size(); a < N; a++) { - int key = (int) newPinned.keyAt(a); - if (key == 0) { + long key = newPinned.keyAt(a); + if (DialogObject.isEncryptedDialog(key)) { continue; } pinArray.add(key); @@ -627,7 +628,7 @@ public class FilterCreateActivity extends BaseFragment { }); } for (int b = 0; b < 3; b++) { - ArrayList fromArray; + ArrayList fromArray; ArrayList toArray; if (b == 0) { fromArray = newAlwaysShow; @@ -644,27 +645,26 @@ public class FilterCreateActivity extends BaseFragment { if (b == 0 && newPinned.indexOfKey(did) >= 0) { continue; } - int lowerId = (int) did; - if (lowerId != 0) { - if (lowerId > 0) { - TLRPC.User user = messagesController.getUser(lowerId); + if (!DialogObject.isEncryptedDialog(did)) { + if (did > 0) { + TLRPC.User user = messagesController.getUser(did); if (user != null) { TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerUser(); - inputPeer.user_id = lowerId; + inputPeer.user_id = did; inputPeer.access_hash = user.access_hash; toArray.add(inputPeer); } } else { - TLRPC.Chat chat = messagesController.getChat(-lowerId); + TLRPC.Chat chat = messagesController.getChat(-did); if (chat != null) { if (ChatObject.isChannel(chat)) { TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChannel(); - inputPeer.channel_id = -lowerId; + inputPeer.channel_id = -did; inputPeer.access_hash = chat.access_hash; toArray.add(inputPeer); } else { TLRPC.InputPeer inputPeer = new TLRPC.TL_inputPeerChat(); - inputPeer.chat_id = -lowerId; + inputPeer.chat_id = -did; toArray.add(inputPeer); } } @@ -890,7 +890,7 @@ public class FilterCreateActivity extends BaseFragment { } case 1: { UserCell userCell = (UserCell) holder.itemView; - Integer id; + Long id; boolean divider; if (position >= includeStartRow && position < includeEndRow) { id = newAlwaysShow.get(position - includeStartRow); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/FilterUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/FilterUsersActivity.java index 90f69a956..cbba8dac2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/FilterUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/FilterUsersActivity.java @@ -29,7 +29,6 @@ import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; -import android.util.SparseArray; import android.util.TypedValue; import android.view.ActionMode; import android.view.Gravity; @@ -46,6 +45,7 @@ import android.widget.ScrollView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; @@ -71,6 +71,7 @@ import org.telegram.ui.Components.RecyclerListView; import java.util.ArrayList; import androidx.annotation.Keep; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -94,11 +95,11 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen private boolean isInclude; private int filterFlags; - private ArrayList initialIds; + private ArrayList initialIds; private boolean searchWas; private boolean searching; - private SparseArray selectedContacts = new SparseArray<>(); + private LongSparseArray selectedContacts = new LongSparseArray<>(); private ArrayList allSpans = new ArrayList<>(); private GroupCreateSpan currentDeletingSpan; @@ -144,7 +145,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen } public interface FilterUsersActivityDelegate { - void didSelectChats(ArrayList ids, int flags); + void didSelectChats(ArrayList ids, int flags); } private class SpansContainer extends ViewGroup { @@ -262,7 +263,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen public void addSpan(final GroupCreateSpan span, boolean animated) { allSpans.add(span); - int uid = span.getUid(); + long uid = span.getUid(); if (uid > Integer.MIN_VALUE + 7) { selectedCount++; } @@ -297,7 +298,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen public void removeSpan(final GroupCreateSpan span) { ignoreScrollEvent = true; - int uid = span.getUid(); + long uid = span.getUid(); if (uid > Integer.MIN_VALUE + 7) { selectedCount--; } @@ -334,7 +335,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen } } - public FilterUsersActivity(boolean include, ArrayList arrayList, int flags) { + public FilterUsersActivity(boolean include, ArrayList arrayList, int flags) { super(); isInclude = include; filterFlags = flags; @@ -631,7 +632,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen if (view instanceof GroupCreateUserCell) { GroupCreateUserCell cell = (GroupCreateUserCell) view; Object object = cell.getObject(); - int id; + long id; if (object instanceof String) { int flag; if (isInclude) { @@ -793,7 +794,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen if (initialIds != null && !initialIds.isEmpty()) { TLObject object; for (int a = 0, N = initialIds.size(); a < N; a++) { - Integer id = initialIds.get(a); + Long id = initialIds.get(a); if (id > 0) { object = getMessagesController().getUser(id); } else { @@ -868,7 +869,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen if (child instanceof GroupCreateUserCell) { GroupCreateUserCell cell = (GroupCreateUserCell) child; Object object = cell.getObject(); - int id; + long id; if (object instanceof String) { String str = (String) object; switch (str) { @@ -917,9 +918,9 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen /*if (!doneButtonVisible || selectedContacts.size() == 0) { return false; }*/ - ArrayList result = new ArrayList<>(); + ArrayList result = new ArrayList<>(); for (int a = 0; a < selectedContacts.size(); a++) { - int uid = selectedContacts.keyAt(a); + long uid = selectedContacts.keyAt(a); if (uid <= Integer.MIN_VALUE + 7) { continue; } @@ -972,12 +973,11 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen ArrayList dialogs = getMessagesController().getAllDialogs(); for (int a = 0, N = dialogs.size(); a < N; a++) { TLRPC.Dialog dialog = dialogs.get(a); - int lowerId = (int) dialog.id; - if (lowerId == 0) { + if (DialogObject.isEncryptedDialog(dialog.id)) { continue; } - if (lowerId > 0) { - TLRPC.User user = getMessagesController().getUser(lowerId); + if (DialogObject.isUserDialog(dialog.id)) { + TLRPC.User user = getMessagesController().getUser(dialog.id); if (user != null) { contacts.add(user); if (UserObject.isUserSelf(user)) { @@ -985,7 +985,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen } } } else { - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + TLRPC.Chat chat = getMessagesController().getChat(-dialog.id); if (chat != null) { contacts.add(chat); } @@ -1163,7 +1163,7 @@ public class FilterUsersActivity extends BaseFragment implements NotificationCen } object = contacts.get(position - usersStartRow); } - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/FilteredSearchView.java b/TMessagesProj/src/main/java/org/telegram/ui/FilteredSearchView.java index 169f4b86b..35d05c1e3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/FilteredSearchView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/FilteredSearchView.java @@ -95,7 +95,7 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente String lastSearchFilterQueryString; FiltersView.MediaFilterData currentSearchFilter; - int currentSearchDialogId; + long currentSearchDialogId; long currentSearchMaxDate; long currentSearchMinDate; String currentSearchString; @@ -444,7 +444,7 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente return fromName == null ? "" : fromName; } - public void search(int dialogId, long minDate, long maxDate, FiltersView.MediaFilterData currentSearchFilter, boolean includeFolder, String query, boolean clearOldResults) { + public void search(long dialogId, long minDate, long maxDate, FiltersView.MediaFilterData currentSearchFilter, boolean includeFolder, String query, boolean clearOldResults) { String currentSearchFilterQueryString = String.format(Locale.ENGLISH, "%d%d%d%d%s%s", dialogId, minDate, maxDate, currentSearchFilter == null ? -1 : currentSearchFilter.filterType, query, includeFolder); boolean filterAndQueryIsSame = lastSearchFilterQueryString != null && lastSearchFilterQueryString.equals(currentSearchFilterQueryString); boolean forceClear = !filterAndQueryIsSame && clearOldResults; @@ -549,14 +549,7 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente MessageObject lastMessage = messages.get(messages.size() - 1); req.offset_id = lastMessage.getId(); req.offset_rate = nextSearchRate; - int id; - if (lastMessage.messageOwner.peer_id.channel_id != 0) { - id = -lastMessage.messageOwner.peer_id.channel_id; - } else if (lastMessage.messageOwner.peer_id.chat_id != 0) { - id = -lastMessage.messageOwner.peer_id.chat_id; - } else { - id = lastMessage.messageOwner.peer_id.user_id; - } + long id = MessageObject.getPeerId(lastMessage.messageOwner.peer_id); req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id); } else { req.offset_rate = 0; @@ -823,7 +816,7 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente emptyView.setKeyboardHeight(keyboardSize, animated); } - public void messagesDeleted(int channelId, ArrayList markAsDeletedMessages) { + public void messagesDeleted(long channelId, ArrayList markAsDeletedMessages) { boolean changed = false; for (int j = 0; j < messages.size(); j++) { MessageObject messageObject = messages.get(j); @@ -984,13 +977,9 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente return; } if (currentSearchFilter.filterType == FiltersView.FILTER_TYPE_MEDIA) { - if (view instanceof DialogCell) { - uiCallback.goToMessage(((DialogCell) view).getMessage()); - } else { - PhotoViewer.getInstance().setParentActivity(parentActivity); - PhotoViewer.getInstance().openPhoto(messages, index, 0, 0, provider); - photoViewerClassGuid = PhotoViewer.getInstance().getClassGuid(); - } + PhotoViewer.getInstance().setParentActivity(parentActivity); + PhotoViewer.getInstance().openPhoto(messages, index, 0, 0, provider); + photoViewerClassGuid = PhotoViewer.getInstance().getClassGuid(); } else if (currentSearchFilter.filterType == FiltersView.FILTER_TYPE_MUSIC || currentSearchFilter.filterType == FiltersView.FILTER_TYPE_VOICE) { if (view instanceof SharedAudioCell) { @@ -1313,7 +1302,7 @@ public class FilteredSearchView extends FrameLayout implements NotificationCente break; case 3: default: - view = new SharedAudioCell(mContext, SharedAudioCell.VIEW_TYPE_GLOBAL_SEARCH) { + view = new SharedAudioCell(mContext, SharedAudioCell.VIEW_TYPE_GLOBAL_SEARCH, null) { @Override public boolean needPlayMessage(MessageObject messageObject) { if (messageObject.isVoice() || messageObject.isRoundVideo()) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/FiltersSetupActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/FiltersSetupActivity.java index c4994678c..bb464ff8d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/FiltersSetupActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/FiltersSetupActivity.java @@ -642,10 +642,10 @@ public class FiltersSetupActivity extends BaseFragment implements NotificationCe filter.pendingUnreadCount = filter.unreadCount = -1; for (int b = 0; b < 2; b++) { ArrayList fromArray = b == 0 ? suggested.filter.include_peers : suggested.filter.exclude_peers; - ArrayList toArray = b == 0 ? filter.alwaysShow : filter.neverShow; + ArrayList toArray = b == 0 ? filter.alwaysShow : filter.neverShow; for (int a = 0, N = fromArray.size(); a < N; a++) { TLRPC.InputPeer peer = fromArray.get(a); - int lowerId; + long lowerId; if (peer.user_id != 0) { lowerId = peer.user_id; } else if (peer.chat_id != 0) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java index 807e9bd67..cae18e2a3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java @@ -41,8 +41,10 @@ import android.text.InputType; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.TextWatcher; -import android.util.LongSparseArray; import android.util.Property; +import android.util.SparseArray; +import android.util.SparseBooleanArray; +import android.util.SparseIntArray; import android.util.TypedValue; import android.view.Gravity; import android.view.HapticFeedbackConstants; @@ -65,6 +67,7 @@ import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.collection.LongSparseArray; import androidx.core.graphics.ColorUtils; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.DiffUtil; @@ -77,6 +80,7 @@ import androidx.viewpager.widget.ViewPager; import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; @@ -89,6 +93,7 @@ import org.telegram.messenger.R; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.UserObject; import org.telegram.messenger.Utilities; +import org.telegram.messenger.support.LongSparseIntArray; import org.telegram.messenger.voip.Instance; import org.telegram.messenger.voip.VoIPService; import org.telegram.tgnet.ConnectionsManager; @@ -155,6 +160,8 @@ import java.util.Locale; import static android.content.Context.AUDIO_SERVICE; +import com.google.android.exoplayer2.util.Log; + public class GroupCallActivity extends BottomSheet implements NotificationCenter.NotificationCenterDelegate, VoIPService.StateListener { public final static int TABLET_LIST_SIZE = 320; @@ -252,7 +259,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter private ArrayList oldParticipants = new ArrayList<>(); private ArrayList oldVideoParticipants = new ArrayList<>(); - private ArrayList oldInvited = new ArrayList<>(); + private ArrayList oldInvited = new ArrayList<>(); private int oldCount; private RLottieDrawable bigMicDrawable; @@ -417,6 +424,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter pressed = true; }; + LongSparseIntArray visiblePeerIds = new LongSparseIntArray(); + public static final Property COLOR_PROGRESS = new AnimationProperties.FloatProperty("colorProgress") { @Override public void setValue(GroupCallActivity object, float value) { @@ -786,7 +795,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter textView.setText(String.format(Locale.US, "%d%%", (int) (vol > 0 ? Math.max(vol, 1) : 0))); VoIPService.getSharedInstance().setParticipantVolume(currentParticipant, currentParticipant.volume); if (finalMove) { - int id = MessageObject.getPeerId(currentParticipant.peer); + long id = MessageObject.getPeerId(currentParticipant.peer); TLObject object; if (id > 0) { object = accountInstance.getMessagesController().getUser(id); @@ -1141,13 +1150,13 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter long justJoinedId = (Long) args[3]; if (justJoinedId != 0) { TLObject object; - if (justJoinedId > 0) { - TLRPC.User user = accountInstance.getMessagesController().getUser((int) justJoinedId); + if (DialogObject.isUserDialog(justJoinedId)) { + TLRPC.User user = accountInstance.getMessagesController().getUser(justJoinedId); if (call.call.participants_count < 250 || UserObject.isContact(user)) { getUndoView().showWithAction(0, UndoView.ACTION_VOIP_USER_JOINED, user, currentChat, null, null); } } else { - TLRPC.Chat chat = accountInstance.getMessagesController().getChat((int) -justJoinedId); + TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-justJoinedId); if (call.call.participants_count < 250 || !ChatObject.isNotInChat(chat)) { getUndoView().showWithAction(0, UndoView.ACTION_VOIP_USER_JOINED, chat, currentChat, null, null); } @@ -1220,7 +1229,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter updateItems(); updateState(isShowing(), false); } - int selfId = MessageObject.getPeerId(selfPeer); + long selfId = MessageObject.getPeerId(selfPeer); if (call != null && chatFull.id == -selfId) { TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId); if (participant != null) { @@ -1242,7 +1251,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } } else if (id == NotificationCenter.didLoadChatAdmins) { - int chatId = (Integer) args[0]; + long chatId = (Long) args[0]; if (chatId == currentChat.id) { updateItems(); updateState(isShowing(), false); @@ -1259,8 +1268,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } } else if (id == NotificationCenter.userInfoDidLoad) { - Integer uid = (Integer) args[0]; - int selfId = MessageObject.getPeerId(selfPeer); + Long uid = (Long) args[0]; + long selfId = MessageObject.getPeerId(selfPeer); if (call != null && selfId == uid) { TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId); if (participant != null) { @@ -1343,8 +1352,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter if (call == null || delayedGroupCallUpdated) { return; } - int self = MessageObject.getPeerId(call.selfPeer); - int dummyPeer = MessageObject.getPeerId(selfPeer); + long self = MessageObject.getPeerId(call.selfPeer); + long dummyPeer = MessageObject.getPeerId(selfPeer); if (self != dummyPeer && call.participants.get(self) != null) { selfPeer = call.selfPeer; } @@ -1582,9 +1591,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter if (VoIPService.getSharedInstance() != null && VoIPService.getSharedInstance().hasFewPeers || scheduleHasFewPeers) { accountSelectCell.setVisibility(View.VISIBLE); accountGap.setVisibility(View.VISIBLE); - int peerId = MessageObject.getPeerId(selfPeer); + long peerId = MessageObject.getPeerId(selfPeer); TLObject object; - if (peerId > 0) { + if (DialogObject.isUserDialog(peerId)) { object = accountInstance.getMessagesController().getUser(peerId); } else { object = accountInstance.getMessagesController().getChat(-peerId); @@ -1852,10 +1861,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter dialog.show(); dialog.setTextColor(Theme.getColor(Theme.key_voipgroup_nameText)); } else { - /*GroupCallRecordAlert alert = new GroupCallRecordAlert(getContext(), currentChat) { TODO uncomment later + GroupCallRecordAlert alert = new GroupCallRecordAlert(getContext(), currentChat, hasVideo) { @Override - protected void onStartRecord(int type) {*/ - int type = 0; //TODO remove after uncomment + protected void onStartRecord(int type) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setDialogButtonColorKey(Theme.key_voipgroup_listeningText); @@ -1873,7 +1881,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter builder.setCheckFocusable(false); EditTextBoldCursor editText = new EditTextBoldCursor(getContext()); - editText.setBackgroundDrawable(Theme.createEditTextDrawable(getContext(), true)); + editText.setBackgroundDrawable(Theme.createEditTextDrawable(getContext(), Theme.getColor(Theme.key_voipgroup_windowBackgroundWhiteInputField), Theme.getColor(Theme.key_voipgroup_windowBackgroundWhiteInputFieldActivated))); LinearLayout linearLayout = new LinearLayout(getContext()); linearLayout.setOrientation(LinearLayout.VERTICAL); @@ -1921,9 +1929,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter if (editText != null) { editText.requestFocus(); } - /*} - }; TODO uncomment later - alert.show();*/ + } + }; + alert.show(); } } else if (id == permission_item) { changingPermissions = true; @@ -2267,7 +2275,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter tabletVideoGridView.setVisibility(isTabletMode ? View.VISIBLE : View.GONE); tabletGridAdapter.setVisibility(tabletVideoGridView, isTabletMode && !renderersContainer.inFullscreenMode, true); - listViewVideoVisibility = (isTabletMode && renderersContainer.inFullscreenMode) || !isTabletMode; + listViewVideoVisibility = !isTabletMode || renderersContainer.inFullscreenMode; boolean fullscreenListVisibility = !isTabletMode && renderersContainer.inFullscreenMode; fullscreenAdapter.setVisibility(fullscreenUsersListView, fullscreenListVisibility); @@ -2392,9 +2400,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; layoutParams.rightMargin = 0; } - // - // actionBar if (isLandscapeMode && !isTabletMode) { layoutParams = (LayoutParams) actionBar.getLayoutParams(); layoutParams.rightMargin = AndroidUtilities.dp(90); @@ -2414,7 +2420,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter layoutParams = (LayoutParams) actionBarShadow.getLayoutParams(); layoutParams.rightMargin = 0; } - // + layoutParams = (LayoutParams) fullscreenUsersListView.getLayoutParams(); if (isLandscapeMode) { if (((LinearLayoutManager) fullscreenUsersListView.getLayoutManager()).getOrientation() != RecyclerView.VERTICAL) { @@ -3050,6 +3056,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter listView = new RecyclerListView(context) { + private final LongSparseIntArray visiblePeerTmp = new LongSparseIntArray(); + @Override public boolean drawChild(Canvas canvas, View child, long drawingTime) { if (child == scrimView) { @@ -3064,6 +3072,12 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter float inMinTop = Float.MAX_VALUE; boolean animateBackground = itemAnimator.outMinTop != Float.MAX_VALUE; + visiblePeerTmp.clear(); + for (int i = 0; i < visiblePeerIds.size(); i++){ + visiblePeerTmp.put(visiblePeerIds.keyAt(i), 1); + } + visiblePeerIds.clear(); + boolean visiblePeersChanged = false; for (int a = 0, N = getChildCount(); a < N; a++) { View child = getChildAt(a); ViewHolder holder = findContainingViewHolder(child); @@ -3071,6 +3085,15 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter continue; } + if (holder.getItemViewType() == 1 && holder.itemView instanceof GroupCallUserCell) { + GroupCallUserCell userCell = (GroupCallUserCell) holder.itemView; + visiblePeerIds.append(userCell.getPeerId(), 1); + if (visiblePeerTmp.get(userCell.getPeerId(), 0) == 0) { + visiblePeersChanged = true; + } else { + visiblePeerTmp.delete(userCell.getPeerId()); + } + } if (animateBackground) { if (!itemAnimator.removingHolders.contains(holder)) { inMinTop = Math.min(inMinTop, Math.max(0, child.getTop())); @@ -3082,6 +3105,14 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } + if (visiblePeerTmp.size() > 0) { + visiblePeersChanged = true; + } + + if (visiblePeersChanged) { + updateSubtitle(); + } + float minTop, maxBottom; if (animateBackground) { minTop = itemAnimator.outMinTop * (1f - itemAnimator.animationProgress) + inMinTop * (itemAnimator.animationProgress); @@ -3243,7 +3274,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter parentActivity.switchToAccount(currentAccount, true); Bundle args = new Bundle(); - args.putInt("user_id", cell.getUser().id); + args.putLong("user_id", cell.getUser().id); if (cell.hasAvatarSet()) { args.putBoolean("expandPhoto", true); } @@ -3268,7 +3299,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } @Override - public void inviteUser(int id) { + public void inviteUser(long id) { inviteUserToCall(id, true); } @@ -4151,8 +4182,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter if (muteButtonState == MUTE_BUTTON_STATE_MUTED_BY_ADMIN) { TLRPC.TL_groupCallParticipant participant = call.participants.get(MessageObject.getPeerId(selfPeer)); TLObject object; - int peerId = MessageObject.getPeerId(participant.peer); - if (peerId > 0) { + long peerId = MessageObject.getPeerId(participant.peer); + if (DialogObject.isUserDialog(peerId)) { object = accountInstance.getMessagesController().getUser(peerId); } else { object = accountInstance.getMessagesController().getChat(-peerId); @@ -4350,9 +4381,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter adminItem = otherItem.addSubItem(admin_can_speak_item, 0, LocaleController.getString("VoipGroupOnlyAdminsCanSpeak", R.string.VoipGroupOnlyAdminsCanSpeak), true); adminItem.updateSelectorBackground(false, true); - everyoneItem.setCheckColor(Theme.getColor(Theme.key_voipgroup_checkMenu)); + everyoneItem.setCheckColor(Theme.key_voipgroup_checkMenu); everyoneItem.setColors(Theme.getColor(Theme.key_voipgroup_checkMenu), Theme.getColor(Theme.key_voipgroup_checkMenu)); - adminItem.setCheckColor(Theme.getColor(Theme.key_voipgroup_checkMenu)); + adminItem.setCheckColor(Theme.key_voipgroup_checkMenu); adminItem.setColors(Theme.getColor(Theme.key_voipgroup_checkMenu), Theme.getColor(Theme.key_voipgroup_checkMenu)); Paint soundDrawablePaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -5397,45 +5428,41 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter SpannableStringBuilder spannableStringBuilder = null; int speakingIndex = 0; for (int i = 0; i < call.currentSpeakingPeers.size(); i++) { - int key = call.currentSpeakingPeers.keyAt(i); + long key = call.currentSpeakingPeers.keyAt(i); TLRPC.TL_groupCallParticipant participant = call.currentSpeakingPeers.get(key); - if (participant.self || renderersContainer.isVisible(participant)) { + if (participant.self || renderersContainer.isVisible(participant) || visiblePeerIds.get(key, 0) == 1) { continue; } - int peerId = MessageObject.getPeerId(participant.peer); - long diff = SystemClock.uptimeMillis() - participant.lastSpeakTime; - boolean newSpeaking = diff < 500; - if (newSpeaking) { - if (spannableStringBuilder == null) { - spannableStringBuilder = new SpannableStringBuilder(); + long peerId = MessageObject.getPeerId(participant.peer); + if (spannableStringBuilder == null) { + spannableStringBuilder = new SpannableStringBuilder(); + } + if (speakingIndex < 2) { + TLRPC.User user = peerId > 0 ? MessagesController.getInstance(currentAccount).getUser(peerId) : null; + TLRPC.Chat chat = peerId <= 0 ? MessagesController.getInstance(currentAccount).getChat(peerId) : null; + if (user == null && chat == null) { + continue; } - if (speakingIndex < 2) { - TLRPC.User user = peerId > 0 ? MessagesController.getInstance(currentAccount).getUser(peerId) : null; - TLRPC.Chat chat = peerId <= 0 ? MessagesController.getInstance(currentAccount).getChat(peerId) : null; - if (user == null && chat == null) { - continue; - } - if (speakingIndex != 0) { - spannableStringBuilder.append(", "); - } - if (user != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - spannableStringBuilder.append(UserObject.getFirstName(user), new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0); - } else { - spannableStringBuilder.append(UserObject.getFirstName(user)); - } + if (speakingIndex != 0) { + spannableStringBuilder.append(", "); + } + if (user != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + spannableStringBuilder.append(UserObject.getFirstName(user), new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0); } else { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - spannableStringBuilder.append(chat.title, new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0); - } else { - spannableStringBuilder.append(chat.title); - } + spannableStringBuilder.append(UserObject.getFirstName(user)); + } + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + spannableStringBuilder.append(chat.title, new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0); + } else { + spannableStringBuilder.append(chat.title); } } - speakingIndex++; - if (speakingIndex == 2) { - break; - } + } + speakingIndex++; + if (speakingIndex == 2) { + break; } } boolean drawStatus; @@ -5773,7 +5800,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } - private void inviteUserToCall(int id, boolean shouldAdd) { + private void inviteUserToCall(long id, boolean shouldAdd) { if (call == null) { return; } @@ -6478,7 +6505,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter buttonsContainer.invalidate(); } - private static void processOnLeave(ChatObject.Call call, boolean discard, int selfId, Runnable onLeave) { + private static void processOnLeave(ChatObject.Call call, boolean discard, long selfId, Runnable onLeave) { if (VoIPService.getSharedInstance() != null) { VoIPService.getSharedInstance().hangUp(discard ? 1 : 0); } @@ -6517,7 +6544,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter TLRPC.Chat currentChat = service.getChat(); ChatObject.Call call = service.groupCall; - int selfId = service.getSelfId(); + long selfId = service.getSelfId(); if (!ChatObject.canManageCalls(currentChat)) { processOnLeave(call, false, selfId, onLeave); return; @@ -6604,7 +6631,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter private AnimatorSet scrimAnimatorSet; private ActionBarPopupWindow scrimPopupWindow; - private void processSelectedOption(TLRPC.TL_groupCallParticipant participant, int peerId, int option) { + private void processSelectedOption(TLRPC.TL_groupCallParticipant participant, long peerId, int option) { VoIPService voIPService = VoIPService.getSharedInstance(); if (voIPService == null) { return; @@ -6711,9 +6738,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter parentActivity.switchToAccount(currentAccount, true); Bundle args = new Bundle(); if (peerId > 0) { - args.putInt("user_id", peerId); + args.putLong("user_id", peerId); } else { - args.putInt("chat_id", -peerId); + args.putLong("chat_id", -peerId); } parentActivity.presentFragment(new ChatActivity(args)); dismiss(); @@ -6728,9 +6755,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } Bundle args = new Bundle(); if (peerId > 0) { - args.putInt("user_id", peerId); + args.putLong("user_id", peerId); } else { - args.putInt("chat_id", -peerId); + args.putLong("chat_id", -peerId); } parentActivity.presentFragment(new ChatActivity(args)); dismiss(); @@ -6799,7 +6826,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter return false; } view = new GroupCallUserCell(groupCallGridCell.getContext()); - int selfPeerId = MessageObject.getPeerId(selfPeer); + long selfPeerId = MessageObject.getPeerId(selfPeer); view.setData(accountInstance, groupCallGridCell.getParticipant().participant, call, selfPeerId, null, false); hasScrimAnchorView = false; scrimGridView = groupCallGridCell; @@ -6816,7 +6843,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter return false; } view = new GroupCallUserCell(groupCallFullscreenCell.getContext()); - int selfPeerId = MessageObject.getPeerId(selfPeer); + long selfPeerId = MessageObject.getPeerId(selfPeer); view.setData(accountInstance, groupCallFullscreenCell.getParticipant(), call, selfPeerId, null, false); hasScrimAnchorView = false; scrimFullscreenView = groupCallFullscreenCell; @@ -6925,7 +6952,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter scrollView.setClipToPadding(false); popupLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); - int peerId = MessageObject.getPeerId(participant.peer); + long peerId = MessageObject.getPeerId(participant.peer); ArrayList items = new ArrayList<>(2); ArrayList icons = new ArrayList<>(2); @@ -7608,8 +7635,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } if (participant != null) { - int peerId = MessageObject.getPeerId(participant.peer); - int selfPeerId = MessageObject.getPeerId(selfPeer); + long peerId = MessageObject.getPeerId(participant.peer); + long selfPeerId = MessageObject.getPeerId(selfPeer); TLRPC.FileLocation uploadingAvatar = (peerId == selfPeerId && avatarUpdaterDelegate != null) ? avatarUpdaterDelegate.avatar : null; float uploadingProgress = (uploadingAvatar != null) ? avatarUpdaterDelegate.uploadingProgress : 1f; boolean animated = userCell.getParticipant() != null && MessageObject.getPeerId(userCell.getParticipant().peer) == peerId; @@ -7620,7 +7647,7 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } case 2: { GroupCallInvitedCell invitedCell = (GroupCallInvitedCell) holder.itemView; - Integer uid; + Long uid; int row = position - invitedStartRow; if (delayedGroupCallUpdated) { if (row >= 0 && row < oldInvited.size()) { @@ -7662,8 +7689,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter } } if (participant != null) { - int peerId = MessageObject.getPeerId(participant.participant.peer); - int selfPeerId = MessageObject.getPeerId(selfPeer); + long peerId = MessageObject.getPeerId(participant.participant.peer); + long selfPeerId = MessageObject.getPeerId(selfPeer); TLRPC.FileLocation uploadingAvatar = (peerId == selfPeerId && avatarUpdaterDelegate != null) ? avatarUpdaterDelegate.avatar : null; float uploadingProgress = (uploadingAvatar != null) ? avatarUpdaterDelegate.uploadingProgress : 1f; boolean animated = userCell.getParticipant() != null && userCell.getParticipant().equals(participant); @@ -7890,8 +7917,8 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter return MessageObject.getPeerId(oldItem.peer) == MessageObject.getPeerId(newItem.peer) && (oldItemPosition == newItemPosition || oldItem.lastActiveDate == oldItem.active_date); } else if (newItemPosition >= listAdapter.invitedStartRow && newItemPosition < listAdapter.invitedEndRow && oldItemPosition >= oldInvitedStartRow && oldItemPosition < oldInvitedEndRow) { - Integer oldItem = oldInvited.get(oldItemPosition - oldInvitedStartRow); - Integer newItem = call.invitedUsers.get(newItemPosition - listAdapter.invitedStartRow); + Long oldItem = oldInvited.get(oldItemPosition - oldInvitedStartRow); + Long newItem = call.invitedUsers.get(newItemPosition - listAdapter.invitedStartRow); return oldItem.equals(newItem); } return false; @@ -7973,9 +8000,9 @@ public class GroupCallActivity extends BottomSheet implements NotificationCenter private TLRPC.FileLocation avatar; private ImageLocation uploadingImageLocation; - private final int peerId; + private final long peerId; - private AvatarUpdaterDelegate(int peerId) { + private AvatarUpdaterDelegate(long peerId) { this.peerId = peerId; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallTabletGridAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallTabletGridAdapter.java index 1e21d5f5f..eb16953bf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallTabletGridAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallTabletGridAdapter.java @@ -130,7 +130,7 @@ public class GroupCallTabletGridAdapter extends RecyclerListView.SelectionAdapte } } - public void scrollToPeerId(int peerId, RecyclerListView fullscreenUsersListView) { + public void scrollToPeerId(long peerId, RecyclerListView fullscreenUsersListView) { // for (int i = 0; i < participants.size(); i++) { // if (peerId == MessageObject.getPeerId(participants.get(i).peer)) { // ((LinearLayoutManager) fullscreenUsersListView.getLayoutManager()).scrollToPositionWithOffset(i, AndroidUtilities.dp(13)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java index 160acfaa5..d61205873 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java @@ -24,6 +24,7 @@ import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import androidx.annotation.Keep; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -34,7 +35,6 @@ import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; -import android.util.SparseArray; import android.util.TypedValue; import android.view.ActionMode; import android.view.Gravity; @@ -54,6 +54,7 @@ import android.widget.ScrollView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.UserObject; @@ -110,11 +111,11 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen private int measuredContainerHeight; private int containerHeight; - private int chatId; - private int channelId; + private long chatId; + private long channelId; private TLRPC.ChatFull info; - private SparseArray ignoreUsers; + private LongSparseArray ignoreUsers; private int maxCount = getMessagesController().maxMegagroupCount; private int chatType = ChatObject.CHAT_TYPE_CHAT; @@ -125,7 +126,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen private boolean searchWas; private boolean searching; private int chatAddType; - private SparseArray selectedContacts = new SparseArray<>(); + private LongSparseArray selectedContacts = new LongSparseArray<>(); private ArrayList allSpans = new ArrayList<>(); private GroupCreateSpan currentDeletingSpan; @@ -138,7 +139,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen private PermanentLinkBottomSheet sharedLinkBottomSheet; public interface GroupCreateActivityDelegate { - void didSelectUsers(ArrayList ids); + void didSelectUsers(ArrayList ids); } public interface GroupCreateActivityImportDelegate { @@ -352,7 +353,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen isNeverShare = args.getBoolean("isNeverShare", false); addToGroup = args.getBoolean("addToGroup", false); chatAddType = args.getInt("chatAddType", 0); - chatId = args.getInt("chatId"); + chatId = args.getLong("chatId"); channelId = args.getInt("channelId"); if (isAlwaysShare || isNeverShare || addToGroup) { maxCount = 0; @@ -682,7 +683,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } else if (view instanceof GroupCreateUserCell) { GroupCreateUserCell cell = (GroupCreateUserCell) view; Object object = cell.getObject(); - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { @@ -895,7 +896,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } } - public void setIgnoreUsers(SparseArray users) { + public void setIgnoreUsers(LongSparseArray users) { ignoreUsers = users; } @@ -926,7 +927,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen if (child instanceof GroupCreateUserCell) { GroupCreateUserCell cell = (GroupCreateUserCell) child; Object object = cell.getObject(); - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { @@ -975,7 +976,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } StringBuilder stringBuilder = new StringBuilder(); for (int a = 0; a < selectedContacts.size(); a++) { - int uid = selectedContacts.keyAt(a); + long uid = selectedContacts.keyAt(a); TLRPC.User user = getMessagesController().getUser(uid); if (user == null) { continue; @@ -987,7 +988,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } TLRPC.Chat chat = getMessagesController().getChat(chatId != 0 ? chatId : channelId); if (selectedContacts.size() > 5) { - SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(AndroidUtilities.replaceTags(LocaleController.formatString("AddMembersAlertNamesText", R.string.AddMembersAlertNamesText, LocaleController.formatPluralString("Members", selectedContacts.size()), chat.title))); + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(AndroidUtilities.replaceTags(LocaleController.formatString("AddMembersAlertNamesText", R.string.AddMembersAlertNamesText, LocaleController.formatPluralString("Members", selectedContacts.size()), chat == null ? "" : chat.title))); String countString = String.format("%d", selectedContacts.size()); int index = TextUtils.indexOf(spannableStringBuilder, countString); if (index >= 0) { @@ -995,7 +996,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen } builder.setMessage(spannableStringBuilder); } else { - builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("AddMembersAlertNamesText", R.string.AddMembersAlertNamesText, stringBuilder, chat.title))); + builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("AddMembersAlertNamesText", R.string.AddMembersAlertNamesText, stringBuilder, chat == null ? "" : chat.title))); } CheckBoxCell[] cells = new CheckBoxCell[1]; if (!ChatObject.isChannel(chat)) { @@ -1032,7 +1033,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen getMessagesController().addUsersToChannel(chatId, result, null); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); Bundle args2 = new Bundle(); - args2.putInt("chat_id", chatId); + args2.putLong("chat_id", chatId); presentFragment(new ChatActivity(args2), true); } else { if (!doneButtonVisible || selectedContacts.size() == 0) { @@ -1041,7 +1042,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen if (addToGroup) { onAddToGroupDone(0); } else { - ArrayList result = new ArrayList<>(); + ArrayList result = new ArrayList<>(); for (int a = 0; a < selectedContacts.size(); a++) { result.add(selectedContacts.keyAt(a)); } @@ -1052,7 +1053,12 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen finishFragment(); } else { Bundle args = new Bundle(); - args.putIntegerArrayList("result", result); + + long[] array = new long[result.size()]; + for (int a = 0; a < array.length; a++) { + array[a] = result.get(a); + } + args.putLongArray("result", array); args.putInt("chatType", chatType); args.putBoolean("forImport", forImport); presentFragment(new GroupCreateFinalActivity(args)); @@ -1164,11 +1170,10 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ArrayList dialogs = getMessagesController().getAllDialogs(); for (int a = 0, N = dialogs.size(); a < N; a++) { TLRPC.Dialog dialog = dialogs.get(a); - int lowerId = (int) dialog.id; - if (lowerId >= 0) { + if (!DialogObject.isChatDialog(dialog.id)) { continue; } - TLRPC.Chat chat = getMessagesController().getChat(-lowerId); + TLRPC.Chat chat = getMessagesController().getChat(-dialog.id); if (chat == null || chat.migrated_to != null || ChatObject.isChannel(chat) && !chat.megagroup) { continue; } @@ -1388,7 +1393,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen object = contacts.get(position - usersStartRow); } cell.setObject(object, name, username); - int id; + long id; if (object instanceof TLRPC.User) { id = ((TLRPC.User) object).id; } else if (object instanceof TLRPC.Chat) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java index bba4a4d89..bd666feac 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCreateFinalActivity.java @@ -102,7 +102,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati private TLRPC.InputFile inputVideo; private String inputVideoPath; private double videoTimestamp; - private ArrayList selectedContacts; + private ArrayList selectedContacts; private boolean createAfterUpload; private boolean donePressed; private ImageUpdater imageUpdater; @@ -122,7 +122,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati public interface GroupCreateFinalActivityDelegate { void didStartChatCreation(); - void didFinishChatCreation(GroupCreateFinalActivity fragment, int chatId); + void didFinishChatCreation(GroupCreateFinalActivity fragment, long chatId); void didFailChatCreation(); } @@ -146,10 +146,16 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati imageUpdater = new ImageUpdater(true); imageUpdater.parentFragment = this; imageUpdater.setDelegate(this); - selectedContacts = getArguments().getIntegerArrayList("result"); - final ArrayList usersToLoad = new ArrayList<>(); + long[] contacts = getArguments().getLongArray("result"); + if (contacts != null) { + selectedContacts = new ArrayList<>(contacts.length); + for (int a = 0; a < contacts.length; a++) { + selectedContacts.add(contacts[a]); + } + } + final ArrayList usersToLoad = new ArrayList<>(); for (int a = 0; a < selectedContacts.size(); a++) { - Integer uid = selectedContacts.get(a); + Long uid = selectedContacts.get(a); if (getMessagesController().getUser(uid) == null) { usersToLoad.add(uid); } @@ -741,7 +747,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati } if (editText != null) { String text = editText.getText().toString(); - if (text != null && text.length() != 0) { + if (text.length() != 0) { args.putString("nameTextView", text); } } @@ -797,17 +803,17 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati } } else if (id == NotificationCenter.chatDidCreated) { reqId = 0; - int chat_id = (Integer) args[0]; + long chatId = (Long) args[0]; if (delegate != null) { - delegate.didFinishChatCreation(this, chat_id); + delegate.didFinishChatCreation(this, chatId); } else { NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats); Bundle args2 = new Bundle(); - args2.putInt("chat_id", chat_id); + args2.putLong("chat_id", chatId); presentFragment(new ChatActivity(args2), true); } if (inputPhoto != null || inputVideo != null) { - getMessagesController().changeChatAvatar(chat_id, null, inputPhoto, inputVideo, videoTimestamp, inputVideoPath, avatar, avatarBig, null); + getMessagesController().changeChatAvatar(chatId, null, inputPhoto, inputVideo, videoTimestamp, inputVideoPath, avatar, avatarBig, null); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupInviteActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupInviteActivity.java index c4a5917d7..c073cf3f3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupInviteActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupInviteActivity.java @@ -18,7 +18,6 @@ import android.widget.FrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.LocaleController; -import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.FileLog; @@ -49,7 +48,7 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen private RecyclerListView listView; private EmptyTextProgressView emptyView; - private int chat_id; + private long chatId; private boolean loading; private TLRPC.TL_chatInviteExported invite; @@ -61,9 +60,9 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen private int shadowRow; private int rowCount; - public GroupInviteActivity(int cid) { + public GroupInviteActivity(long cid) { super(); - chat_id = cid; + chatId = cid; } @Override @@ -71,7 +70,7 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen super.onFragmentCreate(); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.chatInfoDidLoad); - MessagesController.getInstance(currentAccount).loadFullChat(chat_id, classGuid, true); + getMessagesController().loadFullChat(chatId, classGuid, true); loading = true; rowCount = 0; @@ -166,8 +165,8 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen if (id == NotificationCenter.chatInfoDidLoad) { TLRPC.ChatFull info = (TLRPC.ChatFull) args[0]; int guid = (int) args[1]; - if (info.id == chat_id && guid == classGuid) { - invite = MessagesController.getInstance(currentAccount).getExportedInvite(chat_id); + if (info.id == chatId && guid == classGuid) { + invite = getMessagesController().getExportedInvite(chatId); if (invite == null) { generateLink(false); } else { @@ -191,7 +190,7 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen private void generateLink(final boolean newRequest) { loading = true; TLRPC.TL_messages_exportChatInvite req = new TLRPC.TL_messages_exportChatInvite(); - req.peer = MessagesController.getInstance(currentAccount).getInputPeer(-chat_id); + req.peer = getMessagesController().getInputPeer(-chatId); final int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (error == null) { invite = (TLRPC.TL_chatInviteExported) response; @@ -273,7 +272,7 @@ public class GroupInviteActivity extends BaseFragment implements NotificationCen privacyCell.setText(""); privacyCell.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); } else if (position == linkInfoRow) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chat_id); + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (ChatObject.isChannel(chat) && !chat.megagroup) { privacyCell.setText(LocaleController.getString("ChannelLinkInfo", R.string.ChannelLinkInfo)); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupStickersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupStickersActivity.java index 114ec3cfe..0c050860f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupStickersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupStickersActivity.java @@ -93,7 +93,7 @@ public class GroupStickersActivity extends BaseFragment implements NotificationC private TLRPC.TL_messages_stickerSet selectedStickerSet; private TLRPC.ChatFull info; - private int chatId; + private long chatId; private boolean donePressed; @@ -108,7 +108,7 @@ public class GroupStickersActivity extends BaseFragment implements NotificationC private final static int done_button = 1; - public GroupStickersActivity(int id) { + public GroupStickersActivity(long id) { super(); chatId = id; } @@ -696,7 +696,7 @@ public class GroupStickersActivity extends BaseFragment implements NotificationC @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: case 5: @@ -715,6 +715,7 @@ public class GroupStickersActivity extends BaseFragment implements NotificationC view.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); break; case 4: + default: view = new HeaderCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index 93ae99e48..d2b4af000 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -80,6 +80,7 @@ import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsLoadingObserver; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; @@ -588,7 +589,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa drawerLayoutContainer.closeDrawer(false); } else if (id == 11) { Bundle args = new Bundle(); - args.putInt("user_id", UserConfig.getInstance(currentAccount).getClientUserId()); + args.putLong("user_id", UserConfig.getInstance(currentAccount).getClientUserId()); presentFragment(new ChatActivity(args)); drawerLayoutContainer.closeDrawer(false); } else if (id == 12) { @@ -781,7 +782,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } break; case "settings": { - args.putInt("user_id", UserConfig.getInstance(currentAccount).clientUserId); + args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId); ProfileActivity settings = new ProfileActivity(args); actionBarLayout.addFragmentToStack(settings); settings.restoreSelfArgs(savedInstanceState); @@ -886,7 +887,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa private void openSettings(boolean expanded) { Bundle args = new Bundle(); - args.putInt("user_id", UserConfig.getInstance(currentAccount).clientUserId); + args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId); if (expanded) { args.putBoolean("expandPhoto", true); } @@ -896,12 +897,18 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } private void checkSystemBarColors() { + checkSystemBarColors(true, true); + } + + private void checkSystemBarColors(boolean checkStatusBar, boolean checkNavigationBar) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - int color = Theme.getColor(Theme.key_actionBarDefault, null, true); - AndroidUtilities.setLightStatusBar(getWindow(), color == Color.WHITE); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + if (checkStatusBar) { + int color = Theme.getColor(Theme.key_actionBarDefault, null, true); + AndroidUtilities.setLightStatusBar(getWindow(), color == Color.WHITE); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && checkNavigationBar) { final Window window = getWindow(); - color = Theme.getColor(Theme.key_windowBackgroundGray, null, true); + int color = Theme.getColor(Theme.key_windowBackgroundGray, null, true); if (window.getNavigationBarColor() != color) { window.setNavigationBarColor(color); final float brightness = AndroidUtilities.computePerceivedBrightness(color); @@ -909,7 +916,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } } - if (SharedConfig.noStatusBar) { + if (SharedConfig.noStatusBar && Build.VERSION.SDK_INT >= 21 && checkStatusBar) { getWindow().setStatusBarColor(0); } } @@ -1230,8 +1237,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } boolean pushOpened = false; - int push_user_id = 0; - int push_chat_id = 0; + long push_user_id = 0; + long push_chat_id = 0; int push_enc_id = 0; int push_msg_id = 0; int open_settings = 0; @@ -1558,7 +1565,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa String code = null; TLRPC.TL_wallPaper wallPaper = null; Integer messageId = null; - Integer channelId = null; + Long channelId = null; Integer threadId = null; Integer commentId = null; int videoTimestamp = -1; @@ -1698,7 +1705,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else if (path.startsWith("c/")) { List segments = data.getPathSegments(); if (segments.size() == 3) { - channelId = Utilities.parseInt(segments.get(1)); + channelId = Utilities.parseLong(segments.get(1)); messageId = Utilities.parseInt(segments.get(2)); if (messageId == 0 || channelId == 0) { messageId = null; @@ -1784,7 +1791,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa url = url.replace("tg:privatepost", "tg://telegram.org").replace("tg://privatepost", "tg://telegram.org"); data = Uri.parse(url); messageId = Utilities.parseInt(data.getQueryParameter("post")); - channelId = Utilities.parseInt(data.getQueryParameter("channel")); + channelId = Utilities.parseLong(data.getQueryParameter("channel")); if (messageId == 0 || channelId == 0) { messageId = null; channelId = null; @@ -2080,7 +2087,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa break; } } - int userId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data.DATA4)); + long userId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.DATA4)); NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats); push_user_id = userId; String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)); @@ -2102,8 +2109,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else if (intent.getAction().equals("new_dialog")) { open_new_dialog = 1; } else if (intent.getAction().startsWith("com.tmessages.openchat")) { - int chatId = intent.getIntExtra("chatId", 0); - int userId = intent.getIntExtra("userId", 0); + long chatId = intent.getLongExtra("chatId", 0); + long userId = intent.getLongExtra("userId", 0); int encId = intent.getIntExtra("encId", 0); int widgetId = intent.getIntExtra("appWidgetId", 0); if (widgetId != 0) { @@ -2165,7 +2172,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } else { Bundle args = new Bundle(); - args.putInt("user_id", push_user_id); + args.putLong("user_id", push_user_id); if (push_msg_id != 0) { args.putInt("message_id", push_msg_id); } @@ -2179,7 +2186,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } else if (push_chat_id != 0) { Bundle args = new Bundle(); - args.putInt("chat_id", push_chat_id); + args.putLong("chat_id", push_chat_id); if (push_msg_id != 0) { args.putInt("message_id", push_msg_id); } @@ -2215,7 +2222,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } else if (showPlayer) { if (!actionBarLayout.fragmentsStack.isEmpty()) { BaseFragment fragment = actionBarLayout.fragmentsStack.get(0); - fragment.showDialog(new AudioPlayerAlert(this)); + fragment.showDialog(new AudioPlayerAlert(this, null)); } pushOpened = false; } else if (showLocations) { @@ -2230,7 +2237,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa final long dialog_id = info.messageObject.getDialogId(); locationActivity.setDelegate((location, live, notify, scheduleDate) -> SendMessagesHelper.getInstance(intentAccount[0]).sendMessage(location, dialog_id, null, null, null, null, notify, scheduleDate)); presentFragment(locationActivity); - })); + }, null)); } pushOpened = false; } else if (exportingChatUri != null) { @@ -2239,7 +2246,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa AndroidUtilities.runOnUIThread(() -> { if (!actionBarLayout.fragmentsStack.isEmpty()) { BaseFragment fragment = actionBarLayout.fragmentsStack.get(0); - fragment.showDialog(new StickersAlert(this, importingStickersSoftware, importingStickers, importingStickersEmoji)); + fragment.showDialog(new StickersAlert(this, importingStickersSoftware, importingStickers, importingStickersEmoji, null)); } }); pushOpened = false; @@ -2260,7 +2267,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa boolean closePrevious = false; if (open_settings == 1) { Bundle args = new Bundle(); - args.putInt("user_id", UserConfig.getInstance(currentAccount).clientUserId); + args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId); fragment = new ProfileActivity(args); } else if (open_settings == 2) { fragment = new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC); @@ -2554,7 +2561,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } if (!arrayList.isEmpty()) { Bundle args = new Bundle(); - args.putInt("chat_id", (int) -arrayList.get(0).getDialogId()); + args.putLong("chat_id", -arrayList.get(0).getDialogId()); args.putInt("message_id", Math.max(1, messageId)); ChatActivity chatActivity = new ChatActivity(args); chatActivity.setThreadMessages(arrayList, chat, req.msg_id, res.read_inbox_max_id, res.read_outbox_max_id); @@ -2726,7 +2733,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa final String message, final boolean hasUrl, final Integer messageId, - final Integer channelId, + final Long channelId, final Integer threadId, final Integer commentId, final String game, @@ -2801,20 +2808,16 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa inputMediaGame.id = new TLRPC.TL_inputGameShortName(); inputMediaGame.id.short_name = game; inputMediaGame.id.bot_id = MessagesController.getInstance(intentAccount).getInputUser(res.users.get(0)); - SendMessagesHelper.getInstance(intentAccount).sendGame(MessagesController.getInstance(intentAccount).getInputPeer((int) did), inputMediaGame, 0, 0); + SendMessagesHelper.getInstance(intentAccount).sendGame(MessagesController.getInstance(intentAccount).getInputPeer(did), inputMediaGame, 0, 0); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - int lower_part = (int) did; - int high_id = (int) (did >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); } else { - args1.putInt("enc_id", high_id); + args1.putLong("chat_id", -did); } if (MessagesController.getInstance(intentAccount).checkCanOpenChat(args1, fragment1)) { NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats); @@ -2866,10 +2869,10 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa long did = dids.get(0); Bundle args12 = new Bundle(); args12.putBoolean("scrollToTopOnResume", true); - args12.putInt("chat_id", -(int) did); + args12.putLong("chat_id", -did); if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args12, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats); - MessagesController.getInstance(intentAccount).addUserToChat(-(int) did, user, 0, botChat, null, null); + MessagesController.getInstance(intentAccount).addUserToChat(-did, user, 0, botChat, null, null); actionBarLayout.presentFragment(new ChatActivity(args12), true, false, true, false); } }); @@ -2879,10 +2882,10 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa boolean isBot = false; Bundle args = new Bundle(); if (!res.chats.isEmpty()) { - args.putInt("chat_id", res.chats.get(0).id); + args.putLong("chat_id", res.chats.get(0).id); dialog_id = -res.chats.get(0).id; } else { - args.putInt("user_id", res.users.get(0).id); + args.putLong("user_id", res.users.get(0).id); dialog_id = res.users.get(0).id; } if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) { @@ -2973,7 +2976,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa chats.add(invite.chat); MessagesStorage.getInstance(intentAccount).putUsersAndChats(null, chats, false, true); Bundle args = new Bundle(); - args.putInt("chat_id", invite.chat.id); + args.putLong("chat_id", invite.chat.id); if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { boolean[] canceled = new boolean[1]; progressDialog.setOnCancelListener(dialog -> canceled[0] = true); @@ -3064,7 +3067,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa MessagesController.getInstance(intentAccount).putUsers(updates.users, false); MessagesController.getInstance(intentAccount).putChats(updates.chats, false); Bundle args = new Bundle(); - args.putInt("chat_id", chat.id); + args.putLong("chat_id", chat.id); if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) { ChatActivity fragment = new ChatActivity(args); NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats); @@ -3097,7 +3100,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa StickersAlert alert; if (fragment instanceof ChatActivity) { ChatActivity chatActivity = (ChatActivity) fragment; - alert = new StickersAlert(LaunchActivity.this, fragment, stickerset, null, chatActivity.getChatActivityEnterViewForStickers()); + alert = new StickersAlert(LaunchActivity.this, fragment, stickerset, null, chatActivity.getChatActivityEnterViewForStickers(), chatActivity.getResourceProvider()); alert.setCalcMandatoryInsets(chatActivity.isKeyboardVisible()); } else { alert = new StickersAlert(LaunchActivity.this, fragment, stickerset, null, null); @@ -3115,16 +3118,12 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa Bundle args13 = new Bundle(); args13.putBoolean("scrollToTopOnResume", true); args13.putBoolean("hasUrl", hasUrl); - int lower_part = (int) did; - int high_id = (int) (did >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args13.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args13.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args13.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args13.putLong("user_id", did); } else { - args13.putInt("enc_id", high_id); + args13.putLong("chat_id", -did); } if (MessagesController.getInstance(intentAccount).checkCanOpenChat(args13, fragment13)) { NotificationCenter.getInstance(intentAccount).postNotificationName(NotificationCenter.closeChats); @@ -3365,7 +3364,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } else { Bundle args = new Bundle(); - args.putInt("chat_id", channelId); + args.putLong("chat_id", channelId); args.putInt("message_id", messageId); BaseFragment lastFragment = !mainFragmentsStack.isEmpty() ? mainFragmentsStack.get(mainFragmentsStack.size() - 1) : null; if (lastFragment == null || MessagesController.getInstance(intentAccount).checkCanOpenChat(args, lastFragment)) { @@ -3781,10 +3780,10 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa if (!AndroidUtilities.isTablet()) { NotificationCenter.getInstance(account).postNotificationName(NotificationCenter.closeChats); } - if (result > 0) { - args.putInt("user_id", result); + if (DialogObject.isUserDialog(result)) { + args.putLong("user_id", result); } else { - args.putInt("chat_id", -result); + args.putLong("chat_id", -result); } ChatActivity fragment = new ChatActivity(args); fragment.setOpenImport(); @@ -3812,22 +3811,18 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa final ChatActivity fragment; if (dids.size() <= 1) { final long did = dids.get(0); - int lower_part = (int) did; - int high_id = (int) (did >> 32); Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); if (!AndroidUtilities.isTablet()) { NotificationCenter.getInstance(account).postNotificationName(NotificationCenter.closeChats); } - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); } else { - args.putInt("enc_id", high_id); + args.putLong("chat_id", -did); } if (!MessagesController.getInstance(account).checkCanOpenChat(args, dialogsFragment)) { return; @@ -3879,8 +3874,6 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa String captionToSend = null; for (int i = 0; i < dids.size(); i++) { final long did = dids.get(i); - int lower_part = (int) did; - int high_id = (int) (did >> 32); AccountInstance accountInstance = AccountInstance.getInstance(UserConfig.selectedAccount); if (fragment != null) { @@ -4390,7 +4383,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); - if (reason != 2 && reason != 3 && reason != 6) { + if (reason != 2 && reason != 3) { builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), (dialogInterface, i) -> { if (!mainFragmentsStack.isEmpty()) { MessagesController.getInstance(account).openByUserName("spambot", mainFragmentsStack.get(mainFragmentsStack.size() - 1), 1); @@ -4529,7 +4522,11 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } drawerLayoutContainer.setBehindKeyboardColor(Theme.getColor(Theme.key_windowBackgroundWhite)); - checkSystemBarColors(); + boolean checkNavigationBarColor = true; + if (args.length > 1) { + checkNavigationBarColor = (boolean) args[1]; + } + checkSystemBarColors(true, checkNavigationBarColor); } else if (id == NotificationCenter.needSetDayNightTheme) { boolean instant = false; if (Build.VERSION.SDK_INT >= 21 && args[2] != null) { @@ -4738,16 +4735,16 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } if (type == Bulletin.TYPE_NAME_CHANGED) { - int peerId = (int) args[1]; + long peerId = (long) args[1]; String text = peerId > 0 ? LocaleController.getString("YourNameChanged", R.string.YourNameChanged) : LocaleController.getString("CannelTitleChanged", R.string.ChannelTitleChanged); - (container != null ? BulletinFactory.of(container) : BulletinFactory.of(fragment)).createErrorBulletin(text).show(); + (container != null ? BulletinFactory.of(container, null) : BulletinFactory.of(fragment)).createErrorBulletin(text).show(); } else if (type == Bulletin.TYPE_BIO_CHANGED) { - int peerId = (int) args[1]; + long peerId = (long) args[1]; String text = peerId > 0 ? LocaleController.getString("YourBioChanged", R.string.YourBioChanged) : LocaleController.getString("CannelDescriptionChanged", R.string.ChannelDescriptionChanged); - (container != null ? BulletinFactory.of(container) : BulletinFactory.of(fragment)).createErrorBulletin(text).show(); + (container != null ? BulletinFactory.of(container, null) : BulletinFactory.of(fragment)).createErrorBulletin(text).show(); } else if (type == Bulletin.TYPE_STICKER) { TLRPC.Document sticker = (TLRPC.Document) args[1]; - StickerSetBulletinLayout layout = new StickerSetBulletinLayout(this, null, (int) args[2], sticker); + StickerSetBulletinLayout layout = new StickerSetBulletinLayout(this, null, (int) args[2], sticker, null); if (fragment != null) { Bulletin.make(fragment, layout, Bulletin.DURATION_SHORT).show(); } else { @@ -4757,7 +4754,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa if (fragment != null) { BulletinFactory.of(fragment).createErrorBulletin((String) args[1]).show(); } else { - BulletinFactory.of(container).createErrorBulletin((String) args[1]).show(); + BulletinFactory.of(container, null).createErrorBulletin((String) args[1]).show(); } } } @@ -4799,7 +4796,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa boolean wasMuted = wasMutedByAdminRaisedHand; ChatObject.Call call = voIPService.groupCall; TLRPC.InputPeer peer = voIPService.getGroupCallPeer(); - int did; + long did; if (peer != null) { if (peer.user_id != 0) { did = peer.user_id; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java index 710d90f0f..78ece24e6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java @@ -2,18 +2,15 @@ package org.telegram.ui; import android.content.Context; import android.graphics.Canvas; -import android.graphics.Color; import android.os.Vibrator; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.text.method.DigitsKeyListener; -import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; -import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ScrollView; @@ -28,7 +25,6 @@ import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.AdjustPanLayoutHelper; import org.telegram.ui.ActionBar.AlertDialog; import org.telegram.ui.ActionBar.BaseFragment; -import org.telegram.ui.ActionBar.DrawerLayoutContainer; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.ActionBar.ThemeDescription; import org.telegram.ui.Cells.HeaderCell; @@ -47,7 +43,7 @@ public class LinkEditActivity extends BaseFragment { public final static int EDIT_TYPE = 1; private int type; - private final int chatId; + private final long chatId; private SlideChooseView usesChooseView; private SlideChooseView timeChooseView; @@ -64,7 +60,7 @@ public class LinkEditActivity extends BaseFragment { private ScrollView scrollView; private boolean finished; - public LinkEditActivity(int type, int chatId) { + public LinkEditActivity(int type, long chatId) { this.type = type; this.chatId = chatId; } @@ -256,11 +252,7 @@ public class LinkEditActivity extends BaseFragment { timeEditText.setGravity(Gravity.CENTER_VERTICAL); timeEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); timeEditText.setHint(LocaleController.getString("TimeLimitHint", R.string.TimeLimitHint)); - timeEditText.setOnClickListener(view -> { - AlertsCreator.createDatePickerDialog(context, -1, (notify, scheduleDate) -> { - chooseDate(scheduleDate); - }); - }); + timeEditText.setOnClickListener(view -> AlertsCreator.createDatePickerDialog(context, -1, (notify, scheduleDate) -> chooseDate(scheduleDate))); timeChooseView.setCallback(index -> { if (index < dispalyedDates.size()) { @@ -423,22 +415,20 @@ public class LinkEditActivity extends BaseFragment { req.usage_limit = 0; } - getConnectionsManager().sendRequest(req, (response, error) -> { - AndroidUtilities.runOnUIThread(() -> { - loading = false; - if (progressDialog != null) { - progressDialog.dismiss(); + getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { + loading = false; + if (progressDialog != null) { + progressDialog.dismiss(); + } + if (error == null) { + if (callback != null) { + callback.onLinkCreated(response); } - if (error == null) { - if (callback != null) { - callback.onLinkCreated(response); - } - finishFragment(); - } else { - AlertsCreator.showSimpleAlert(LinkEditActivity.this, error.text); - } - }); - }); + finishFragment(); + } else { + AlertsCreator.showSimpleAlert(LinkEditActivity.this, error.text); + } + })); } else if (type == EDIT_TYPE) { if (progressDialog != null) { progressDialog.dismiss(); @@ -487,22 +477,20 @@ public class LinkEditActivity extends BaseFragment { } if (edited) { - getConnectionsManager().sendRequest(req, (response, error) -> { - AndroidUtilities.runOnUIThread(() -> { - loading = false; - if (progressDialog != null) { - progressDialog.dismiss(); + getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { + loading = false; + if (progressDialog != null) { + progressDialog.dismiss(); + } + if (error == null) { + if (callback != null) { + callback.onLinkEdited(inviteToEdit, response); } - if (error == null) { - if (callback != null) { - callback.onLinkEdited(inviteToEdit, response); - } - finishFragment(); - } else { - AlertsCreator.showSimpleAlert(LinkEditActivity.this, error.text); - } - }); - }); + finishFragment(); + } else { + AlertsCreator.showSimpleAlert(LinkEditActivity.this, error.text); + } + })); } } }); @@ -662,24 +650,21 @@ public class LinkEditActivity extends BaseFragment { @Override public ArrayList getThemeDescriptions() { - ThemeDescription.ThemeDescriptionDelegate descriptionDelegate = new ThemeDescription.ThemeDescriptionDelegate() { - @Override - public void didSetColor() { - if (dividerUses != null) { - Context context = dividerUses.getContext(); - dividerUses.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); - divider.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); - buttonTextView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); + ThemeDescription.ThemeDescriptionDelegate descriptionDelegate = () -> { + if (dividerUses != null) { + Context context = dividerUses.getContext(); + dividerUses.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); + divider.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); + buttonTextView.setBackgroundDrawable(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed))); - usesEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); - usesEditText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + usesEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + usesEditText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); - timeEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); - timeEditText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); - buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); - if (revokeLink != null) { - revokeLink.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText5)); - } + timeEditText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); + timeEditText.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText)); + buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText)); + if (revokeLink != null) { + revokeLink.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText5)); } } }; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java index 960e1e9dd..563b5ceb8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java @@ -41,7 +41,6 @@ import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.text.TextUtils; -import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -77,6 +76,7 @@ import com.google.android.gms.maps.model.PatternItem; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocationController; @@ -126,6 +126,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -187,7 +188,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter private Runnable updateRunnable; private ArrayList markers = new ArrayList<>(); - private SparseArray markersMap = new SparseArray<>(); + private LongSparseArray markersMap = new LongSparseArray<>(); private ArrayList placeMarkers = new ArrayList<>(); @@ -247,7 +248,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter } public static class LiveLocation { - public int id; + public long id; public TLRPC.Message object; public TLRPC.User user; public TLRPC.Chat chat; @@ -900,8 +901,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter openProximityAlert(); }); TLRPC.Chat chat = null; - if ((int) dialogId < 0) { - chat = getMessagesController().getChat(-(int) dialogId); + if (DialogObject.isChatDialog(dialogId)) { + chat = getMessagesController().getChat(-dialogId); } if (messageObject == null || !messageObject.isLiveLocation() || messageObject.isExpiredLiveLocation(getConnectionsManager().getCurrentTime()) || ChatObject.isChannel(chat) && !chat.megagroup) { proximityButton.setVisibility(View.GONE); @@ -911,7 +912,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter if (myInfo != null && myInfo.proximityMeters > 0) { proximityButton.setImageResource(R.drawable.msg_location_alert2); } else { - if ((int) dialogId > 0 && messageObject.getFromChatId() == getUserConfig().getClientUserId()) { + if (DialogObject.isUserDialog(dialogId) && messageObject.getFromChatId() == getUserConfig().getClientUserId()) { proximityButton.setVisibility(View.INVISIBLE); proximityButton.setAlpha(0.0f); proximityButton.setScaleX(0.4f); @@ -955,7 +956,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0)); listView = new RecyclerListView(context); - listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false) { + listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false, null) { @Override protected void onDirectionClick() { if (Build.VERSION.SDK_INT >= 23) { @@ -1019,7 +1020,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter final AlertDialog[] progressDialog = new AlertDialog[]{new AlertDialog(getParentActivity(), 3)}; TLRPC.TL_channels_editLocation req = new TLRPC.TL_channels_editLocation(); req.address = venue.address; - req.channel = getMessagesController().getInputChannel(-(int) dialogId); + req.channel = getMessagesController().getInputChannel(-dialogId); req.geo_point = new TLRPC.TL_inputGeoPoint(); req.geo_point.lat = venue.geo.lat; req.geo_point._long = venue.geo._long; @@ -1418,11 +1419,11 @@ public class LocationActivity extends BaseFragment implements NotificationCenter return result; } - private int getMessageId(TLRPC.Message message) { + private long getMessageId(TLRPC.Message message) { if (message.from_id != null) { return MessageObject.getFromChatId(message); } else { - return (int) MessageObject.getDialogId(message); + return MessageObject.getDialogId(message); } } @@ -1434,8 +1435,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter } TLRPC.User user; - if ((int) dialogId > 0) { - user = getMessagesController().getUser((int) dialogId); + if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); } else { user = null; } @@ -1446,7 +1447,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter moveToBounds(radius, true, true); } } - if ((int) dialogId < 0) { + if (DialogObject.isChatDialog(dialogId)) { return true; } for (int a = 0, N = markers.size(); a < N; a++) { @@ -1511,18 +1512,18 @@ public class LocationActivity extends BaseFragment implements NotificationCenter int lastTime = preferences.getInt("backgroundloc", 0); if (Math.abs(System.currentTimeMillis() / 1000 - lastTime) > 24 * 60 * 60 && activity.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { preferences.edit().putInt("backgroundloc", (int) (System.currentTimeMillis() / 1000)).commit(); - AlertsCreator.createBackgroundLocationPermissionDialog(activity, getMessagesController().getUser(getUserConfig().getClientUserId()), () -> openShareLiveLocation(askWithRadius)).show(); + AlertsCreator.createBackgroundLocationPermissionDialog(activity, getMessagesController().getUser(getUserConfig().getClientUserId()), () -> openShareLiveLocation(askWithRadius), null).show(); return; } } } TLRPC.User user; - if ((int) dialogId > 0) { - user = getMessagesController().getUser((int) dialogId); + if (DialogObject.isUserDialog(dialogId)) { + user = getMessagesController().getUser(dialogId); } else { user = null; } - showDialog(AlertsCreator.createLocationUpdateDialog(getParentActivity(), user, param -> shareLiveLocation(user, param, proximityRadius))); + showDialog(AlertsCreator.createLocationUpdateDialog(getParentActivity(), user, param -> shareLiveLocation(user, param, proximityRadius), null)); } private void shareLiveLocation(TLRPC.User user, int period, int radius) { @@ -1607,8 +1608,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter liveLocation.user = getMessagesController().getUser(liveLocation.object.from_id.user_id); liveLocation.id = liveLocation.object.from_id.user_id; } else { - int did = (int) MessageObject.getDialogId(message); - if (did > 0) { + long did = MessageObject.getDialogId(message); + if (DialogObject.isUserDialog(did)) { liveLocation.user = getMessagesController().getUser(did); } else { liveLocation.chat = getMessagesController().getChat(-did); @@ -1664,13 +1665,12 @@ public class LocationActivity extends BaseFragment implements NotificationCenter private LiveLocation addUserMarker(TLRPC.TL_channelLocation location) { LatLng latLng = new LatLng(location.geo_point.lat, location.geo_point._long); LiveLocation liveLocation = new LiveLocation(); - int did = (int) dialogId; - if (did > 0) { - liveLocation.user = getMessagesController().getUser(did); + if (DialogObject.isUserDialog(dialogId)) { + liveLocation.user = getMessagesController().getUser(dialogId); } else { - liveLocation.chat = getMessagesController().getChat(-did); + liveLocation.chat = getMessagesController().getChat(-dialogId); } - liveLocation.id = did; + liveLocation.id = dialogId; try { MarkerOptions options = new MarkerOptions().position(latLng); @@ -1933,8 +1933,8 @@ public class LocationActivity extends BaseFragment implements NotificationCenter int val = preferences.getInt("proximityhint", 0); if (val < 3) { preferences.edit().putInt("proximityhint", ++val).commit(); - if ((int) dialogId > 0) { - TLRPC.User user = getMessagesController().getUser((int) dialogId); + if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = getMessagesController().getUser(dialogId); hintView.setOverrideText(LocaleController.formatString("ProximityTooltioUser", R.string.ProximityTooltioUser, UserObject.getFirstName(user))); } else { hintView.setOverrideText(LocaleController.getString("ProximityTooltioGroup", R.string.ProximityTooltioGroup)); @@ -2155,7 +2155,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter dialogId = messageObject.getDialogId(); } - public void setChatLocation(int chatId, TLRPC.TL_channelLocation location) { + public void setChatLocation(long chatId, TLRPC.TL_channelLocation location) { dialogId = -chatId; chatLocation = location; } @@ -2311,16 +2311,15 @@ public class LocationActivity extends BaseFragment implements NotificationCenter } else { messages = null; } - int lower_id = (int) dialogId; - if (lower_id < 0) { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = getMessagesController().getChat(-dialogId); if (ChatObject.isChannel(chat) && !chat.megagroup) { return false; } } TLRPC.TL_messages_getRecentLocations req = new TLRPC.TL_messages_getRecentLocations(); final long dialog_id = messageObject.getDialogId(); - req.peer = getMessagesController().getInputPeer((int) dialog_id); + req.peer = getMessagesController().getInputPeer(dialog_id); req.limit = 100; getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { @@ -2410,8 +2409,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter addUserMarker(messageObject.messageOwner); added = true; } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { - int lowerId = (int) messageObject.getDialogId(); - if (lowerId > 0) { + if (DialogObject.isUserDialog(messageObject.getDialogId())) { proximityButton.setImageResource(R.drawable.msg_location_alert); if (proximityCircle != null) { proximityCircle.remove(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java index e587cae32..fab78132d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java @@ -68,24 +68,24 @@ import android.widget.Toast; import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.ApplicationLoader; +import org.telegram.messenger.BuildVars; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLocation; +import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.ApplicationLoader; -import org.telegram.messenger.BuildVars; -import org.telegram.messenger.FileLog; -import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.messenger.SRPHelper; +import org.telegram.messenger.UserConfig; +import org.telegram.messenger.Utilities; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLRPC; -import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; @@ -102,19 +102,20 @@ import org.telegram.ui.Components.BulletinFactory; import org.telegram.ui.Components.CombinedDrawable; import org.telegram.ui.Components.ContextProgressView; import org.telegram.ui.Components.EditTextBoldCursor; -import org.telegram.ui.Components.RLottieDrawable; -import org.telegram.ui.Components.RLottieImageView; -import org.telegram.ui.Components.VerticalPositionAutoAnimator; import org.telegram.ui.Components.HintEditText; import org.telegram.ui.Components.ImageUpdater; import org.telegram.ui.Components.LayoutHelper; +import org.telegram.ui.Components.RLottieDrawable; +import org.telegram.ui.Components.RLottieImageView; import org.telegram.ui.Components.RadialProgressView; import org.telegram.ui.Components.SlideView; +import org.telegram.ui.Components.VerticalPositionAutoAnimator; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -1127,9 +1128,8 @@ public class LoginActivity extends BaseFragment { private int countryState = 0; - private ArrayList countriesArray = new ArrayList<>(); - private HashMap countriesMap = new HashMap<>(); - private HashMap codesMap = new HashMap<>(); + private ArrayList countriesArray = new ArrayList<>(); + private HashMap codesMap = new HashMap<>(); private HashMap phoneFormatMap = new HashMap<>(); private boolean ignoreSelection = false; @@ -1153,9 +1153,9 @@ public class LoginActivity extends BaseFragment { countryButton.setBackground(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 7)); addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 0, 0, 14)); countryButton.setOnClickListener(view -> { - CountrySelectActivity fragment = new CountrySelectActivity(true); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - selectCountry(name, shortName); + CountrySelectActivity fragment = new CountrySelectActivity(true, countriesArray); + fragment.setCountrySelectActivityDelegate((country) -> { + selectCountry(country); AndroidUtilities.runOnUIThread(() -> AndroidUtilities.showKeyboard(phoneField), 300); phoneField.requestFocus(); phoneField.setSelection(phoneField.length()); @@ -1218,7 +1218,7 @@ public class LoginActivity extends BaseFragment { phoneField.setHintText(null); countryState = 1; } else { - String country; + CountrySelectActivity.Country country; boolean ok = false; String textToSet = null; if (text.length() > 4) { @@ -1239,18 +1239,11 @@ public class LoginActivity extends BaseFragment { } country = codesMap.get(text); if (country != null) { - int index = countriesArray.indexOf(country); - if (index != -1) { - ignoreSelection = true; - countryButton.setText(countriesArray.get(index)); - String hint = phoneFormatMap.get(text); - phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); - countryState = 0; - } else { - countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry)); - phoneField.setHintText(null); - countryState = 2; - } + ignoreSelection = true; + countryButton.setText(country.name); + String hint = phoneFormatMap.get(text); + phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); + countryState = 0; } else { countryButton.setText(LocaleController.getString("WrongCountry", R.string.WrongCountry)); phoneField.setHintText(null); @@ -1425,9 +1418,9 @@ public class LoginActivity extends BaseFragment { FileLog.e(e); } if (syncContacts) { - BulletinFactory.of((FrameLayout) fragmentView).createSimpleBulletin(R.raw.contacts_sync_on, LocaleController.getString("SyncContactsOn", R.string.SyncContactsOn)).show(); + BulletinFactory.of((FrameLayout) fragmentView, null).createSimpleBulletin(R.raw.contacts_sync_on, LocaleController.getString("SyncContactsOn", R.string.SyncContactsOn)).show(); } else { - BulletinFactory.of((FrameLayout) fragmentView).createSimpleBulletin(R.raw.contacts_sync_off, LocaleController.getString("SyncContactsOff", R.string.SyncContactsOff)).show(); + BulletinFactory.of((FrameLayout) fragmentView, null).createSimpleBulletin(R.raw.contacts_sync_off, LocaleController.getString("SyncContactsOff", R.string.SyncContactsOff)).show(); } } }); @@ -1448,14 +1441,18 @@ public class LoginActivity extends BaseFragment { } HashMap languageMap = new HashMap<>(); + try { BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt"))); String line; while ((line = reader.readLine()) != null) { String[] args = line.split(";"); - countriesArray.add(0, args[2]); - countriesMap.put(args[2], args[0]); - codesMap.put(args[0], args[2]); + CountrySelectActivity.Country countryWithCode = new CountrySelectActivity.Country(); + countryWithCode.name = args[2]; + countryWithCode.code = args[0]; + countryWithCode.shortname = args[1]; + countriesArray.add(0, countryWithCode); + codesMap.put(args[0], countryWithCode); if (args.length > 3) { phoneFormatMap.put(args[0], args[3]); } @@ -1466,7 +1463,7 @@ public class LoginActivity extends BaseFragment { FileLog.e(e); } - Collections.sort(countriesArray, String::compareTo); + Collections.sort(countriesArray, Comparator.comparing(o -> o.name)); String country = null; @@ -1505,28 +1502,56 @@ public class LoginActivity extends BaseFragment { } else { codeField.requestFocus(); } + + TLRPC.TL_help_getCountriesList req = new TLRPC.TL_help_getCountriesList(); + req.lang_code = ""; + getConnectionsManager().sendRequest(req, (response, error) -> { + if (error == null) { + countriesArray.clear(); + codesMap.clear(); + phoneFormatMap.clear(); + TLRPC.TL_help_countriesList help_countriesList = (TLRPC.TL_help_countriesList) response; + for (int i = 0; i < help_countriesList.countries.size(); i++) { + TLRPC.TL_help_country c = help_countriesList.countries.get(i); + for (int k = 0; k < c.country_codes.size(); k++) { + CountrySelectActivity.Country countryWithCode = new CountrySelectActivity.Country(); + countryWithCode.name = c.default_name; + countryWithCode.code = c.country_codes.get(k).country_code; + + countriesArray.add(countryWithCode); + codesMap.put(c.country_codes.get(k).country_code, countryWithCode); + if (c.country_codes.get(k).patterns.size() > 0) { + phoneFormatMap.put(c.country_codes.get(k).country_code, c.country_codes.get(k).patterns.get(0)); + } + } + } + } + }, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors); } - public void selectCountry(String name, String iso) { - int index = countriesArray.indexOf(name); - if (index != -1) { - ignoreOnTextChange = true; - String code = countriesMap.get(name); - codeField.setText(code); - countryButton.setText(name); - String hint = phoneFormatMap.get(code); - phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); - countryState = 0; - ignoreOnTextChange = false; - } + public void selectCountry(CountrySelectActivity.Country country) { + ignoreOnTextChange = true; + String code = country.code; + codeField.setText(code); + countryButton.setText(country.name); + String hint = phoneFormatMap.get(code); + phoneField.setHintText(hint != null ? hint.replace('X', '–') : null); + countryState = 0; + ignoreOnTextChange = false; } private void setCountry(HashMap languageMap, String country) { - String countryName = languageMap.get(country); - if (countryName != null) { - int index = countriesArray.indexOf(countryName); - if (index != -1) { - codeField.setText(countriesMap.get(countryName)); + String name = languageMap.get(country); + if (name != null) { + CountrySelectActivity.Country countryWithCode = null; + for (int i = 0; i < countriesArray.size(); i++) { + if (countriesArray.get(i) != null && countriesArray.get(i).name.equals(country)) { + countryWithCode = countriesArray.get(i); + break; + } + } + if (countryWithCode != null) { + codeField.setText(countryWithCode.code); countryState = 0; } } @@ -1544,8 +1569,8 @@ public class LoginActivity extends BaseFragment { return; } ignoreOnTextChange = true; - String str = countriesArray.get(i); - codeField.setText(countriesMap.get(str)); + CountrySelectActivity.Country countryWithCode = countriesArray.get(i); + codeField.setText(countryWithCode.code); ignoreOnTextChange = false; } @@ -1775,7 +1800,7 @@ public class LoginActivity extends BaseFragment { if (number.length() > 4) { for (int a = 4; a >= 1; a--) { String sub = number.substring(0, a); - String country = codesMap.get(sub); + CountrySelectActivity.Country country = codesMap.get(sub); if (country != null) { ok = true; textToSet = number.substring(a); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ManageLinksActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ManageLinksActivity.java index 74a6e2456..74717c4a6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ManageLinksActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ManageLinksActivity.java @@ -83,11 +83,11 @@ public class ManageLinksActivity extends BaseFragment { private TLRPC.Chat currentChat; private TLRPC.ChatFull info; private TLRPC.TL_chatInviteExported invite; - private int adminId; + private long adminId; private boolean isChannel; - private int currentChatId; + private long currentChatId; private int helpRow; private int permanentLinkHeaderRow; @@ -134,7 +134,7 @@ public class ManageLinksActivity extends BaseFragment { private RecyclerItemsEnterAnimator recyclerItemsEnterAnimator; private ArrayList invites = new ArrayList<>(); private ArrayList revokedInvites = new ArrayList<>(); - private HashMap users = new HashMap<>(); + private HashMap users = new HashMap<>(); private InviteLinkBottomSheet inviteLinkBottomSheet; private ArrayList admins = new ArrayList<>(); @@ -170,7 +170,7 @@ public class ManageLinksActivity extends BaseFragment { private final int currentAccount = UserConfig.selectedAccount; - private static final String stickerSetName = "tg_placeholders"; + private static final String stickerSetName = AndroidUtilities.STICKERS_PLACEHOLDER_PACK_NAME; public EmptyView(Context context) { super(context); @@ -221,7 +221,7 @@ public class ManageLinksActivity extends BaseFragment { } } - public ManageLinksActivity(int chatId, int adminId, int invitesCount) { + public ManageLinksActivity(long chatId, long adminId, int invitesCount) { super(); currentChatId = chatId; this.invitesCount = invitesCount; @@ -244,46 +244,42 @@ public class ManageLinksActivity extends BaseFragment { linksLoading = true; TLRPC.TL_messages_getAdminsWithInvites req = new TLRPC.TL_messages_getAdminsWithInvites(); req.peer = getMessagesController().getInputPeer(-currentChatId); - int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { - AndroidUtilities.runOnUIThread(() -> { - getNotificationCenter().doOnIdle(() -> { - linksLoading = false; - if (error == null) { - TLRPC.TL_messages_chatAdminsWithInvites adminsWithInvites = (TLRPC.TL_messages_chatAdminsWithInvites) response; - for (int i = 0; i < adminsWithInvites.admins.size(); i++) { - TLRPC.TL_chatAdminWithInvites admin = adminsWithInvites.admins.get(i); - if (admin.admin_id != getAccountInstance().getUserConfig().clientUserId) { - admins.add(admin); - } - } - for (int i = 0; i < adminsWithInvites.users.size(); i++) { - TLRPC.User user = adminsWithInvites.users.get(i); - users.put(user.id, user); - } + int reqId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> getNotificationCenter().doOnIdle(() -> { + linksLoading = false; + if (error == null) { + TLRPC.TL_messages_chatAdminsWithInvites adminsWithInvites = (TLRPC.TL_messages_chatAdminsWithInvites) response; + for (int i = 0; i < adminsWithInvites.admins.size(); i++) { + TLRPC.TL_chatAdminWithInvites admin = adminsWithInvites.admins.get(i); + if (admin.admin_id != getAccountInstance().getUserConfig().clientUserId) { + admins.add(admin); + } + } + for (int i = 0; i < adminsWithInvites.users.size(); i++) { + TLRPC.User user = adminsWithInvites.users.get(i); + users.put(user.id, user); + } - } - int oldRowsCount = rowCount; - adminsLoaded = true; + } + int oldRowsCount = rowCount; + adminsLoaded = true; - hasMore = false; - if (admins.size() > 0) { - if (recyclerItemsEnterAnimator != null && !isPaused && isOpened) { - recyclerItemsEnterAnimator.showItemsAnimated(oldRowsCount + 1); - } - } - if (!hasMore || (invites.size() + revokedInvites.size() + admins.size()) >= 5) { - resumeDelayedFragmentAnimation(); - } + hasMore = false; + if (admins.size() > 0) { + if (recyclerItemsEnterAnimator != null && !isPaused && isOpened) { + recyclerItemsEnterAnimator.showItemsAnimated(oldRowsCount + 1); + } + } + if (!hasMore || (invites.size() + revokedInvites.size() + admins.size()) >= 5) { + resumeDelayedFragmentAnimation(); + } - if (!hasMore && !loadRevoked) { - hasMore = true; - loadRevoked = true; - loadLinks(false); - } - updateRows(true); - }); - }); - }); + if (!hasMore && !loadRevoked) { + hasMore = true; + loadRevoked = true; + loadLinks(false); + } + updateRows(true); + }))); getConnectionsManager().bindRequestToGuid(reqId, getClassGuid()); } else { TLRPC.TL_messages_getExportedChatInvites req = new TLRPC.TL_messages_getExportedChatInvites(); @@ -328,93 +324,91 @@ public class ManageLinksActivity extends BaseFragment { } TLRPC.TL_chatInviteExported finalPermanentLink = permanentLink; - AndroidUtilities.runOnUIThread(() -> { - getNotificationCenter().doOnIdle(() -> { - linksLoading = false; - hasMore = false; - if (finalPermanentLink != null) { - invite = finalPermanentLink; - if (info != null) { - info.exported_invite = finalPermanentLink; - } + AndroidUtilities.runOnUIThread(() -> getNotificationCenter().doOnIdle(() -> { + linksLoading = false; + hasMore = false; + if (finalPermanentLink != null) { + invite = finalPermanentLink; + if (info != null) { + info.exported_invite = finalPermanentLink; } - DiffCallback callback = saveListState(); - boolean updateByDiffUtils = false; + } + DiffCallback callback = saveListState(); + boolean updateByDiffUtils = false; - if (error == null) { - TLRPC.TL_messages_exportedChatInvites invites = (TLRPC.TL_messages_exportedChatInvites) response; + if (error == null) { + TLRPC.TL_messages_exportedChatInvites invites = (TLRPC.TL_messages_exportedChatInvites) response; - if (revoked) { - for (int i = 0; i < invites.invites.size(); i++) { - TLRPC.TL_chatInviteExported in = (TLRPC.TL_chatInviteExported) invites.invites.get(i); - fixDate(in); - this.revokedInvites.add(in); - } - } else { - if (adminId != getAccountInstance().getUserConfig().clientUserId && this.invites.size() == 0 && invites.invites.size() > 0) { - invite = (TLRPC.TL_chatInviteExported) invites.invites.get(0); - invites.invites.remove(0); - } - for (int i = 0; i < invites.invites.size(); i++) { - TLRPC.TL_chatInviteExported in = (TLRPC.TL_chatInviteExported) invites.invites.get(i); - fixDate(in); - this.invites.add(in); - } - } - - for (int i = 0; i < invites.users.size(); i++) { - users.put(invites.users.get(i).id, invites.users.get(i)); - } - int oldRowsCount = rowCount; - if (invites.invites.size() == 0) { - hasMore = false; - } else if (revoked) { - hasMore = this.revokedInvites.size() + 1 < invites.count; - } else { - hasMore = this.invites.size() + 1 < invites.count; - } - if (invites.invites.size() > 0 && isOpened) { - if (recyclerItemsEnterAnimator != null && !isPaused) { - recyclerItemsEnterAnimator.showItemsAnimated(oldRowsCount + 1); - } - } else { - updateByDiffUtils = true; - } - if (info != null && !revoked) { - info.invitesCount = invites.count; - getMessagesStorage().saveChatLinksCount(currentChatId, info.invitesCount); + if (revoked) { + for (int i = 0; i < invites.invites.size(); i++) { + TLRPC.TL_chatInviteExported in = (TLRPC.TL_chatInviteExported) invites.invites.get(i); + fixDate(in); + this.revokedInvites.add(in); } } else { + if (adminId != getAccountInstance().getUserConfig().clientUserId && this.invites.size() == 0 && invites.invites.size() > 0) { + invite = (TLRPC.TL_chatInviteExported) invites.invites.get(0); + invites.invites.remove(0); + } + for (int i = 0; i < invites.invites.size(); i++) { + TLRPC.TL_chatInviteExported in = (TLRPC.TL_chatInviteExported) invites.invites.get(i); + fixDate(in); + this.invites.add(in); + } + } + + for (int i = 0; i < invites.users.size(); i++) { + users.put(invites.users.get(i).id, invites.users.get(i)); + } + int oldRowsCount = rowCount; + if (invites.invites.size() == 0) { hasMore = false; - } - - boolean loadNext = false; - if (!hasMore && !loadRevoked && adminId == getAccountInstance().getUserConfig().clientUserId) { - hasMore = true; - loadAdmins = true; - loadNext = true; - } else if (!hasMore && !loadRevoked) { - hasMore = true; - loadRevoked = true; - loadNext = true; - } - - if (!hasMore || (invites.size() + revokedInvites.size() + admins.size()) >= 5) { - resumeDelayedFragmentAnimation(); - } - - if (loadNext) { - loadLinks(false); - } - - if (updateByDiffUtils && listViewAdapter != null && listView.getChildCount() > 0) { - updateRecyclerViewAnimated(callback); + } else if (revoked) { + hasMore = this.revokedInvites.size() + 1 < invites.count; } else { - updateRows(true); + hasMore = this.invites.size() + 1 < invites.count; } - }); - }); + if (invites.invites.size() > 0 && isOpened) { + if (recyclerItemsEnterAnimator != null && !isPaused) { + recyclerItemsEnterAnimator.showItemsAnimated(oldRowsCount + 1); + } + } else { + updateByDiffUtils = true; + } + if (info != null && !revoked) { + info.invitesCount = invites.count; + getMessagesStorage().saveChatLinksCount(currentChatId, info.invitesCount); + } + } else { + hasMore = false; + } + + boolean loadNext = false; + if (!hasMore && !loadRevoked && adminId == getAccountInstance().getUserConfig().clientUserId) { + hasMore = true; + loadAdmins = true; + loadNext = true; + } else if (!hasMore && !loadRevoked) { + hasMore = true; + loadRevoked = true; + loadNext = true; + } + + if (!hasMore || (invites.size() + revokedInvites.size() + admins.size()) >= 5) { + resumeDelayedFragmentAnimation(); + } + + if (loadNext) { + loadLinks(false); + } + + if (updateByDiffUtils && listViewAdapter != null && listView.getChildCount() > 0) { + updateRecyclerViewAnimated(callback); + } else { + updateRows(true); + } + })); }); getConnectionsManager().bindRequestToGuid(reqId, getClassGuid()); } @@ -594,7 +588,7 @@ public class ManageLinksActivity extends BaseFragment { TLRPC.User user = users.get(invite.admin_id); if (user != null) { Bundle bundle = new Bundle(); - bundle.putInt("user_id", user.id); + bundle.putLong("user_id", user.id); MessagesController.getInstance(UserConfig.selectedAccount).putUser(user, false); ProfileActivity profileActivity = new ProfileActivity(bundle); presentFragment(profileActivity); @@ -1180,9 +1174,7 @@ public class ManageLinksActivity extends BaseFragment { AlertDialog.Builder builder2 = new AlertDialog.Builder(getParentActivity()); builder2.setMessage(LocaleController.getString("RevokeAlert", R.string.RevokeAlert)); builder2.setTitle(LocaleController.getString("RevokeLink", R.string.RevokeLink)); - builder2.setPositiveButton(LocaleController.getString("RevokeButton", R.string.RevokeButton), (dialogInterface2, i2) -> { - revokeLink(inviteFinal); - }); + builder2.setPositiveButton(LocaleController.getString("RevokeButton", R.string.RevokeButton), (dialogInterface2, i2) -> revokeLink(inviteFinal)); builder2.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder2.create()); break; @@ -1191,9 +1183,7 @@ public class ManageLinksActivity extends BaseFragment { builder2 = new AlertDialog.Builder(getParentActivity()); builder2.setTitle(LocaleController.getString("DeleteLink", R.string.DeleteLink)); builder2.setMessage(LocaleController.getString("DeleteLinkHelp", R.string.DeleteLinkHelp)); - builder2.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface2, i2) -> { - deleteLink(inviteFinal); - }); + builder2.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface2, i2) -> deleteLink(inviteFinal)); builder2.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder2.create()); break; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java index a114ff2cd..11800c450 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java @@ -48,6 +48,7 @@ import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; @@ -162,7 +163,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No private boolean swipeBackEnabled; - private long dialog_id; + private long dialogId; private int columnsCount = 3; private static final Interpolator interpolator = t -> { @@ -290,10 +291,10 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No super(args); hasMedia = media; initialTab = initTab; - dialog_id = args.getLong("dialog_id", 0); + dialogId = args.getLong("dialog_id", 0); for (int a = 0; a < sharedMediaData.length; a++) { sharedMediaData[a] = new SharedMediaLayout.SharedMediaData(); - sharedMediaData[a].max_id[0] = ((int) dialog_id) == 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; + sharedMediaData[a].max_id[0] = DialogObject.isEncryptedDialog(dialogId) ? Integer.MIN_VALUE : Integer.MAX_VALUE; if (mergeDialogId != 0 && info != null) { sharedMediaData[a].max_id[1] = info.migrated_from_max_id; sharedMediaData[a].endReached[1] = false; @@ -373,32 +374,30 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setAddToContainer(false); actionBar.setClipContent(true); - int lower_id = (int) dialog_id; - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); - if (user != null) { - if (user.self) { - actionBar.setTitle(LocaleController.getString("SavedMessages", R.string.SavedMessages)); - } else { - actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); - } - } - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (chat != null) { - actionBar.setTitle(chat.title); - } - } - } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat((int) (dialog_id >> 32)); + if (DialogObject.isEncryptedDialog(dialogId)) { + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); if (encryptedChat != null) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); + TLRPC.User user = getMessagesController().getUser(encryptedChat.user_id); if (user != null) { actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); } } + } else if (DialogObject.isUserDialog(dialogId)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); + if (user != null) { + if (user.self) { + actionBar.setTitle(LocaleController.getString("SavedMessages", R.string.SavedMessages)); + } else { + actionBar.setTitle(ContactsController.formatName(user.first_name, user.last_name)); + } + } + } else { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); + if (chat != null) { + actionBar.setTitle(chat.title); + } } + if (TextUtils.isEmpty(actionBar.getTitle())) { actionBar.setTitle(LocaleController.getString("SharedContentTitle", R.string.SharedContentTitle)); } @@ -415,21 +414,18 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No TLRPC.Chat currentChat = null; TLRPC.User currentUser = null; TLRPC.EncryptedChat currentEncryptedChat = null; - int lower_id = (int) dialog_id; - if (lower_id != 0) { - if (lower_id > 0) { - currentUser = MessagesController.getInstance(currentAccount).getUser(lower_id); - } else { - currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + currentEncryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId); } else { - currentEncryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat((int) (dialog_id >> 32)); + currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId); } AlertsCreator.createDeleteMessagesAlert(MediaActivity.this, currentUser, currentChat, currentEncryptedChat, null, mergeDialogId, null, selectedFiles, null, false, 1, () -> { actionBar.hideActionMode(); actionBar.closeSearchField(); cantDeleteMessagesCount = 0; - }); + }, null); } else if (id == forward) { Bundle args = new Bundle(); args.putBoolean("onlySelect", true); @@ -465,20 +461,16 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No fragment1.finishFragment(); } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); } else { - args1.putInt("enc_id", high_part); + args1.putLong("chat_id", -did); } - if (lower_part != 0) { + if (!DialogObject.isEncryptedDialog(did)) { if (!MessagesController.getInstance(currentAccount).checkCanOpenChat(args1, fragment1)) { return; } @@ -501,21 +493,18 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return; } Bundle args = new Bundle(); - int lower_part = (int) dialog_id; - int high_id = (int) (dialog_id >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else if (lower_part < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + long did = dialogId; + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", did); + did = -chat.migrated_to.channel_id; + } + args.putLong("chat_id", -did); } args.putInt("message_id", selectedFiles[0].keyAt(0)); args.putBoolean("need_remove_previous_same_chat_activity", false); @@ -660,7 +649,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No selectedMessagesCountTextView.setOnTouchListener((v, event) -> true); actionMode.addView(selectedMessagesCountTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 72, 0, 0, 0)); - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { actionModeViews.add(gotoItem = actionMode.addItemWithWidth(gotochat, R.drawable.msg_message, AndroidUtilities.dp(54), LocaleController.getString("AccDescrGoToMessage", R.string.AccDescrGoToMessage))); actionModeViews.add(actionMode.addItemWithWidth(forward, R.drawable.msg_forward, AndroidUtilities.dp(54), LocaleController.getString("Forward", R.string.Forward))); } @@ -1155,7 +1144,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } if (!sharedMediaData[mediaPage.selectedType].endReached[0]) { sharedMediaData[mediaPage.selectedType].loading = true; - MediaDataController.getInstance(currentAccount).loadMedia(dialog_id, 50, sharedMediaData[mediaPage.selectedType].max_id[0], type, 1, classGuid); + MediaDataController.getInstance(currentAccount).loadMedia(dialogId, 50, sharedMediaData[mediaPage.selectedType].max_id[0], type, 1, classGuid); } else if (mergeDialogId != 0 && !sharedMediaData[mediaPage.selectedType].endReached[1]) { sharedMediaData[mediaPage.selectedType].loading = true; MediaDataController.getInstance(currentAccount).loadMedia(mergeDialogId, 50, sharedMediaData[mediaPage.selectedType].max_id[1], type, 1, classGuid); @@ -1314,8 +1303,8 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No sharedMediaData[type].loading = false; sharedMediaData[type].totalCount = (Integer) args[1]; ArrayList arr = (ArrayList) args[2]; - boolean enc = ((int) dialog_id) == 0; - int loadIndex = uid == dialog_id ? 0 : 1; + boolean enc = DialogObject.isEncryptedDialog(dialogId); + int loadIndex = uid == dialogId ? 0 : 1; RecyclerListView.Adapter adapter = null; if (type == 0) { @@ -1381,10 +1370,10 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return; } TLRPC.Chat currentChat = null; - if ((int) dialog_id < 0) { - currentChat = MessagesController.getInstance(currentAccount).getChat(-(int) dialog_id); + if (DialogObject.isChatDialog(dialogId)) { + currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId); } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; int loadIndex = 0; if (ChatObject.isChannel(currentChat)) { if (channelId == 0 && mergeDialogId != 0) { @@ -1430,9 +1419,9 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return; } long uid = (Long) args[0]; - if (uid == dialog_id) { + if (uid == dialogId) { ArrayList arr = (ArrayList) args[1]; - boolean enc = ((int) dialog_id) == 0; + boolean enc = DialogObject.isEncryptedDialog(dialogId); boolean updated = false; for (int a = 0; a < arr.size(); a++) { MessageObject obj = arr.get(a); @@ -1443,7 +1432,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No if (type == -1) { return; } - if (sharedMediaData[type].addMessage(obj, obj.getDialogId() == dialog_id ? 0 : 1, true, enc)) { + if (sharedMediaData[type].addMessage(obj, obj.getDialogId() == dialogId ? 0 : 1, true, enc)) { updated = true; hasMedia[type] = 1; } @@ -1652,7 +1641,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No changed = true; } } - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if (hasMedia[3] != 0 && !scrollSlidingTextTabStrip.hasTab(3)) { changed = true; } @@ -1679,7 +1668,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No scrollSlidingTextTabStrip.addTextTab(1, LocaleController.getString("SharedFilesTab2", R.string.SharedFilesTab2)); } } - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { if (hasMedia[3] != 0) { if (!scrollSlidingTextTabStrip.hasTab(3)) { scrollSlidingTextTabStrip.addTextTab(3, LocaleController.getString("SharedLinksTab2", R.string.SharedLinksTab2)); @@ -1836,7 +1825,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } if (!sharedMediaData[mediaPages[a].selectedType].loading && !sharedMediaData[mediaPages[a].selectedType].endReached[0] && sharedMediaData[mediaPages[a].selectedType].messages.isEmpty()) { sharedMediaData[mediaPages[a].selectedType].loading = true; - MediaDataController.getInstance(currentAccount).loadMedia(dialog_id, 50, 0, mediaPages[a].selectedType, 1, classGuid); + MediaDataController.getInstance(currentAccount).loadMedia(dialogId, 50, 0, mediaPages[a].selectedType, 1, classGuid); } mediaPages[a].listView.setVisibility(View.VISIBLE); } @@ -1855,7 +1844,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return false; } AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus()); - selectedFiles[item.getDialogId() == dialog_id ? 0 : 1].put(item.getId(), item); + selectedFiles[item.getDialogId() == dialogId ? 0 : 1].put(item.getId(), item); if (!item.canDeleteMessage(false, null)) { cantDeleteMessagesCount++; } @@ -1896,7 +1885,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return; } if (actionBar.isActionModeShowed()) { - int loadIndex = message.getDialogId() == dialog_id ? 0 : 1; + int loadIndex = message.getDialogId() == dialogId ? 0 : 1; if (selectedFiles[loadIndex].indexOfKey(message.getId()) >= 0) { selectedFiles[loadIndex].remove(message.getId()); if (!message.canDeleteMessage(false, null)) { @@ -1933,7 +1922,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } else { if (selectedMode == 0) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); - PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id, mergeDialogId, provider); + PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialogId, mergeDialogId, provider); } else if (selectedMode == 2 || selectedMode == 4) { if (view instanceof SharedAudioCell) { ((SharedAudioCell) view).didPressedButton(); @@ -1951,7 +1940,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No documents.add(message); PhotoViewer.getInstance().openPhoto(documents, 0, 0, 0, provider); } else { - PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialog_id, mergeDialogId, provider); + PhotoViewer.getInstance().openPhoto(sharedMediaData[selectedMode].messages, index, dialogId, mergeDialogId, provider); } return; } @@ -2164,7 +2153,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No ((SharedLinkCell) view).setDelegate(sharedLinkCellDelegate); break; case 3: - View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, 3, dialog_id); + View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, 3, dialogId); emptyStubView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return new RecyclerListView.Holder(emptyStubView); case 2: @@ -2191,7 +2180,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = messageObjects.get(position - 1); sharedLinkCell.setLink(messageObject, position != messageObjects.size() || section == sharedMediaData[3].sections.size() - 1 && sharedMediaData[3].loading); if (actionBar.isActionModeShowed()) { - sharedLinkCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedLinkCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedLinkCell.setChecked(false, !scrolling); } @@ -2298,7 +2287,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No view = new LoadingCell(mContext, AndroidUtilities.dp(32), AndroidUtilities.dp(54)); break; case 4: - View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, currentType, dialog_id); + View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, currentType, dialogId); emptyStubView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return new RecyclerListView.Holder(emptyStubView); case 3: @@ -2349,7 +2338,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = messageObjects.get(position - 1); sharedDocumentCell.setDocument(messageObject, position != messageObjects.size() || section == sharedMediaData[currentType].sections.size() - 1 && sharedMediaData[currentType].loading); if (actionBar.isActionModeShowed()) { - sharedDocumentCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedDocumentCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedDocumentCell.setChecked(false, !scrolling); } @@ -2360,7 +2349,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = messageObjects.get(position - 1); sharedAudioCell.setMessageObject(messageObject, position != messageObjects.size() || section == sharedMediaData[currentType].sections.size() - 1 && sharedMediaData[currentType].loading); if (actionBar.isActionModeShowed()) { - sharedAudioCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedAudioCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedAudioCell.setChecked(false, !scrolling); } @@ -2492,7 +2481,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No cache.add((SharedPhotoVideoCell) view); break; case 3: - View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, 0, dialog_id); + View emptyStubView = SharedMediaLayout.createEmptyStubView(mContext, 0, dialogId); emptyStubView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return new RecyclerListView.Holder(emptyStubView); case 2: @@ -2524,7 +2513,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = messageObjects.get(index); cell.setItem(a, sharedMediaData[0].messages.indexOf(messageObject), messageObject); if (actionBar.isActionModeShowed()) { - cell.setChecked(a, selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + cell.setChecked(a, selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { cell.setChecked(a, false, !scrolling); } @@ -2586,8 +2575,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } public void queryServerSearch(final String query, final int max_id, long did) { - int uid = (int) did; - if (uid == 0) { + if (DialogObject.isEncryptedDialog(did)) { return; } if (reqId != 0) { @@ -2612,7 +2600,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No req.filter = new TLRPC.TL_inputMessagesFilterMusic(); } req.q = query; - req.peer = MessagesController.getInstance(currentAccount).getInputPeer(uid); + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(did); if (req.peer == null) { return; } @@ -2687,7 +2675,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = sharedMediaData[currentType].messages.get(sharedMediaData[currentType].messages.size() - 1); queryServerSearch(query, messageObject.getId(), messageObject.getDialogId()); } else if (currentType == 3) { - queryServerSearch(query, 0, dialog_id); + queryServerSearch(query, 0, dialogId); } if (currentType == 1 || currentType == 4) { final ArrayList copy = new ArrayList<>(sharedMediaData[currentType].messages); @@ -2847,7 +2835,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = getItem(position); sharedDocumentCell.setDocument(messageObject, position != getItemCount() - 1); if (actionBar.isActionModeShowed()) { - sharedDocumentCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedDocumentCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedDocumentCell.setChecked(false, !scrolling); } @@ -2856,7 +2844,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = getItem(position); sharedLinkCell.setLink(messageObject, position != getItemCount() - 1); if (actionBar.isActionModeShowed()) { - sharedLinkCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedLinkCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedLinkCell.setChecked(false, !scrolling); } @@ -2865,7 +2853,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No MessageObject messageObject = getItem(position); sharedAudioCell.setMessageObject(messageObject, position != getItemCount() - 1); if (actionBar.isActionModeShowed()) { - sharedAudioCell.setChecked(selectedFiles[messageObject.getDialogId() == dialog_id ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); + sharedAudioCell.setChecked(selectedFiles[messageObject.getDialogId() == dialogId ? 0 : 1].indexOfKey(messageObject.getId()) >= 0, !scrolling); } else { sharedAudioCell.setChecked(false, !scrolling); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MessageSeenView.java b/TMessagesProj/src/main/java/org/telegram/ui/MessageSeenView.java new file mode 100644 index 000000000..b24ca7f0d --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/MessageSeenView.java @@ -0,0 +1,289 @@ +package org.telegram.ui; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.ColorFilter; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.text.TextUtils; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.ContactsController; +import org.telegram.messenger.ImageLocation; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.MessageObject; +import org.telegram.messenger.MessagesController; +import org.telegram.messenger.R; +import org.telegram.tgnet.ConnectionsManager; +import org.telegram.tgnet.RequestDelegate; +import org.telegram.tgnet.TLObject; +import org.telegram.tgnet.TLRPC; +import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.Components.AvatarDrawable; +import org.telegram.ui.Components.AvatarsImageView; +import org.telegram.ui.Components.BackupImageView; +import org.telegram.ui.Components.FlickerLoadingView; +import org.telegram.ui.Components.HideViewAfterAnimation; +import org.telegram.ui.Components.LayoutHelper; +import org.telegram.ui.Components.RecyclerListView; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Vector; + +public class MessageSeenView extends FrameLayout { + + ArrayList peerIds = new ArrayList<>(); + public ArrayList users = new ArrayList<>(); + AvatarsImageView avatarsImageView; + TextView titleView; + ImageView iconView; + int currentAccount; + boolean isVoice; + + FlickerLoadingView flickerLoadingView; + + public MessageSeenView(@NonNull Context context, int currentAccount, MessageObject messageObject) { + super(context); + this.currentAccount = currentAccount; + isVoice = (messageObject.isRoundVideo() || messageObject.isVoice()); + flickerLoadingView = new FlickerLoadingView(context); + flickerLoadingView.setColors(Theme.key_actionBarDefaultSubmenuBackground, Theme.key_listSelector, null); + flickerLoadingView.setViewType(FlickerLoadingView.MESSAGE_SEEN_TYPE); + flickerLoadingView.setIsSingleCell(false); + addView(flickerLoadingView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT)); + + titleView = new TextView(context); + titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + titleView.setLines(1); + titleView.setEllipsize(TextUtils.TruncateAt.END); + + addView(titleView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 40, 0, 62, 0)); + + avatarsImageView = new AvatarsImageView(context, false); + avatarsImageView.setStyle(AvatarsImageView.STYLE_MESSAGE_SEEN); + addView(avatarsImageView, LayoutHelper.createFrame(24 + 12 + 12 + 8, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 0, 0)); + + titleView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + + TLRPC.TL_messages_getMessageReadParticipants req = new TLRPC.TL_messages_getMessageReadParticipants(); + req.msg_id = messageObject.getId(); + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(messageObject.getDialogId()); + + iconView = new ImageView(context); + addView(iconView, LayoutHelper.createFrame(24, 24, Gravity.LEFT | Gravity.CENTER_VERTICAL, 11, 0, 0, 0)); + Drawable drawable = ContextCompat.getDrawable(context, isVoice ? R.drawable.msg_played : R.drawable.msg_seen).mutate(); + drawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon), PorterDuff.Mode.MULTIPLY)); + iconView.setImageDrawable(drawable); + + avatarsImageView.setAlpha(0); + titleView.setAlpha(0); + long fromId = 0; + if (messageObject.messageOwner.from_id != null) { + fromId = messageObject.messageOwner.from_id.user_id; + } + long finalFromId = fromId; + ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { + if (error == null) { + TLRPC.Vector vector = (TLRPC.Vector) response; + ArrayList unknownUsers = new ArrayList<>(); + HashMap usersLocal = new HashMap<>(); + ArrayList allPeers = new ArrayList<>(); + for (int i = 0, n = vector.objects.size(); i < n; i++) { + Object object = vector.objects.get(i); + if (object instanceof Long) { + Long peerId = (Long) object; + if (finalFromId == peerId) { + continue; + } + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(peerId); + allPeers.add(peerId); + if (user == null) { + unknownUsers.add(peerId); + } else { + usersLocal.put(peerId, user); + } + } + } + + if (unknownUsers.isEmpty()) { + for (int i = 0; i < allPeers.size(); i++) { + peerIds.add(allPeers.get(i)); + users.add(usersLocal.get(allPeers.get(i))); + } + updateView(); + } else { + TLRPC.TL_users_getUsers usersReq = new TLRPC.TL_users_getUsers(); + for (int i = 0; i < unknownUsers.size(); i++) { + usersReq.id.add(MessagesController.getInstance(currentAccount).getInputUser(unknownUsers.get(i))); + } + ConnectionsManager.getInstance(currentAccount).sendRequest(usersReq, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> { + if (response1 != null) { + TLRPC.Vector users = (TLRPC.Vector) response1; + for (int i = 0; i < users.objects.size(); i++) { + TLRPC.User user = (TLRPC.User) users.objects.get(i); + MessagesController.getInstance(currentAccount).putUser(user, false); + usersLocal.put(user.id, user); + } + for (int i = 0; i < allPeers.size(); i++) { + peerIds.add(allPeers.get(i)); + this.users.add(usersLocal.get(allPeers.get(i))); + } + } + updateView(); + })); + } + } else { + updateView(); + } + })); + setBackground(Theme.createRadSelectorDrawable(Theme.getColor(Theme.key_dialogButtonSelector), AndroidUtilities.dp(4), AndroidUtilities.dp(4))); + setEnabled(false); + } + + boolean ignoreLayout; + + @Override + public void requestLayout() { + if (ignoreLayout) { + return; + } + super.requestLayout(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + if (flickerLoadingView.getVisibility() == View.VISIBLE) { + ignoreLayout = true; + flickerLoadingView.setVisibility(View.GONE); + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + flickerLoadingView.getLayoutParams().width = getMeasuredWidth(); + flickerLoadingView.setVisibility(View.VISIBLE); + ignoreLayout = false; + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } else { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + } + + private void updateView() { + setEnabled(users.size() > 0); + for (int i = 0; i < 3; i++) { + if (i < users.size()) { + avatarsImageView.setObject(i, currentAccount, users.get(i)); + } else { + avatarsImageView.setObject(i, currentAccount, null); + } + } + if (users.size() == 1) { + avatarsImageView.setTranslationX(AndroidUtilities.dp(24)); + } else if (users.size() == 2) { + avatarsImageView.setTranslationX(AndroidUtilities.dp(12)); + } else { + avatarsImageView.setTranslationX(0); + } + + avatarsImageView.commitTransition(false); + if (peerIds.size() == 1 && users.get(0) != null) { + titleView.setText(ContactsController.formatName(users.get(0).first_name, users.get(0).last_name)); + } else { + titleView.setText(LocaleController.formatPluralString(isVoice ? "MessagePlayed" : "MessageSeen", peerIds.size())); + } + titleView.animate().alpha(1f).setDuration(220).start(); + avatarsImageView.animate().alpha(1f).setDuration(220).start(); + flickerLoadingView.animate().alpha(0f).setDuration(220).setListener(new HideViewAfterAnimation(flickerLoadingView)).start(); + } + + public RecyclerListView createListView() { + RecyclerListView recyclerListView = new RecyclerListView(getContext()); + recyclerListView.setLayoutManager(new LinearLayoutManager(getContext())); + recyclerListView.addItemDecoration(new RecyclerView.ItemDecoration() { + @Override + public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { + int p = parent.getChildAdapterPosition(view); + if (p == 0) { + outRect.top = AndroidUtilities.dp(4); + } + if (p == users.size() - 1) { + outRect.bottom = AndroidUtilities.dp(4); + } + } + }); + recyclerListView.setAdapter(new RecyclerListView.SelectionAdapter() { + + @Override + public boolean isEnabled(RecyclerView.ViewHolder holder) { + return true; + } + + @Override + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + UserCell userCell = new UserCell(parent.getContext()); + userCell.setLayoutParams(new RecyclerView.LayoutParams(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); + return new RecyclerListView.Holder(userCell); + } + + @Override + public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { + UserCell cell = (UserCell) holder.itemView; + cell.setUser(users.get(position)); + } + + @Override + public int getItemCount() { + return users.size(); + } + + }); + return recyclerListView; + } + + private static class UserCell extends FrameLayout { + + BackupImageView avatarImageView; + TextView nameView; + AvatarDrawable avatarDrawable = new AvatarDrawable(); + + public UserCell(Context context) { + super(context); + avatarImageView = new BackupImageView(context); + addView(avatarImageView, LayoutHelper.createFrame(32, 32, Gravity.CENTER_VERTICAL, 13, 0, 0, 0)); + avatarImageView.setRoundRadius(AndroidUtilities.dp(16)); + nameView = new TextView(context); + nameView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); + nameView.setLines(1); + nameView.setEllipsize(TextUtils.TruncateAt.END); + addView(nameView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 59, 0, 13, 0)); + + nameView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(44), View.MeasureSpec.EXACTLY)); + } + + public void setUser(TLRPC.User user) { + if (user != null) { + avatarDrawable.setInfo(user); + ImageLocation imageLocation = ImageLocation.getForUser(user, ImageLocation.TYPE_SMALL); + avatarImageView.setImage(imageLocation, "50_50", avatarDrawable, user); + nameView.setText(ContactsController.formatName(user.first_name, user.last_name)); + } + } + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MessageStatisticActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MessageStatisticActivity.java index e015407c7..9a062decf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MessageStatisticActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MessageStatisticActivity.java @@ -32,6 +32,7 @@ import org.json.JSONObject; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.Emoji; import org.telegram.messenger.FileLoader; @@ -83,7 +84,7 @@ import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; public class MessageStatisticActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { private TLRPC.ChatFull chat; - private final int chatId; + private final long chatId; private final int messageId; private ListAdapter listViewAdapter; private EmptyTextProgressView emptyView; @@ -284,12 +285,12 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati listView.setOnItemClickListener((view, position) -> { if (position >= startRow && position < endRow) { TLRPC.Message message = messages.get(position - startRow); - int did = (int) MessageObject.getDialogId(message); + long did = MessageObject.getDialogId(message); Bundle args = new Bundle(); - if (did > 0) { - args.putInt("user_id", did); + if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); } else { - args.putInt("chat_id", -did); + args.putLong("chat_id", -did); } args.putInt("message_id", message.id); args.putBoolean("need_remove_previous_same_chat_activity", false); @@ -427,9 +428,9 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati } else if (id == 1) { Bundle args = new Bundle(); if (messageObject.messageOwner.fwd_from == null) { - args.putInt("chat_id", messageObject.getChatId()); + args.putLong("chat_id", messageObject.getChatId()); } else { - args.putInt("chat_id", -messageObject.getFromChatId()); + args.putLong("chat_id", -messageObject.getFromChatId()); } presentFragment(new StatisticActivity(args)); } @@ -451,7 +452,7 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati } } Bundle args = new Bundle(); - args.putInt("chat_id", chatId); + args.putLong("chat_id", chatId); args.putInt("message_id", messageId); args.putBoolean("need_remove_previous_same_chat_activity", false); ChatActivity a = new ChatActivity(args); @@ -486,12 +487,12 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati req.channel = getMessagesController().getInputChannel(-messageObject.getFromChatId()); } else { req.msg_id = messageObject.getId(); - req.channel = getMessagesController().getInputChannel((int) -messageObject.getDialogId()); + req.channel = getMessagesController().getInputChannel(-messageObject.getDialogId()); } if (!messages.isEmpty()) { TLRPC.Message message = messages.get(messages.size() - 1); req.offset_id = message.id; - req.offset_peer = getMessagesController().getInputPeer((int) MessageObject.getDialogId(message)); + req.offset_peer = getMessagesController().getInputPeer(MessageObject.getDialogId(message)); req.offset_rate = nextRate; } else { req.offset_peer = new TLRPC.TL_inputPeerEmpty(); @@ -529,7 +530,7 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati req.channel = getMessagesController().getInputChannel(-messageObject.getFromChatId()); } else { req.msg_id = messageObject.getId(); - req.channel = getMessagesController().getInputChannel((int) -messageObject.getDialogId()); + req.channel = getMessagesController().getInputChannel(-messageObject.getDialogId()); } getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { statsLoaded = true; @@ -754,10 +755,10 @@ public class MessageStatisticActivity extends BaseFragment implements Notificati case 0: ManageChatUserCell userCell = (ManageChatUserCell) holder.itemView; TLRPC.Message item = getItem(position); - int did = (int) MessageObject.getDialogId(item); + long did = MessageObject.getDialogId(item); TLObject object; String status = null; - if (did > 0) { + if (DialogObject.isUserDialog(did)) { object = getMessagesController().getUser(did); } else { object = getMessagesController().getChat(-did); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/NewContactActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/NewContactActivity.java index 4d758d8b8..6778213db 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/NewContactActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/NewContactActivity.java @@ -318,8 +318,8 @@ public class NewContactActivity extends BaseFragment implements AdapterView.OnIt contentLayout.addView(countryButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 0, 24, 0, 14)); countryButton.setOnClickListener(view -> { CountrySelectActivity fragment = new CountrySelectActivity(true); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - selectCountry(name); + fragment.setCountrySelectActivityDelegate((country) -> { + selectCountry(country.name); phoneField.requestFocus(); phoneField.setSelection(phoneField.length()); }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsCustomSettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsCustomSettingsActivity.java index 74e7d552d..de1eaf95d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsCustomSettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsCustomSettingsActivity.java @@ -33,6 +33,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.NotificationCenter; @@ -379,7 +380,7 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(position); if (!enabled) { getNotificationsController().setGlobalNotificationsEnabled(currentType, 0); - checkCell.setChecked(!enabled); + checkCell.setChecked(true); if (holder != null) { adapter.onBindViewHolder(holder, position); } @@ -602,14 +603,14 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { ArrayList channelsResult = new ArrayList<>(); LongSparseArray waitingForLoadExceptions = new LongSparseArray<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedChatsToLoad = new ArrayList<>(); ArrayList users = new ArrayList<>(); ArrayList chats = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); - int selfId = getUserConfig().clientUserId; + long selfId = getUserConfig().clientUserId; SharedPreferences preferences = getNotificationsSettings(); Map values = preferences.getAll(); @@ -631,37 +632,11 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { } } - int lower_id = (int) did; - int high_id = (int) (did << 32); - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = getMessagesController().getUser(lower_id); - if (user == null) { - usersToLoad.add(lower_id); - waitingForLoadExceptions.put(did, exception); - } else if (user.deleted) { - continue; - } - usersResult.add(exception); - } else { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); - if (chat == null) { - chatsToLoad.add(-lower_id); - waitingForLoadExceptions.put(did, exception); - continue; - } else if (chat.left || chat.kicked || chat.migrated_to != null) { - continue; - } - if (ChatObject.isChannel(chat) && !chat.megagroup) { - channelsResult.add(exception); - } else { - chatsResult.add(exception); - } - } - } else if (high_id != 0) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(did)) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedChatId); if (encryptedChat == null) { - encryptedChatsToLoad.add(high_id); + encryptedChatsToLoad.add(encryptedChatId); waitingForLoadExceptions.put(did, exception); } else { TLRPC.User user = getMessagesController().getUser(encryptedChat.user_id); @@ -673,6 +648,29 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { } } usersResult.add(exception); + } else if (DialogObject.isUserDialog(did)) { + TLRPC.User user = getMessagesController().getUser(did); + if (user == null) { + usersToLoad.add(did); + waitingForLoadExceptions.put(did, exception); + } else if (user.deleted) { + continue; + } + usersResult.add(exception); + } else { + TLRPC.Chat chat = getMessagesController().getChat(-did); + if (chat == null) { + chatsToLoad.add(-did); + waitingForLoadExceptions.put(did, exception); + continue; + } else if (chat.left || chat.kicked || chat.migrated_to != null) { + continue; + } + if (ChatObject.isChannel(chat) && !chat.megagroup) { + channelsResult.add(exception); + } else { + chatsResult.add(exception); + } } } } @@ -716,11 +714,11 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { } for (int a = 0, size = encryptedChats.size(); a < size; a++) { TLRPC.EncryptedChat encryptedChat = encryptedChats.get(a); - waitingForLoadExceptions.remove(((long) encryptedChat.id) << 32); + waitingForLoadExceptions.remove(DialogObject.makeEncryptedDialogId(encryptedChat.id)); } for (int a = 0, size = waitingForLoadExceptions.size(); a < size; a++) { long did = waitingForLoadExceptions.keyAt(a); - if ((int) did < 0) { + if (DialogObject.isChatDialog(did)) { chatsResult.remove(waitingForLoadExceptions.valueAt(a)); channelsResult.remove(waitingForLoadExceptions.valueAt(a)); } else { @@ -930,34 +928,10 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { for (int a = 0; a < contactsCopy.size(); a++) { NotificationsSettingsActivity.NotificationException exception = contactsCopy.get(a); - int lower_id = (int) exception.did; - int high_id = (int) (exception.did >> 32); TLObject object = null; - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = getMessagesController().getUser(lower_id); - if (user.deleted) { - continue; - } - if (user != null) { - names[0] = ContactsController.formatName(user.first_name, user.last_name); - names[1] = user.username; - object = user; - } - } else { - TLRPC.Chat chat = getMessagesController().getChat(-lower_id); - if (chat != null) { - if (chat.left || chat.kicked || chat.migrated_to != null) { - continue; - } - names[0] = chat.title; - names[1] = chat.username; - object = chat; - } - } - } else { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(exception.did)) { + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(exception.did)); if (encryptedChat != null) { TLRPC.User user = getMessagesController().getUser(encryptedChat.user_id); if (user != null) { @@ -965,6 +939,24 @@ public class NotificationsCustomSettingsActivity extends BaseFragment { names[1] = user.username; } } + } else if (DialogObject.isUserDialog(exception.did)) { + TLRPC.User user = getMessagesController().getUser(exception.did); + if (user == null || user.deleted) { + continue; + } + names[0] = ContactsController.formatName(user.first_name, user.last_name); + names[1] = user.username; + object = user; + } else { + TLRPC.Chat chat = getMessagesController().getChat(-exception.did); + if (chat != null) { + if (chat.left || chat.kicked || chat.migrated_to != null) { + continue; + } + names[0] = chat.title; + names[1] = chat.username; + object = chat; + } } String originalName = names[0]; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java index e1d62bda6..80d4df5bf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java @@ -28,6 +28,7 @@ import android.widget.Toast; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.NotificationsController; @@ -194,14 +195,14 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif ArrayList channelsResult = new ArrayList<>(); LongSparseArray waitingForLoadExceptions = new LongSparseArray<>(); - ArrayList usersToLoad = new ArrayList<>(); - ArrayList chatsToLoad = new ArrayList<>(); + ArrayList usersToLoad = new ArrayList<>(); + ArrayList chatsToLoad = new ArrayList<>(); ArrayList encryptedChatsToLoad = new ArrayList<>(); ArrayList users = new ArrayList<>(); ArrayList chats = new ArrayList<>(); ArrayList encryptedChats = new ArrayList<>(); - int selfId = UserConfig.getInstance(currentAccount).clientUserId; + long selfId = UserConfig.getInstance(currentAccount).clientUserId; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); Map values = preferences.getAll(); @@ -223,37 +224,11 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } } - int lower_id = (int) did; - int high_id = (int) (did << 32); - if (lower_id != 0) { - if (lower_id > 0) { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); - if (user == null) { - usersToLoad.add(lower_id); - waitingForLoadExceptions.put(did, exception); - } else if (user.deleted) { - continue; - } - usersResult.add(exception); - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); - if (chat == null) { - chatsToLoad.add(-lower_id); - waitingForLoadExceptions.put(did, exception); - continue; - } else if (chat.left || chat.kicked || chat.migrated_to != null) { - continue; - } - if (ChatObject.isChannel(chat) && !chat.megagroup) { - channelsResult.add(exception); - } else { - chatsResult.add(exception); - } - } - } else if (high_id != 0) { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(high_id); + if (DialogObject.isEncryptedDialog(did)) { + int encryptedChatId = DialogObject.getEncryptedChatId(did); + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(encryptedChatId); if (encryptedChat == null) { - encryptedChatsToLoad.add(high_id); + encryptedChatsToLoad.add(encryptedChatId); waitingForLoadExceptions.put(did, exception); } else { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(encryptedChat.user_id); @@ -265,6 +240,29 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } } usersResult.add(exception); + } else if (DialogObject.isUserDialog(did)) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(did); + if (user == null) { + usersToLoad.add(did); + waitingForLoadExceptions.put(did, exception); + } else if (user.deleted) { + continue; + } + usersResult.add(exception); + } else { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-did); + if (chat == null) { + chatsToLoad.add(-did); + waitingForLoadExceptions.put(did, exception); + continue; + } else if (chat.left || chat.kicked || chat.migrated_to != null) { + continue; + } + if (ChatObject.isChannel(chat) && !chat.megagroup) { + channelsResult.add(exception); + } else { + chatsResult.add(exception); + } } } } @@ -308,11 +306,11 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } for (int a = 0, size = encryptedChats.size(); a < size; a++) { TLRPC.EncryptedChat encryptedChat = encryptedChats.get(a); - waitingForLoadExceptions.remove(((long) encryptedChat.id) << 32); + waitingForLoadExceptions.remove(DialogObject.makeEncryptedDialogId(encryptedChat.id)); } for (int a = 0, size = waitingForLoadExceptions.size(); a < size; a++) { long did = waitingForLoadExceptions.keyAt(a); - if ((int) did < 0) { + if (DialogObject.isChatDialog(did)) { chatsResult.remove(waitingForLoadExceptions.valueAt(a)); channelsResult.remove(waitingForLoadExceptions.valueAt(a)); } else { @@ -916,10 +914,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } textCell.setTextAndValue(LocaleController.getString("VoipSettingsRingtone", R.string.VoipSettingsRingtone), value, false); } else if (position == callsVibrateRow) { - int value = 0; - if (position == callsVibrateRow) { - value = preferences.getInt("vibrate_calls", 0); - } + int value = preferences.getInt("vibrate_calls", 0); if (value == 0) { textCell.setTextAndValue(LocaleController.getString("Vibrate", R.string.Vibrate), LocaleController.getString("VibrationDefault", R.string.VibrationDefault), true); } else if (value == 1) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PassportActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PassportActivity.java index 30a692808..5a9beecbd 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PassportActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PassportActivity.java @@ -192,7 +192,7 @@ public class PassportActivity extends BaseFragment implements NotificationCenter private String initialValues; private int currentActivityType; - private int currentBotId; + private long currentBotId; private String currentPayload; private String currentNonce; private boolean useCurrentValue; @@ -666,7 +666,7 @@ public class PassportActivity extends BaseFragment implements NotificationCenter } } - public PassportActivity(int type, int botId, String scope, String publicKey, String payload, String nonce, String callbackUrl, TLRPC.TL_account_authorizationForm form, TLRPC.TL_account_password accountPassword) { + public PassportActivity(int type, long botId, String scope, String publicKey, String payload, String nonce, String callbackUrl, TLRPC.TL_account_authorizationForm form, TLRPC.TL_account_password accountPassword) { this(type, form, accountPassword, null, null, null, null, null, null); currentBotId = botId; currentPayload = payload; @@ -2860,12 +2860,12 @@ public class PassportActivity extends BaseFragment implements NotificationCenter } if (event.getAction() == MotionEvent.ACTION_UP) { CountrySelectActivity fragment = new CountrySelectActivity(false); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - inputFields[FIELD_PHONECOUNTRY].setText(name); - int index = countriesArray.indexOf(name); + fragment.setCountrySelectActivityDelegate(country -> { + inputFields[FIELD_PHONECOUNTRY].setText(country.name); + int index = countriesArray.indexOf(country.name); if (index != -1) { ignoreOnTextChange = true; - String code = countriesMap.get(name); + String code = countriesMap.get(country.name); inputFields[FIELD_PHONECODE].setText(code); String hint = phoneFormatMap.get(code); inputFields[FIELD_PHONE].setHintText(hint != null ? hint.replace('X', '–') : null); @@ -3355,9 +3355,9 @@ public class PassportActivity extends BaseFragment implements NotificationCenter } if (event.getAction() == MotionEvent.ACTION_UP) { CountrySelectActivity fragment = new CountrySelectActivity(false); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - inputFields[FIELD_COUNTRY].setText(name); - currentCitizeship = shortName; + fragment.setCountrySelectActivityDelegate((country) -> { + inputFields[FIELD_COUNTRY].setText(country.name); + currentCitizeship = country.shortname; }); presentFragment(fragment); } @@ -3694,7 +3694,7 @@ public class PassportActivity extends BaseFragment implements NotificationCenter for (int a = 0, size = translationDocuments.size(); a < size; a++) { SecureDocument document = translationDocuments.get(a); String key = "translation" + getDocumentHash(document); - if (key != null && errorsValues.containsKey(key)) { + if (errorsValues.containsKey(key)) { onFieldError(documentsCells.get(document)); return true; } @@ -4150,15 +4150,15 @@ public class PassportActivity extends BaseFragment implements NotificationCenter } if (event.getAction() == MotionEvent.ACTION_UP) { CountrySelectActivity fragment = new CountrySelectActivity(false); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { + fragment.setCountrySelectActivityDelegate((country) -> { int field12 = (Integer) v.getTag(); final EditTextBoldCursor editText = inputFields[field12]; if (field12 == FIELD_CITIZENSHIP) { - currentCitizeship = shortName; + currentCitizeship = country.shortname; } else { - currentResidence = shortName; + currentResidence = country.shortname; } - editText.setText(name); + editText.setText(country.name); }); presentFragment(fragment); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PaymentFormActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PaymentFormActivity.java index 6e98327a7..d3052b0c9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PaymentFormActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PaymentFormActivity.java @@ -639,9 +639,9 @@ public class PaymentFormActivity extends BaseFragment implements NotificationCen } if (event.getAction() == MotionEvent.ACTION_UP) { CountrySelectActivity fragment = new CountrySelectActivity(false); - fragment.setCountrySelectActivityDelegate((name, shortName) -> { - inputFields[FIELD_COUNTRY].setText(name); - countryName = shortName; + fragment.setCountrySelectActivityDelegate((country) -> { + inputFields[FIELD_COUNTRY].setText(country.name); + countryName = country.shortname; }); presentFragment(fragment); } @@ -1181,7 +1181,7 @@ public class PaymentFormActivity extends BaseFragment implements NotificationCen } if (event.getAction() == MotionEvent.ACTION_UP) { CountrySelectActivity fragment = new CountrySelectActivity(false); - fragment.setCountrySelectActivityDelegate((name, shortName) -> inputFields[FIELD_CARD_COUNTRY].setText(name)); + fragment.setCountrySelectActivityDelegate((country) -> inputFields[FIELD_CARD_COUNTRY].setText(country.name)); presentFragment(fragment); } return true; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PeopleNearbyActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PeopleNearbyActivity.java index 2b6354524..04bba9e58 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PeopleNearbyActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PeopleNearbyActivity.java @@ -367,7 +367,7 @@ public class PeopleNearbyActivity extends BaseFragment implements NotificationCe ManageChatUserCell cell = (ManageChatUserCell) view; TLRPC.TL_peerLocated peerLocated = users.get(position - usersStartRow); Bundle args1 = new Bundle(); - args1.putInt("user_id", peerLocated.peer.user_id); + args1.putLong("user_id", peerLocated.peer.user_id); if (cell.hasAvatarSet()) { args1.putBoolean("expandPhoto", true); } @@ -378,13 +378,13 @@ public class PeopleNearbyActivity extends BaseFragment implements NotificationCe } else if (position >= chatsStartRow && position < chatsEndRow) { TLRPC.TL_peerLocated peerLocated = chats.get(position - chatsStartRow); Bundle args1 = new Bundle(); - int chatId; + long chatId; if (peerLocated.peer instanceof TLRPC.TL_peerChat) { chatId = peerLocated.peer.chat_id; } else { chatId = peerLocated.peer.channel_id; } - args1.putInt("chat_id", chatId); + args1.putLong("chat_id", chatId); ChatActivity chatActivity = new ChatActivity(args1); presentFragment(chatActivity); } else if (position == chatsCreateRow) { @@ -781,7 +781,7 @@ public class PeopleNearbyActivity extends BaseFragment implements NotificationCe if (ChatObject.isNotInChat(chat)) { getMessagesController().deleteDialog(dialogId, 0, revoke); } else { - getMessagesController().deleteParticipantFromChat((int) -dialogId, getMessagesController().getUser(getUserConfig().getClientUserId()), null, null, revoke, revoke); + getMessagesController().deleteParticipantFromChat(-dialogId, getMessagesController().getUser(getUserConfig().getClientUserId()), null, null, revoke, revoke); } } else { getMessagesController().deleteDialog(dialogId, 0, revoke); @@ -978,7 +978,7 @@ public class PeopleNearbyActivity extends BaseFragment implements NotificationCe } else if (position >= chatsStartRow && position < chatsEndRow) { int index = position - chatsStartRow; TLRPC.TL_peerLocated peerLocated = chats.get(index); - int chatId; + long chatId; if (peerLocated.peer instanceof TLRPC.TL_peerChat) { chatId = peerLocated.peer.chat_id; } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java index 62f711966..f8b279d27 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoAlbumPickerActivity.java @@ -479,7 +479,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati } else { itemCells[a].setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_schedule); } - } else if (num == 1) { + } else { itemCells[a].setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off); } itemCells[a].setMinimumWidth(AndroidUtilities.dp(196)); @@ -494,7 +494,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, notify, scheduleDate); finishFragment(); }); - } else if (num == 1) { + } else { sendSelectedPhotos(selectedPhotos, selectedPhotosOrder, true, 0); finishFragment(); } @@ -555,7 +555,7 @@ public class PhotoAlbumPickerActivity extends BaseFragment implements Notificati commentTextView.setVisibility(View.GONE); } - if (loading && (albumsSorted == null || albumsSorted != null && albumsSorted.isEmpty())) { + if (loading && (albumsSorted == null || albumsSorted.isEmpty())) { progressView.setVisibility(View.VISIBLE); listView.setEmptyView(null); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java index 1f5e52d7c..99269da11 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoCropActivity.java @@ -69,160 +69,157 @@ public class PhotoCropActivity extends BaseFragment { halfPaint.setColor(0xc8000000); setBackgroundColor(0xff333333); - setOnTouchListener(new OnTouchListener() { - @Override - public boolean onTouch(View view, MotionEvent motionEvent) { - float x = motionEvent.getX(); - float y = motionEvent.getY(); - int cornerSide = AndroidUtilities.dp(14); - if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { - if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide < y && rectY + cornerSide > y) { - draggingState = 1; - } else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide < y && rectY + cornerSide > y) { - draggingState = 2; - } else if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) { - draggingState = 3; - } else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) { - draggingState = 4; - } else if (rectX < x && rectX + rectSizeX > x && rectY < y && rectY + rectSizeY > y) { - draggingState = 5; - } else { - draggingState = 0; - } - if (draggingState != 0) { - PhotoCropView.this.requestDisallowInterceptTouchEvent(true); - } - oldX = x; - oldY = y; - } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { + setOnTouchListener((view, motionEvent) -> { + float x = motionEvent.getX(); + float y = motionEvent.getY(); + int cornerSide = AndroidUtilities.dp(14); + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide < y && rectY + cornerSide > y) { + draggingState = 1; + } else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide < y && rectY + cornerSide > y) { + draggingState = 2; + } else if (rectX - cornerSide < x && rectX + cornerSide > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) { + draggingState = 3; + } else if (rectX - cornerSide + rectSizeX < x && rectX + cornerSide + rectSizeX > x && rectY - cornerSide + rectSizeY < y && rectY + cornerSide + rectSizeY > y) { + draggingState = 4; + } else if (rectX < x && rectX + rectSizeX > x && rectY < y && rectY + rectSizeY > y) { + draggingState = 5; + } else { draggingState = 0; - } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && draggingState != 0) { - float diffX = x - oldX; - float diffY = y - oldY; - if (draggingState == 5) { - rectX += diffX; - rectY += diffY; + } + if (draggingState != 0) { + PhotoCropView.this.requestDisallowInterceptTouchEvent(true); + } + oldX = x; + oldY = y; + } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { + draggingState = 0; + } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && draggingState != 0) { + float diffX = x - oldX; + float diffY = y - oldY; + if (draggingState == 5) { + rectX += diffX; + rectY += diffY; - if (rectX < bitmapX) { - rectX = bitmapX; - } else if (rectX + rectSizeX > bitmapX + bitmapWidth) { - rectX = bitmapX + bitmapWidth - rectSizeX; + if (rectX < bitmapX) { + rectX = bitmapX; + } else if (rectX + rectSizeX > bitmapX + bitmapWidth) { + rectX = bitmapX + bitmapWidth - rectSizeX; + } + if (rectY < bitmapY) { + rectY = bitmapY; + } else if (rectY + rectSizeY > bitmapY + bitmapHeight) { + rectY = bitmapY + bitmapHeight - rectSizeY; + } + } else { + if (draggingState == 1) { + if (rectSizeX - diffX < 160) { + diffX = rectSizeX - 160; } - if (rectY < bitmapY) { - rectY = bitmapY; - } else if (rectY + rectSizeY > bitmapY + bitmapHeight) { - rectY = bitmapY + bitmapHeight - rectSizeY; + if (rectX + diffX < bitmapX) { + diffX = bitmapX - rectX; } - } else { - if (draggingState == 1) { - if (rectSizeX - diffX < 160) { - diffX = rectSizeX - 160; + if (!freeform) { + if (rectY + diffX < bitmapY) { + diffX = bitmapY - rectY; } - if (rectX + diffX < bitmapX) { - diffX = bitmapX - rectX; + rectX += diffX; + rectY += diffX; + rectSizeX -= diffX; + rectSizeY -= diffX; + } else { + if (rectSizeY - diffY < 160) { + diffY = rectSizeY - 160; } - if (!freeform) { - if (rectY + diffX < bitmapY) { - diffX = bitmapY - rectY; - } - rectX += diffX; - rectY += diffX; - rectSizeX -= diffX; - rectSizeY -= diffX; - } else { - if (rectSizeY - diffY < 160) { - diffY = rectSizeY - 160; - } - if (rectY + diffY < bitmapY) { - diffY = bitmapY - rectY; - } - rectX += diffX; - rectY += diffY; - rectSizeX -= diffX; - rectSizeY -= diffY; + if (rectY + diffY < bitmapY) { + diffY = bitmapY - rectY; } - } else if (draggingState == 2) { - if (rectSizeX + diffX < 160) { - diffX = -(rectSizeX - 160); + rectX += diffX; + rectY += diffY; + rectSizeX -= diffX; + rectSizeY -= diffY; + } + } else if (draggingState == 2) { + if (rectSizeX + diffX < 160) { + diffX = -(rectSizeX - 160); + } + if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) { + diffX = bitmapX + bitmapWidth - rectX - rectSizeX; + } + if (!freeform) { + if (rectY - diffX < bitmapY) { + diffX = rectY - bitmapY; } - if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) { - diffX = bitmapX + bitmapWidth - rectX - rectSizeX; + rectY -= diffX; + rectSizeX += diffX; + rectSizeY += diffX; + } else { + if (rectSizeY - diffY < 160) { + diffY = rectSizeY - 160; } - if (!freeform) { - if (rectY - diffX < bitmapY) { - diffX = rectY - bitmapY; - } - rectY -= diffX; - rectSizeX += diffX; - rectSizeY += diffX; - } else { - if (rectSizeY - diffY < 160) { - diffY = rectSizeY - 160; - } - if (rectY + diffY < bitmapY) { - diffY = bitmapY - rectY; - } - rectY += diffY; - rectSizeX += diffX; - rectSizeY -= diffY; + if (rectY + diffY < bitmapY) { + diffY = bitmapY - rectY; } - } else if (draggingState == 3) { - if (rectSizeX - diffX < 160) { - diffX = rectSizeX - 160; + rectY += diffY; + rectSizeX += diffX; + rectSizeY -= diffY; + } + } else if (draggingState == 3) { + if (rectSizeX - diffX < 160) { + diffX = rectSizeX - 160; + } + if (rectX + diffX < bitmapX) { + diffX = bitmapX - rectX; + } + if (!freeform) { + if (rectY + rectSizeX - diffX > bitmapY + bitmapHeight) { + diffX = rectY + rectSizeX - bitmapY - bitmapHeight; } - if (rectX + diffX < bitmapX) { - diffX = bitmapX - rectX; - } - if (!freeform) { - if (rectY + rectSizeX - diffX > bitmapY + bitmapHeight) { - diffX = rectY + rectSizeX - bitmapY - bitmapHeight; - } - rectX += diffX; - rectSizeX -= diffX; - rectSizeY -= diffX; - } else { - if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) { - diffY = bitmapY + bitmapHeight - rectY - rectSizeY; - } - rectX += diffX; - rectSizeX -= diffX; - rectSizeY += diffY; - if (rectSizeY < 160) { - rectSizeY = 160; - } - } - } else if (draggingState == 4) { - if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) { - diffX = bitmapX + bitmapWidth - rectX - rectSizeX; - } - if (!freeform) { - if (rectY + rectSizeX + diffX > bitmapY + bitmapHeight) { - diffX = bitmapY + bitmapHeight - rectY - rectSizeX; - } - rectSizeX += diffX; - rectSizeY += diffX; - } else { - if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) { - diffY = bitmapY + bitmapHeight - rectY - rectSizeY; - } - rectSizeX += diffX; - rectSizeY += diffY; - } - if (rectSizeX < 160) { - rectSizeX = 160; + rectX += diffX; + rectSizeX -= diffX; + rectSizeY -= diffX; + } else { + if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) { + diffY = bitmapY + bitmapHeight - rectY - rectSizeY; } + rectX += diffX; + rectSizeX -= diffX; + rectSizeY += diffY; if (rectSizeY < 160) { rectSizeY = 160; } } + } else if (draggingState == 4) { + if (rectX + rectSizeX + diffX > bitmapX + bitmapWidth) { + diffX = bitmapX + bitmapWidth - rectX - rectSizeX; + } + if (!freeform) { + if (rectY + rectSizeX + diffX > bitmapY + bitmapHeight) { + diffX = bitmapY + bitmapHeight - rectY - rectSizeX; + } + rectSizeX += diffX; + rectSizeY += diffX; + } else { + if (rectY + rectSizeY + diffY > bitmapY + bitmapHeight) { + diffY = bitmapY + bitmapHeight - rectY - rectSizeY; + } + rectSizeX += diffX; + rectSizeY += diffY; + } + if (rectSizeX < 160) { + rectSizeX = 160; + } + if (rectSizeY < 160) { + rectSizeY = 160; + } } - - oldX = x; - oldY = y; - invalidate(); } - return true; + + oldX = x; + oldY = y; + invalidate(); } + return true; }); } @@ -240,10 +237,10 @@ public class PhotoCropActivity extends BaseFragment { float scaleY = viewHeight / h; if (scaleX > scaleY) { bitmapHeight = viewHeight; - bitmapWidth = (int)Math.ceil(w * scaleY); + bitmapWidth = (int) Math.ceil(w * scaleY); } else { bitmapWidth = viewWidth; - bitmapHeight = (int)Math.ceil(h * scaleX); + bitmapHeight = (int) Math.ceil(h * scaleX); } bitmapX = (viewWidth - bitmapWidth) / 2 + AndroidUtilities.dp(14); bitmapY = (viewHeight - bitmapHeight) / 2 + AndroidUtilities.dp(14); @@ -289,10 +286,10 @@ public class PhotoCropActivity extends BaseFragment { float percY = (rectY - bitmapY) / bitmapHeight; float percSizeX = rectSizeX / bitmapWidth; float percSizeY = rectSizeY / bitmapWidth; - int x = (int)(percX * imageToCrop.getWidth()); - int y = (int)(percY * imageToCrop.getHeight()); - int sizeX = (int)(percSizeX * imageToCrop.getWidth()); - int sizeY = (int)(percSizeY * imageToCrop.getWidth()); + int x = (int) (percX * imageToCrop.getWidth()); + int y = (int) (percY * imageToCrop.getHeight()); + int sizeX = (int) (percSizeX * imageToCrop.getWidth()); + int sizeY = (int) (percSizeY * imageToCrop.getWidth()); if (x < 0) { x = 0; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java index d4e296be4..3da384b43 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoPickerActivity.java @@ -50,6 +50,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; @@ -927,7 +928,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0 : Math.abs(layoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1; if (visibleItemCount > 0) { int totalItemCount = layoutManager.getItemCount(); - if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2 && !searching) { + if (firstVisibleItem + visibleItemCount > totalItemCount - 2 && !searching) { if (!imageSearchEndReached) { searchImages(type == 1, lastSearchString, nextImagesSearchOffset, true); } @@ -1085,7 +1086,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen } else { itemCells[a].setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_schedule); } - } else if (num == 1) { + } else { itemCells[a].setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off); } itemCells[a].setMinimumWidth(AndroidUtilities.dp(196)); @@ -1097,7 +1098,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen } if (num == 0) { AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), chatActivity.getDialogId(), this::sendSelectedPhotos); - } else if (num == 1) { + } else { sendSelectedPhotos(true, 0); } }); @@ -1215,7 +1216,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen Integer index = (Integer) view.getTag(); MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(index); SharedDocumentCell cell = (SharedDocumentCell) view; - cell.setChecked(selectedPhotosOrder.indexOf(photoEntry.imageId) >= 0, true); + cell.setChecked(selectedPhotosOrder.contains(photoEntry.imageId), true); } updatePhotosButton(add ? 1 : 2); delegate.selectedPhotosChanged(); @@ -1597,12 +1598,10 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen if (chatActivity != null) { long dialogId = chatActivity.getDialogId(); - int lower_id = (int) dialogId; - int high_id = (int) (dialogId >> 32); - if (lower_id != 0) { - req.peer = MessagesController.getInstance(currentAccount).getInputPeer(lower_id); - } else { + if (DialogObject.isEncryptedDialog(dialogId)) { req.peer = new TLRPC.TL_inputPeerEmpty(); + } else { + req.peer = getMessagesController().getInputPeer(dialogId); } } else { req.peer = new TLRPC.TL_inputPeerEmpty(); @@ -1642,7 +1641,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen } image.document = result.document; image.size = 0; - if (result.photo != null && result.document != null) { + if (result.photo != null) { TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(result.photo.sizes, itemSize, true); if (size != null) { result.document.thumbs.add(size); @@ -1778,7 +1777,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen View view; switch (viewType) { case 0: - PhotoAttachPhotoCell cell = new PhotoAttachPhotoCell(mContext); + PhotoAttachPhotoCell cell = new PhotoAttachPhotoCell(mContext, null); cell.setDelegate(new PhotoAttachPhotoCell.PhotoAttachPhotoCellDelegate() { private void checkSlowMode() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java index 49d0c1717..38afc23cf 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PhotoViewer.java @@ -136,6 +136,7 @@ import org.telegram.messenger.BuildConfig; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.MediaDataController; import org.telegram.messenger.Emoji; @@ -377,6 +378,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private boolean doneButtonPressed; boolean keyboardAnimationEnabled; + private Theme.ResourcesProvider resourcesProvider; private Runnable setLoadingRunnable = new Runnable() { @Override @@ -674,7 +676,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private void onLongClick(URLSpan link) { int timestamp = -1; - BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity); + BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity, false, resourcesProvider); if (link.getURL().startsWith("video?")) { try { String timestampStr = link.getURL().substring(link.getURL().indexOf('?') + 1); @@ -707,26 +709,26 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (!isMedia && currentMessageObject.replyMessageObject != null) { messageObject1 = currentMessageObject.replyMessageObject; } - int lower_id = (int) messageObject1.getDialogId(); + long dialogId = messageObject1.getDialogId(); int messageId = messageObject1.getId(); if (messageObject1.messageOwner.fwd_from != null) { if (messageObject1.messageOwner.fwd_from.saved_from_peer != null) { - lower_id = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.saved_from_peer); + dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.saved_from_peer); messageId = messageObject1.messageOwner.fwd_from.saved_from_msg_id; } else if (messageObject1.messageOwner.fwd_from.from_id != null) { - lower_id = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.from_id); + dialogId = MessageObject.getPeerId(messageObject1.messageOwner.fwd_from.from_id); messageId = messageObject1.messageOwner.fwd_from.channel_post; } } - if (lower_id < 0) { - TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId); if (currentChat != null && currentChat.username != null) { url1 = "https://t.me/" + currentChat.username + "/" + messageId + "?t=" + finalTimestamp; } } else { - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId); if (user != null && user.username != null) { url1 = "https://t.me/" + user.username + "/" + messageId + "?t=" + finalTimestamp; } @@ -744,7 +746,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { bulletinMessage = LocaleController.getString("LinkCopied", R.string.LinkCopied); } - BulletinFactory.of(containerView).createSimpleBulletin(R.raw.voip_invite, bulletinMessage).show(); + BulletinFactory.of(containerView, resourcesProvider).createSimpleBulletin(R.raw.voip_invite, bulletinMessage).show(); } }); BottomSheet bottomSheet = builder.create(); @@ -1076,7 +1078,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private boolean dontAutoPlay; boolean fromCamera; - private int avatarsDialogId; + private long avatarsDialogId; private boolean canEditAvatar; private boolean isEvent; private int sharedMediaType; @@ -1709,7 +1711,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat public int viewY; public View parentView; public ImageReceiver.BitmapHolder thumb; - public int dialogId; + public long dialogId; public int index; public int size; public int[] radius; @@ -2362,7 +2364,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat adjustPanLayoutHelper.onAttach(); Bulletin.addDelegate(this, new Bulletin.Delegate() { @Override - public int getBottomOffset() { + public int getBottomOffset(int tag) { int offset = 0; if (bottomLayout != null && bottomLayout.getVisibility() == VISIBLE) { offset += bottomLayout.getHeight(); @@ -3075,7 +3077,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } } else if (id == NotificationCenter.dialogPhotosLoaded) { int guid = (Integer) args[3]; - int did = (Integer) args[0]; + long did = (Long) args[0]; if (avatarsDialogId == did && classGuid == guid) { boolean fromCache = (Boolean) args[2]; @@ -3340,7 +3342,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (scheduled) { return; } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; ArrayList markAsDeletedMessages = (ArrayList) args[0]; boolean reset = false; boolean resetCurrent = false; @@ -3394,7 +3396,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } private void showDownloadAlert() { - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); boolean alreadyDownloading = currentMessageObject != null && currentMessageObject.isVideo() && FileLoader.getInstance(currentMessageObject.currentAccount).isLoadingFile(currentFileNames[0]); @@ -3486,7 +3488,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } public void setParentActivity(final Activity activity) { + setParentActivity(activity, null); + } + + public void setParentActivity(final Activity activity, Theme.ResourcesProvider resourcesProvider) { Theme.createChatResources(activity, false); + this.resourcesProvider = resourcesProvider; currentAccount = UserConfig.selectedAccount; centerImage.setCurrentAccount(currentAccount); leftImage.setCurrentAccount(currentAccount); @@ -3846,21 +3853,17 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (currentMessageObject != null) { dialogId = currentMessageObject.getDialogId(); } - int lower_part = (int) dialogId; - int high_id = (int) (dialogId >> 32); - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_part); - if (chat != null && chat.migrated_to != null) { - args.putInt("migrated_to", lower_part); - lower_part = -chat.migrated_to.channel_id; - } - args.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(dialogId)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + args.putLong("user_id", dialogId); } else { - args.putInt("enc_id", high_id); + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); + if (chat != null && chat.migrated_to != null) { + args.putLong("migrated_to", dialogId); + dialogId = -chat.migrated_to.channel_id; + } + args.putLong("chat_id", -dialogId); } args.putInt("message_id", currentMessageObject.getId()); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats); @@ -3902,18 +3905,14 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); } else { - args1.putInt("enc_id", high_part); + args1.putLong("chat_id", -did); } NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats); ChatActivity chatActivity = new ChatActivity(args1); @@ -3932,9 +3931,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } boolean isChannel = false; if (currentMessageObject != null && !currentMessageObject.scheduled) { - int lower_id = (int) currentMessageObject.getDialogId(); - if (lower_id < 0) { - isChannel = ChatObject.isChannel(MessagesController.getInstance(currentAccount).getChat(-lower_id)); + long dialogId = currentMessageObject.getDialogId(); + if (DialogObject.isChatDialog(dialogId)) { + isChannel = ChatObject.isChannel(MessagesController.getInstance(currentAccount).getChat(-dialogId)); } } AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); @@ -3967,16 +3966,16 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat final boolean[] deleteForAll = new boolean[1]; if (currentMessageObject != null && !currentMessageObject.scheduled) { - int lower_id = (int) currentMessageObject.getDialogId(); - if (lower_id != 0) { + long dialogId = currentMessageObject.getDialogId(); + if (!DialogObject.isEncryptedDialog(dialogId)) { TLRPC.Chat currentChat; TLRPC.User currentUser; - if (lower_id > 0) { - currentUser = MessagesController.getInstance(currentAccount).getUser(lower_id); + if (DialogObject.isUserDialog(dialogId)) { + currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId); currentChat = null; } else { currentUser = null; - currentChat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId); } if (currentUser != null || !ChatObject.isChannel(currentChat)) { boolean hasOutgoing = false; @@ -3993,7 +3992,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat boolean canRevokeInbox = currentUser != null && MessagesController.getInstance(currentAccount).canRevokePmInbox; if ((currentMessageObject.messageOwner.action == null || currentMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && (currentMessageObject.isOut() || canRevokeInbox || ChatObject.hasAdminRights(currentChat)) && (currentDate - currentMessageObject.messageOwner.date) <= revokeTimeLimit) { FrameLayout frameLayout = new FrameLayout(parentActivity); - CheckBoxCell cell = new CheckBoxCell(parentActivity, 1); + CheckBoxCell cell = new CheckBoxCell(parentActivity, 1, resourcesProvider); cell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); if (currentChat != null) { cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false); @@ -4031,13 +4030,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ArrayList random_ids = null; TLRPC.EncryptedChat encryptedChat = null; - if ((int) obj.getDialogId() == 0 && obj.messageOwner.random_id != 0) { + if (DialogObject.isEncryptedDialog(obj.getDialogId()) && obj.messageOwner.random_id != 0) { random_ids = new ArrayList<>(); random_ids.add(obj.messageOwner.random_id); - encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat((int) (obj.getDialogId() >> 32)); + encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(obj.getDialogId())); } - MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat, obj.getDialogId(), obj.messageOwner.peer_id.channel_id, deleteForAll[0], obj.scheduled); + MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat, obj.getDialogId(), deleteForAll[0], obj.scheduled); } } else if (!avatarsArr.isEmpty()) { if (currentIndex < 0 || currentIndex >= avatarsArr.size()) { @@ -4047,7 +4046,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (message != null) { ArrayList arr = new ArrayList<>(); arr.add(message.id); - MessagesController.getInstance(currentAccount).deleteMessages(arr, null, null, MessageObject.getDialogId(message), message.peer_id.channel_id, true, false); + MessagesController.getInstance(currentAccount).deleteMessages(arr, null, null, MessageObject.getDialogId(message), true, false); NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.reloadDialogPhotos); } if (isCurrentAvatarSet()) { @@ -4115,7 +4114,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat showAlertDialog(builder); TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); if (button != null) { - button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2)); + button.setTextColor(getThemedColor(Theme.key_dialogTextRed2)); } } else if (id == gallery_menu_share || id == gallery_menu_share2) { onSharePressed(); @@ -4139,7 +4138,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat Browser.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url); closePhoto(false, false); } else if (currentMessageObject != null) { - if (AndroidUtilities.openForView(currentMessageObject, parentActivity)) { + if (AndroidUtilities.openForView(currentMessageObject, parentActivity, resourcesProvider)) { closePhoto(false, false); } else { showDownloadAlert(); @@ -4166,7 +4165,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { return; } - masksAlert = new StickersAlert(parentActivity, currentMessageObject, object) { + masksAlert = new StickersAlert(parentActivity, currentMessageObject, object, resourcesProvider) { @Override public void dismiss() { super.dismiss(); @@ -4354,7 +4353,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat shareItem.setContentDescription(LocaleController.getString("ShareFile", R.string.ShareFile)); menuItem = menu.addItem(0, R.drawable.ic_ab_other); - menuItemSpeed = new ActionBarMenuItem(parentActivity, null, 0, 0); + menuItemSpeed = new ActionBarMenuItem(parentActivity, null, 0, 0, resourcesProvider); menuItemSpeed.setDelegate(id -> { if (id >= gallery_menu_speed_veryslow && id <= gallery_menu_speed_veryfast) { switch (id) { @@ -4474,7 +4473,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } @Override - public int getAvatarsDialogId() { + public long getAvatarsDialogId() { return avatarsDialogId; } @@ -4592,7 +4591,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat photoProgressViews[a].setBackgroundState(PROGRESS_EMPTY, false, true); } - miniProgressView = new RadialProgressView(activityContext) { + miniProgressView = new RadialProgressView(activityContext, resourcesProvider) { @Override public void setAlpha(float alpha) { super.setAlpha(alpha); @@ -4699,7 +4698,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat createVideoControlsInterface(); - progressView = new RadialProgressView(parentActivity); + progressView = new RadialProgressView(parentActivity, resourcesProvider); progressView.setProgressColor(0xffffffff); progressView.setBackgroundResource(R.drawable.circle_big); progressView.setVisibility(View.INVISIBLE); @@ -4710,7 +4709,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat qualityPicker.updateSelectedCount(0, false); qualityPicker.setTranslationY(AndroidUtilities.dp(120)); qualityPicker.doneButton.setText(LocaleController.getString("Done", R.string.Done).toUpperCase()); - qualityPicker.doneButton.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + qualityPicker.doneButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); containerView.addView(qualityPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT)); qualityPicker.cancelButton.setOnClickListener(view -> { selectedCompression = previousCompression; @@ -5001,11 +5000,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } }; pickerViewSendButton.setScaleType(ImageView.ScaleType.CENTER); - pickerViewSendDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_dialogFloatingButton), Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); + pickerViewSendDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton)); pickerViewSendButton.setBackgroundDrawable(pickerViewSendDrawable); pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(0xffffffff, PorterDuff.Mode.MULTIPLY)); pickerViewSendButton.setImageResource(R.drawable.attach_send); - pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); + pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); containerView.addView(pickerViewSendButton, LayoutHelper.createFrame(56, 56, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 14, 14)); pickerViewSendButton.setContentDescription(LocaleController.getString("Send", R.string.Send)); pickerViewSendButton.setOnClickListener(v -> { @@ -5096,7 +5095,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else if (a == 4 && (isCurrentVideo || timeItem.getColorFilter() != null)) { continue; } - ActionBarMenuSubItem cell = new ActionBarMenuSubItem(parentActivity, a == 0, a == 3); + ActionBarMenuSubItem cell = new ActionBarMenuSubItem(parentActivity, a == 0, a == 3, resourcesProvider); if (a == 0) { if (UserObject.isUserSelf(user)) { cell.setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule); @@ -5249,7 +5248,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return; } if (photoCropView.rotate()) { - rotateItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + rotateItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } else { rotateItem.setColorFilter(null); } @@ -5266,7 +5265,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return; } if (photoCropView.mirror()) { - mirrorItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + mirrorItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } else { mirrorItem.setColorFilter(null); } @@ -5405,7 +5404,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (parentActivity == null || captionEditText.getTag() != null) { return; } - BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity); + BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity, false, resourcesProvider); builder.setUseHardwareLayer(false); LinearLayout linearLayout = new LinearLayout(parentActivity); linearLayout.setOrientation(LinearLayout.VERTICAL); @@ -5435,7 +5434,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat titleView.setOnTouchListener((v12, event) -> true); final BottomSheet bottomSheet = builder.create(); - final NumberPicker numberPicker = new NumberPicker(parentActivity); + final NumberPicker numberPicker = new NumberPicker(parentActivity, resourcesProvider); numberPicker.setMinValue(0); numberPicker.setMaxValue(28); Object object = imagesArrLocals.get(currentIndex); @@ -5495,7 +5494,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat textView.setMinWidth(AndroidUtilities.dp(64)); textView.setTag(Dialog.BUTTON_POSITIVE); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); - textView.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + textView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); textView.setGravity(Gravity.CENTER); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setText(LocaleController.getString("Done", R.string.Done).toUpperCase()); @@ -5521,7 +5520,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else if (object1 instanceof MediaController.SearchImage) { ((MediaController.SearchImage) object1).ttl = seconds; } - timeItem.setColorFilter(seconds != 0 ? new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY) : null); + timeItem.setColorFilter(seconds != 0 ? new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY) : null); if (!checkImageView.isChecked()) { checkImageView.callOnClick(); } @@ -5624,7 +5623,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat checkImageView.setHasBorder(true); checkImageView.setSize(34); checkImageView.setCheckOffset(AndroidUtilities.dp(1)); - checkImageView.setColor(Theme.getColor(Theme.key_dialogFloatingButton), 0xffffffff); + checkImageView.setColor(getThemedColor(Theme.key_dialogFloatingButton), 0xffffffff); checkImageView.setVisibility(View.GONE); containerView.addView(checkImageView, LayoutHelper.createFrame(34, 34, Gravity.RIGHT | Gravity.TOP, 0, rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 61 : 71, 11, 0)); if (isStatusBarVisible()) { @@ -5683,7 +5682,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ignoreDidSetImage = false; }); - captionEditText = new PhotoViewerCaptionEnterView(activityContext, containerView, windowView) { + captionEditText = new PhotoViewerCaptionEnterView(activityContext, containerView, windowView, resourcesProvider) { @Override public boolean dispatchTouchEvent(MotionEvent ev) { try { @@ -5730,7 +5729,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null && text != null) { mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(), parentChatActivity.messages, false, false); } - int color = Theme.getColor(Theme.key_dialogFloatingIcon); + int color = getThemedColor(Theme.key_dialogFloatingIcon); if (captionEditText.getCaptionLimitOffset() < 0) { captionLimitView.setText(Integer.toString(captionEditText.getCaptionLimitOffset())); captionLimitView.setVisibility(pickerViewSendButton.getVisibility()); @@ -5803,7 +5802,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat captionEditText.setVisibility(View.GONE); containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT)); - mentionListView = new RecyclerListView(activityContext) { + mentionListView = new RecyclerListView(activityContext, resourcesProvider) { @Override public boolean dispatchTouchEvent(MotionEvent ev) { return !bottomTouchEnabled && super.dispatchTouchEvent(ev); @@ -5834,7 +5833,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat mentionListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER); containerView.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM)); - mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(activityContext, true, 0, new MentionsAdapter.MentionsAdapterDelegate() { + mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(activityContext, true, 0, 0, new MentionsAdapter.MentionsAdapterDelegate() { @Override public void needChangePanelVisibility(boolean show) { if (show) { @@ -5915,7 +5914,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat public void onContextClick(TLRPC.BotInlineResult result) { } - })); + }, resourcesProvider)); mentionListView.setOnItemClickListener((view, position) -> { Object object = mentionsAdapter.getItem(position); @@ -5943,7 +5942,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat mentionListView.setOnItemLongClickListener((view, position) -> { Object object = mentionsAdapter.getItem(position); if (object instanceof String) { - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch)); builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> mentionsAdapter.clearRecentHashtags()); @@ -5954,7 +5953,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return false; }); - hintView = new UndoView(activityContext); + hintView = new UndoView(activityContext, null, false, resourcesProvider); hintView.setAdditionalTranslationY(AndroidUtilities.dp(112)); hintView.setColors(0xf9222222, 0xffffffff); containerView.addView(hintView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8)); @@ -6383,7 +6382,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return; } if (show && !videoPreviewFrame.isReady()) { - needShowOnReady = show; + needShowOnReady = true; return; } if (videoPreviewFrameAnimation != null) { @@ -6790,15 +6789,15 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } public void updateColors() { - int color = Theme.getColor(Theme.key_dialogFloatingButton); + int color = getThemedColor(Theme.key_dialogFloatingButton); if (pickerViewSendButton != null) { Drawable drawable = pickerViewSendButton.getBackground(); Theme.setSelectorDrawableColor(drawable, color, false); - Theme.setSelectorDrawableColor(drawable, Theme.getColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton), true); - pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); + Theme.setSelectorDrawableColor(drawable, getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton), true); + pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY)); } if (checkImageView != null) { - checkImageView.setColor(Theme.getColor(Theme.key_dialogFloatingButton), 0xffffffff); + checkImageView.setColor(getThemedColor(Theme.key_dialogFloatingButton), 0xffffffff); } PorterDuffColorFilter filter = new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY); if (timeItem != null && timeItem.getColorFilter() != null) { @@ -7143,12 +7142,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (!menuItem.isSubItemVisible(gallery_menu_openin)) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setMessage(LocaleController.getString("CantPlayVideo", R.string.CantPlayVideo)); builder.setPositiveButton(LocaleController.getString("Open", R.string.Open), (dialog, which) -> { try { - AndroidUtilities.openForView(currentMessageObject, parentActivity); + AndroidUtilities.openForView(currentMessageObject, parentActivity, resourcesProvider); closePhoto(false, false); } catch (Exception e1) { FileLog.e(e1); @@ -8047,14 +8046,14 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } if (currentEditMode == 1) { entry.isCropped = true; - cropItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + cropItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } else if (currentEditMode == 2) { entry.isFiltered = true; - tuneItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + tuneItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } else if (currentEditMode == 3) { if (hasChanged) { entry.isPainted = true; - paintItem.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); + paintItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY)); } } @@ -8125,7 +8124,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (photoCropView != null) { return; } - photoCropView = new PhotoCropView(activityContext); + photoCropView = new PhotoCropView(activityContext, resourcesProvider); photoCropView.setVisibility(View.GONE); photoCropView.onDisappear(); int index = containerView.indexOfChild(videoTimelineView); @@ -8467,7 +8466,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat photoCropView.onAppear(); editorDoneLayout.doneButton.setText(LocaleController.getString("Crop", R.string.Crop)); - editorDoneLayout.doneButton.setTextColor(Theme.getColor(Theme.key_dialogFloatingButton)); + editorDoneLayout.doneButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton)); changeModeAnimation = new AnimatorSet(); ArrayList arrayList = new ArrayList<>(); @@ -8621,7 +8620,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { hasFaces = currentImageHasFace == 1 ? 1 : 0; } - photoFilterView = new PhotoFilterView(parentActivity, videoTextureView != null ? (VideoEditTextureView) videoTextureView : null, bitmap, orientation, state, isCurrentVideo ? null : paintingOverlay, hasFaces, videoTextureView == null && (editState.cropState != null && editState.cropState.mirrored || cropTransform.isMirrored())); + photoFilterView = new PhotoFilterView(parentActivity, videoTextureView != null ? (VideoEditTextureView) videoTextureView : null, bitmap, orientation, state, isCurrentVideo ? null : paintingOverlay, hasFaces, videoTextureView == null && (editState.cropState != null && editState.cropState.mirrored || cropTransform.isMirrored()), resourcesProvider); containerView.addView(photoFilterView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); photoFilterView.getDoneTextView().setOnClickListener(v -> { applyCurrentEditMode(); @@ -8632,7 +8631,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (parentActivity == null) { return; } - AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); + AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider); builder.setMessage(LocaleController.getString("DiscardChanges", R.string.DiscardChanges)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> switchToEditMode(0)); @@ -8816,7 +8815,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { state = editState.cropState; } - photoPaintView = new PhotoPaintView(parentActivity, bitmap, isCurrentVideo ? null : centerImage.getBitmap(), centerImage.getOrientation(), editState.mediaEntities, state, () -> paintingOverlay.hideBitmap()) { + photoPaintView = new PhotoPaintView(parentActivity, bitmap, isCurrentVideo ? null : centerImage.getBitmap(), centerImage.getOrientation(), editState.mediaEntities, state, () -> paintingOverlay.hideBitmap(), resourcesProvider) { @Override protected void onOpenCloseStickersAlert(boolean open) { if (videoPlayer == null) { @@ -9906,7 +9905,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat mentionsAdapter.setChatInfo(parentChatActivity.chatInfo); mentionsAdapter.setNeedUsernames(parentChatActivity.currentChat != null); mentionsAdapter.setNeedBotContext(false); - needCaptionLayout = allowCaption && (placeProvider == null || placeProvider != null && placeProvider.allowCaption()); + needCaptionLayout = allowCaption && (placeProvider == null || placeProvider.allowCaption()); captionEditText.setVisibility(needCaptionLayout ? View.VISIBLE : View.GONE); if (needCaptionLayout) { captionEditText.onCreate(); @@ -10053,7 +10052,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { setItemVisible(pipItem, true, !masksItemVisible); } - if (newMessageObject.hasAttachedStickers() && (int) newMessageObject.getDialogId() != 0) { + if (newMessageObject.hasAttachedStickers() && !DialogObject.isEncryptedDialog(newMessageObject.getDialogId())) { menuItem.showSubItem(gallery_menu_masks2); } else { menuItem.hideSubItem(gallery_menu_masks2); @@ -10061,7 +10060,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else { menuItem.hideSubItem(gallery_menu_openin); final boolean pipItemVisible = pipItem.getVisibility() == View.VISIBLE; - final boolean shouldMasksItemBeVisible = newMessageObject.hasAttachedStickers() && (int) newMessageObject.getDialogId() != 0; + final boolean shouldMasksItemBeVisible = newMessageObject.hasAttachedStickers() && !DialogObject.isEncryptedDialog(newMessageObject.getDialogId()); if (pipItemVisible) { setItemVisible(pipItem, false, !shouldMasksItemBeVisible); } @@ -10187,7 +10186,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } else if (newMessageObject.getDocument() != null) { actionBar.setTitle(LocaleController.getString("AttachDocument", R.string.AttachDocument)); } - if ((int) currentDialogId == 0 && !isEmbedVideo) { + if (DialogObject.isEncryptedDialog(currentDialogId) && !isEmbedVideo) { setItemVisible(sendItem, false, false); } if (isEmbedVideo || newMessageObject.messageOwner.ttl != 0 && newMessageObject.messageOwner.ttl < 60 * 60) { @@ -10441,7 +10440,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat } updateCaptionTextForCurrentPhoto(object); - PorterDuffColorFilter filter = new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY); + PorterDuffColorFilter filter = new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY); timeItem.setColorFilter(ttl != 0 ? filter : null); paintItem.setColorFilter(isPainted ? filter : null); cropItem.setColorFilter(isCropped ? filter : null); @@ -11132,7 +11131,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat f2 = FileLoader.getPathToMessage(messageObject.messageOwner); } if (messageObject.isVideo()) { - canStream = SharedConfig.streamMedia && messageObject.canStreamVideo() && (int) messageObject.getDialogId() != 0; + canStream = SharedConfig.streamMedia && messageObject.canStreamVideo() && !DialogObject.isEncryptedDialog(messageObject.getDialogId()); isVideo = true; } } else if (currentBotInlineResult != null) { @@ -11480,7 +11479,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat if (currentThumb != null && imageReceiver == centerImage) { placeHolder = currentThumb; } - TLRPC.PhotoSize thumbLocation = messageObject != null ? FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 100) : null; + TLRPC.PhotoSize thumbLocation = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 100); int size = (int) (2048 / AndroidUtilities.density); imageReceiver.setImage(ImageLocation.getForDocument(document), String.format(Locale.US, "%d_%d", size, size), placeHolder == null ? ImageLocation.getForDocument(thumbLocation, document) : null, "b", placeHolder != null ? new BitmapDrawable(placeHolder.bitmap) : null, document.size, null, messageObject, 0); } else { @@ -14117,7 +14116,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat file = FileLoader.getPathToMessage(currentMessageObject.messageOwner); if (!file.exists()) { file = null; - if (SharedConfig.streamMedia && (int) currentMessageObject.getDialogId() != 0 && currentMessageObject.isVideo() && currentMessageObject.canStreamVideo()) { + if (SharedConfig.streamMedia && !DialogObject.isEncryptedDialog(currentMessageObject.getDialogId()) && currentMessageObject.isVideo() && currentMessageObject.canStreamVideo()) { try { int reference = FileLoader.getInstance(currentMessageObject.currentAccount).getFileReference(currentMessageObject); FileLoader.getInstance(currentAccount).loadFile(currentMessageObject.getDocument(), currentMessageObject, 1, 0); @@ -15083,14 +15082,15 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat private int selectCompression() { SharedPreferences preferences = MessagesController.getGlobalMainSettings(); int compressionsCount = this.compressionsCount; + int maxCompression = 2; while (compressionsCount < 5) { int selectedCompression = preferences.getInt(String.format(Locale.US, "compress_video_%d", compressionsCount), -1); if (selectedCompression >= 0) { - return selectedCompression; + return Math.min(selectedCompression, maxCompression); } compressionsCount++; } - return Math.round(DownloadController.getInstance(currentAccount).getMaxVideoBitrate() / (100f / compressionsCount)) - 1; + return Math.min(maxCompression, Math.round(DownloadController.getInstance(currentAccount).getMaxVideoBitrate() / (100f / compressionsCount)) - 1); } private void updateCompressionsCount(int h, int w) { @@ -15247,4 +15247,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat return 0; } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java index 1213a1ad3..1890a4c13 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PopupNotificationActivity.java @@ -39,6 +39,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.DownloadController; import org.telegram.messenger.ImageLocation; import org.telegram.messenger.LocaleController; @@ -176,7 +177,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC statusDrawables[0] = new TypingDotsDrawable(false); statusDrawables[1] = new RecordStatusDrawable(false); statusDrawables[2] = new SendingFileDrawable(false); - statusDrawables[3] = new PlayingGameDrawable(false); + statusDrawables[3] = new PlayingGameDrawable(false, null); statusDrawables[4] = new RoundStatusDrawable(false); SizeNotifierFrameLayout contentView = new SizeNotifierFrameLayout(this) { @@ -1249,16 +1250,13 @@ public class PopupNotificationActivity extends Activity implements NotificationC return; } Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class); - long dialog_id = currentMessageObject.getDialogId(); - if ((int) dialog_id != 0) { - int lower_id = (int) dialog_id; - if (lower_id < 0) { - intent.putExtra("chatId", -lower_id); - } else { - intent.putExtra("userId", lower_id); - } - } else { - intent.putExtra("encId", (int) (dialog_id >> 32)); + long dialogId = currentMessageObject.getDialogId(); + if (DialogObject.isEncryptedDialog(dialogId)) { + intent.putExtra("encId", DialogObject.getEncryptedChatId(dialogId)); + } else if (DialogObject.isUserDialog(dialogId)) { + intent.putExtra("userId", dialogId); + } else if (DialogObject.isChatDialog(dialogId)) { + intent.putExtra("chatId", -dialogId); } intent.putExtra("currentAccount", currentMessageObject.currentAccount); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); @@ -1281,21 +1279,18 @@ public class PopupNotificationActivity extends Activity implements NotificationC } currentChat = null; currentUser = null; - long dialog_id = currentMessageObject.getDialogId(); - chatActivityEnterView.setDialogId(dialog_id, currentMessageObject.currentAccount); - if ((int) dialog_id != 0) { - int lower_id = (int) dialog_id; - if (lower_id > 0) { - currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(lower_id); - } else { - currentChat = MessagesController.getInstance(currentMessageObject.currentAccount).getChat(-lower_id); - if (currentMessageObject.isFromUser()) { - currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(currentMessageObject.messageOwner.from_id.user_id); - } - } - } else { - TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentMessageObject.currentAccount).getEncryptedChat((int) (dialog_id >> 32)); + long dialogId = currentMessageObject.getDialogId(); + chatActivityEnterView.setDialogId(dialogId, currentMessageObject.currentAccount); + if (DialogObject.isEncryptedDialog(dialogId)) { + TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance(currentMessageObject.currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(encryptedChat.user_id); + } else if (DialogObject.isUserDialog(dialogId)) { + currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(dialogId); + } else if (DialogObject.isChatDialog(dialogId)) { + currentChat = MessagesController.getInstance(currentMessageObject.currentAccount).getChat(-dialogId); + if (currentMessageObject.isFromUser()) { + currentUser = MessagesController.getInstance(currentMessageObject.currentAccount).getUser(currentMessageObject.messageOwner.from_id.user_id); + } } if (currentChat != null) { @@ -1309,7 +1304,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC nameTextView.setCompoundDrawablePadding(0); } else if (currentUser != null) { nameTextView.setText(UserObject.getUserName(currentUser)); - if ((int) dialog_id == 0) { + if (DialogObject.isEncryptedDialog(dialogId)) { nameTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_white, 0, 0, 0); nameTextView.setCompoundDrawablePadding(AndroidUtilities.dp(4)); } else { @@ -1498,7 +1493,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC } if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) { CharSequence printString = MessagesController.getInstance(currentMessageObject.currentAccount).getPrintingString(currentMessageObject.getDialogId(), 0, false); - if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) { + if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && !lastPrintString.equals(printString)) { updateSubtitle(); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PrivacyControlActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PrivacyControlActivity.java index 84b92e02d..c4053e3eb 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PrivacyControlActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PrivacyControlActivity.java @@ -25,6 +25,7 @@ import android.widget.FrameLayout; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; @@ -69,12 +70,12 @@ public class PrivacyControlActivity extends BaseFragment implements Notification private int initialRulesType; private int initialRulesSubType; - private ArrayList initialPlus = new ArrayList<>(); - private ArrayList initialMinus = new ArrayList<>(); + private ArrayList initialPlus = new ArrayList<>(); + private ArrayList initialMinus = new ArrayList<>(); private int rulesType; - private ArrayList currentPlus; - private ArrayList currentMinus; + private ArrayList currentPlus; + private ArrayList currentMinus; private int currentType; private int currentSubType; @@ -348,12 +349,12 @@ public class PrivacyControlActivity extends BaseFragment implements Notification listView.setAdapter(listAdapter); listView.setOnItemClickListener((view, position) -> { if (position == nobodyRow || position == everybodyRow || position == myContactsRow) { - int newType = currentType; + int newType; if (position == nobodyRow) { newType = TYPE_NOBODY; } else if (position == everybodyRow) { newType = TYPE_EVERYBODY; - } else if (position == myContactsRow) { + } else { newType = TYPE_CONTACTS; } if (newType == currentType) { @@ -363,10 +364,10 @@ public class PrivacyControlActivity extends BaseFragment implements Notification updateDoneButton(); updateRows(true); } else if (position == phoneContactsRow || position == phoneEverybodyRow) { - int newType = currentSubType; + int newType; if (position == phoneEverybodyRow) { newType = 0; - } else if (position == phoneContactsRow) { + } else { newType = 1; } if (newType == currentSubType) { @@ -376,7 +377,7 @@ public class PrivacyControlActivity extends BaseFragment implements Notification updateDoneButton(); updateRows(true); } else if (position == neverShareRow || position == alwaysShareRow) { - ArrayList createFromArray; + ArrayList createFromArray; if (position == neverShareRow) { createFromArray = currentMinus; } else { @@ -491,8 +492,8 @@ public class PrivacyControlActivity extends BaseFragment implements Notification TLRPC.TL_inputPrivacyValueAllowUsers usersRule = new TLRPC.TL_inputPrivacyValueAllowUsers(); TLRPC.TL_inputPrivacyValueAllowChatParticipants chatsRule = new TLRPC.TL_inputPrivacyValueAllowChatParticipants(); for (int a = 0; a < currentPlus.size(); a++) { - int id = currentPlus.get(a); - if (id > 0) { + long id = currentPlus.get(a); + if (DialogObject.isUserDialog(id)) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id); if (user != null) { TLRPC.InputUser inputUser = MessagesController.getInstance(currentAccount).getInputUser(user); @@ -511,8 +512,8 @@ public class PrivacyControlActivity extends BaseFragment implements Notification TLRPC.TL_inputPrivacyValueDisallowUsers usersRule = new TLRPC.TL_inputPrivacyValueDisallowUsers(); TLRPC.TL_inputPrivacyValueDisallowChatParticipants chatsRule = new TLRPC.TL_inputPrivacyValueDisallowChatParticipants(); for (int a = 0; a < currentMinus.size(); a++) { - int id = currentMinus.get(a); - if (id > 0) { + long id = currentMinus.get(a); + if (DialogObject.isUserDialog(id)) { TLRPC.User user = getMessagesController().getUser(id); if (user != null) { TLRPC.InputUser inputUser = getMessagesController().getInputUser(user); @@ -761,10 +762,10 @@ public class PrivacyControlActivity extends BaseFragment implements Notification } radioCell.setChecked(currentType == checkedType, true); } else { - int checkedType = 0; + int checkedType; if (position == phoneContactsRow) { checkedType = 1; - } else if (position == phoneEverybodyRow) { + } else { checkedType = 0; } radioCell.setChecked(currentSubType == checkedType, true); @@ -937,10 +938,10 @@ public class PrivacyControlActivity extends BaseFragment implements Notification return new RecyclerListView.Holder(view); } - private int getUsersCount(ArrayList arrayList) { + private int getUsersCount(ArrayList arrayList) { int count = 0; for (int a = 0; a < arrayList.size(); a++) { - int id = arrayList.get(a); + long id = arrayList.get(a); if (id > 0) { count++; } else { @@ -1089,7 +1090,7 @@ public class PrivacyControlActivity extends BaseFragment implements Notification } else { radioCell.setText(LocaleController.getString("LastSeenContacts", R.string.LastSeenContacts), currentType == TYPE_CONTACTS, nobodyRow != -1); } - } else if (position == nobodyRow) { + } else { if (rulesType == PRIVACY_RULES_TYPE_P2P) { radioCell.setText(LocaleController.getString("P2PNobody", R.string.P2PNobody), currentType == TYPE_NOBODY, false); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java index ea64f5bf8..b6d9ca1f7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PrivacySettingsActivity.java @@ -342,7 +342,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("SyncContactsDeleteText", R.string.SyncContactsDeleteText))); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> { - AlertDialog.Builder builder12 = new AlertDialog.Builder(getParentActivity(), 3); + AlertDialog.Builder builder12 = new AlertDialog.Builder(getParentActivity(), 3, null); progressDialog = builder12.show(); progressDialog.setCanCacnel(false); @@ -383,8 +383,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2)); } } else { - newSuggest = !newSuggest; - cell.setChecked(newSuggest); + cell.setChecked(newSuggest = true); } } else if (position == newChatsRow) { final TextCheckCell cell = (TextCheckCell) view; @@ -396,7 +395,7 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio ((TextCheckCell) view).setChecked(newSync); } } else if (position == secretMapRow) { - AlertsCreator.showSecretLocationAlert(getParentActivity(), currentAccount, () -> listAdapter.notifyDataSetChanged(), false); + AlertsCreator.showSecretLocationAlert(getParentActivity(), currentAccount, () -> listAdapter.notifyDataSetChanged(), false, null); } else if (position == paymentsClearRow) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("PrivacyPaymentsClearAlertTitle", R.string.PrivacyPaymentsClearAlertTitle)); @@ -407,14 +406,14 @@ public class PrivacySettingsActivity extends BaseFragment implements Notificatio builder.setView(linearLayout); for (int a = 0; a < 2; a++) { - String name = null; + String name; if (a == 0) { name = LocaleController.getString("PrivacyClearShipping", R.string.PrivacyClearShipping); - } else if (a == 1) { + } else { name = LocaleController.getString("PrivacyClearPayment", R.string.PrivacyClearPayment); } clear[a] = true; - CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 1, 21); + CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 1, 21, null); checkBoxCell.setTag(a); checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false)); checkBoxCell.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/PrivacyUsersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/PrivacyUsersActivity.java index c44e27b4e..83bdb80e8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/PrivacyUsersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/PrivacyUsersActivity.java @@ -16,6 +16,7 @@ import android.view.ViewGroup; import android.widget.FrameLayout; import org.telegram.PhoneFormat.PhoneFormat; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.LocaleController; import org.telegram.tgnet.TLRPC; import org.telegram.messenger.MessagesController; @@ -58,7 +59,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe private boolean blockedUsersActivity; private boolean isGroup; - private ArrayList uidArray; + private ArrayList uidArray; private boolean isAlwaysShare; private PrivacyActivityDelegate delegate; @@ -70,7 +71,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe public static final int TYPE_FILTER = 2; public interface PrivacyActivityDelegate { - void didUpdateUserList(ArrayList ids, boolean added); + void didUpdateUserList(ArrayList ids, boolean added); } public PrivacyUsersActivity() { @@ -79,7 +80,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe blockedUsersActivity = true; } - public PrivacyUsersActivity(int type, ArrayList users, boolean group, boolean always) { + public PrivacyUsersActivity(int type, ArrayList users, boolean group, boolean always) { super(); uidArray = users; isAlwaysShare = always; @@ -177,7 +178,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe } GroupCreateActivity fragment = new GroupCreateActivity(args); fragment.setDelegate(ids -> { - for (Integer id1 : ids) { + for (Long id1 : ids) { if (uidArray.contains(id1)) { continue; } @@ -193,15 +194,15 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe } else if (position >= usersStartRow && position < usersEndRow) { if (currentType == TYPE_BLOCKED) { Bundle args = new Bundle(); - args.putInt("user_id", getMessagesController().blockePeers.keyAt(position - usersStartRow)); + args.putLong("user_id", getMessagesController().blockePeers.keyAt(position - usersStartRow)); presentFragment(new ProfileActivity(args)); } else { Bundle args = new Bundle(); - int uid = uidArray.get(position - usersStartRow); - if (uid > 0) { - args.putInt("user_id", uid); + long uid = uidArray.get(position - usersStartRow); + if (DialogObject.isUserDialog(uid)) { + args.putLong("user_id", uid); } else { - args.putInt("chat_id", -uid); + args.putLong("chat_id", -uid); } presentFragment(new ProfileActivity(args)); } @@ -253,7 +254,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe delegate = privacyActivityDelegate; } - private void showUnblockAlert(Integer uid) { + private void showUnblockAlert(Long uid) { if (getParentActivity() == null) { return; } @@ -383,7 +384,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); ((ManageChatUserCell) view).setDelegate((cell, click) -> { if (click) { - showUnblockAlert((Integer) cell.getTag()); + showUnblockAlert((Long) cell.getTag()); } return true; }); @@ -411,7 +412,7 @@ public class PrivacyUsersActivity extends BaseFragment implements NotificationCe switch (holder.getItemViewType()) { case 0: ManageChatUserCell userCell = (ManageChatUserCell) holder.itemView; - int uid; + long uid; if (currentType == TYPE_BLOCKED) { uid = getMessagesController().blockePeers.keyAt(position - usersStartRow); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java index 8bc25af12..d6c1bb701 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProfileActivity.java @@ -14,6 +14,7 @@ import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; +import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; @@ -46,7 +47,6 @@ import android.text.TextPaint; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.util.Property; -import android.util.SparseArray; import android.util.SparseIntArray; import android.util.TypedValue; import android.view.Display; @@ -67,6 +67,7 @@ import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Keep; +import androidx.collection.LongSparseArray; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.core.graphics.ColorUtils; @@ -86,7 +87,9 @@ import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildConfig; import org.telegram.messenger.BuildVars; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.ChatThemeController; import org.telegram.messenger.ContactsController; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.ImageLoader; @@ -110,6 +113,7 @@ import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.ActionBar.ActionBar; +import org.telegram.ui.ActionBar.ActionBarLayout; import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenuItem; import org.telegram.ui.ActionBar.AlertDialog; @@ -239,9 +243,9 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private ActionBarMenuItem searchItem; protected float headerShadowAlpha = 1.0f; private TopView topView; - private int user_id; - private int chat_id; - private long dialog_id; + private long userId; + private long chatId; + private long dialogId; private boolean creatingChat; private boolean userBlocked; private boolean reportSpam; @@ -255,10 +259,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private boolean canSearchMembers; private boolean loadingUsers; - private SparseArray participantsMap = new SparseArray<>(); + private LongSparseArray participantsMap = new LongSparseArray<>(); private boolean usersEndReached; - private int banFromGroup; + private long banFromGroup; private boolean openAnimationInProgress; private boolean transitionAnimationInProress; private boolean recreateMenuAfterAnimation; @@ -301,7 +305,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private String currentBio; - private int selectedUser; + private long selectedUser; private int onlineCount = -1; private ArrayList sortedUsers; @@ -420,6 +424,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. PinchToZoomHelper pinchToZoomHelper; private View transitionOnlineText; + private int actionBarAnimationColorFrom = 0; + private int navigationBarAnimationColorFrom = 0; private final Property HEADER_SHADOW = new AnimationProperties.FloatProperty("headerShadow") { @Override @@ -443,13 +449,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } TLRPC.FileLocation photoBig = null; - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user != null && user.photo != null && user.photo.photo_big != null) { photoBig = user.photo.photo_big; } - } else if (chat_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat != null && chat.photo != null && chat.photo.photo_big != null) { photoBig = chat.photo.photo_big; } @@ -463,16 +469,16 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. object.viewY = coords[1] - (Build.VERSION.SDK_INT >= 21 ? 0 : AndroidUtilities.statusBarHeight); object.parentView = avatarImage; object.imageReceiver = avatarImage.getImageReceiver(); - if (user_id != 0) { - object.dialogId = user_id; - } else if (chat_id != 0) { - object.dialogId = -chat_id; + if (userId != 0) { + object.dialogId = userId; + } else if (chatId != 0) { + object.dialogId = -chatId; } object.thumb = object.imageReceiver.getBitmapSafe(); object.size = -1; object.radius = avatarImage.getImageReceiver().getRoundRadius(); object.scale = avatarContainer.getScaleX(); - object.canEdit = user_id == getUserConfig().clientUserId; + object.canEdit = userId == getUserConfig().clientUserId; return object; } return null; @@ -1028,7 +1034,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. RecyclerListView innerListView = sharedMediaLayout.getCurrentListView(); consumed[1] = dy; if (t > 0) { - consumed[1] -= Math.min(consumed[1], dy); + consumed[1] -= dy; } if (consumed[1] > 0) { innerListView.scrollBy(0, consumed[1]); @@ -1297,9 +1303,9 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public boolean onFragmentCreate() { - user_id = arguments.getInt("user_id", 0); - chat_id = arguments.getInt("chat_id", 0); - banFromGroup = arguments.getInt("ban_chat_id", 0); + userId = arguments.getLong("user_id", 0); + chatId = arguments.getLong("chat_id", 0); + banFromGroup = arguments.getLong("ban_chat_id", 0); reportSpam = arguments.getBoolean("reportSpam", false); if (!expandPhoto) { expandPhoto = arguments.getBoolean("expandPhoto", false); @@ -1307,12 +1313,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. needSendMessage = true; } } - if (user_id != 0) { - dialog_id = arguments.getLong("dialog_id", 0); - if (dialog_id != 0) { - currentEncryptedChat = getMessagesController().getEncryptedChat((int) (dialog_id >> 32)); + if (userId != 0) { + dialogId = arguments.getLong("dialog_id", 0); + if (dialogId != 0) { + currentEncryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); } - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return false; } @@ -1326,13 +1332,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. getNotificationCenter().addObserver(this, NotificationCenter.userInfoDidLoad); NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.reloadInterface); - userBlocked = getMessagesController().blockePeers.indexOfKey(user_id) >= 0; + userBlocked = getMessagesController().blockePeers.indexOfKey(userId) >= 0; if (user.bot) { isBot = true; getMediaDataController().loadBotInfo(user.id, user.id, true, classGuid); } - userInfo = getMessagesController().getUserFull(user_id); - getMessagesController().loadFullUser(getMessagesController().getUser(user_id), classGuid, true); + userInfo = getMessagesController().getUserFull(userId); + getMessagesController().loadFullUser(getMessagesController().getUser(userId), classGuid, true); participantsMap = null; if (UserObject.isUserSelf(user)) { @@ -1344,12 +1350,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. getMessagesController().loadSuggestedFilters(); getMessagesController().loadUserInfo(getUserConfig().getCurrentUser(), true, classGuid); } - } else if (chat_id != 0) { - currentChat = getMessagesController().getChat(chat_id); + actionBarAnimationColorFrom = arguments.getInt("actionBarColor", 0); + } else if (chatId != 0) { + currentChat = getMessagesController().getChat(chatId); if (currentChat == null) { final CountDownLatch countDownLatch = new CountDownLatch(1); getMessagesStorage().getStorageQueue().postRunnable(() -> { - currentChat = getMessagesStorage().getChat(chat_id); + currentChat = getMessagesStorage().getChat(chatId); countDownLatch.countDown(); }); try { @@ -1376,12 +1383,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. sortedUsers = new ArrayList<>(); updateOnlineCount(true); if (chatInfo == null) { - chatInfo = getMessagesController().getChatFull(chat_id); + chatInfo = getMessagesController().getChatFull(chatId); } if (ChatObject.isChannel(currentChat)) { - getMessagesController().loadFullChat(chat_id, classGuid, true); + getMessagesController().loadFullChat(chatId, classGuid, true); } else if (chatInfo == null) { - chatInfo = getMessagesStorage().loadChatInfo(chat_id, false, null, false, false); + chatInfo = getMessagesStorage().loadChatInfo(chatId, false, null, false, false); } } else { return false; @@ -1401,12 +1408,21 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } if (arguments.containsKey("preload_messages")) { - getMessagesController().ensureMessagesLoaded(user_id, 0, null); + getMessagesController().ensureMessagesLoaded(userId, 0, null); } return true; } + @Override + protected void setParentLayout(ActionBarLayout layout) { + super.setParentLayout(layout); + Activity activity = getParentActivity(); + if (activity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + navigationBarAnimationColorFrom = activity.getWindow().getNavigationBarColor(); + } + } + @Override public void onFragmentDestroy() { super.onFragmentDestroy(); @@ -1427,7 +1443,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (avatarsViewPager != null) { avatarsViewPager.onDestroy(); } - if (user_id != 0) { + if (userId != 0) { getNotificationCenter().removeObserver(this, NotificationCenter.newSuggestionsAvailable); getNotificationCenter().removeObserver(this, NotificationCenter.contactsDidLoad); getNotificationCenter().removeObserver(this, NotificationCenter.encryptedChatCreated); @@ -1436,8 +1452,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. getNotificationCenter().removeObserver(this, NotificationCenter.botInfoDidLoad); getNotificationCenter().removeObserver(this, NotificationCenter.userInfoDidLoad); NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.reloadInterface); - getMessagesController().cancelLoadFullUser(user_id); - } else if (chat_id != 0) { + getMessagesController().cancelLoadFullUser(userId); + } else if (chatId != 0) { getNotificationCenter().removeObserver(this, NotificationCenter.chatInfoDidLoad); getNotificationCenter().removeObserver(this, NotificationCenter.chatOnlineCountDidLoad); getNotificationCenter().removeObserver(this, NotificationCenter.groupCallUpdated); @@ -1467,7 +1483,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } }; actionBar.setBackgroundColor(Color.TRANSPARENT); - actionBar.setItemsBackgroundColor(AvatarDrawable.getButtonColorForId(user_id != 0 || ChatObject.isChannel(chat_id, currentAccount) && !currentChat.megagroup ? 5 : chat_id), false); + actionBar.setItemsBackgroundColor(AvatarDrawable.getButtonColorForId(userId != 0 || ChatObject.isChannel(chatId, currentAccount) && !currentChat.megagroup ? 5 : chatId), false); actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultIcon), false); actionBar.setBackButtonDrawable(new BackDrawable(false)); actionBar.setCastShadows(false); @@ -1496,34 +1512,34 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (id == -1) { finishFragment(); } else if (id == block_contact) { - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } if (!isBot || MessagesController.isSupportUser(user)) { if (userBlocked) { - getMessagesController().unblockPeer(user_id); + getMessagesController().unblockPeer(userId); if (BulletinFactory.canShowBulletin(ProfileActivity.this)) { BulletinFactory.createBanBulletin(ProfileActivity.this, false).show(); } } else { if (reportSpam) { - AlertsCreator.showBlockReportSpamAlert(ProfileActivity.this, user_id, user, null, currentEncryptedChat, false, null, param -> { + AlertsCreator.showBlockReportSpamAlert(ProfileActivity.this, userId, user, null, currentEncryptedChat, false, null, param -> { if (param == 1) { getNotificationCenter().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); playProfileAnimation = 0; finishFragment(); } else { - getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, (long) user_id); + getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, userId); } - }); + }, null); } else { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("BlockUser", R.string.BlockUser)); builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("AreYouSureBlockContact2", R.string.AreYouSureBlockContact2, ContactsController.formatName(user.first_name, user.last_name)))); builder.setPositiveButton(LocaleController.getString("BlockContact", R.string.BlockContact), (dialogInterface, i) -> { - getMessagesController().blockPeer(user_id); + getMessagesController().blockPeer(userId); if (BulletinFactory.canShowBulletin(ProfileActivity.this)) { BulletinFactory.createBanBulletin(ProfileActivity.this, true).show(); } @@ -1539,17 +1555,17 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } else { if (!userBlocked) { - getMessagesController().blockPeer(user_id); + getMessagesController().blockPeer(userId); } else { - getMessagesController().unblockPeer(user_id); - getSendMessagesHelper().sendMessage("/start", user_id, null, null, null, false, null, null, null, true, 0, null); + getMessagesController().unblockPeer(userId); + getSendMessagesHelper().sendMessage("/start", userId, null, null, null, false, null, null, null, true, 0, null); finishFragment(); } } } else if (id == add_contact) { - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); Bundle args = new Bundle(); - args.putInt("user_id", user.id); + args.putLong("user_id", user.id); args.putBoolean("addContact", true); presentFragment(new ContactAddActivity(args)); } else if (id == share_contact) { @@ -1563,10 +1579,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. presentFragment(fragment); } else if (id == edit_contact) { Bundle args = new Bundle(); - args.putInt("user_id", user_id); + args.putLong("user_id", userId); presentFragment(new ContactAddActivity(args)); } else if (id == delete_contact) { - final TLRPC.User user = getMessagesController().getUser(user_id); + final TLRPC.User user = getMessagesController().getUser(userId); if (user == null || getParentActivity() == null) { return; } @@ -1589,12 +1605,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. leaveChatPressed(); } else if (id == edit_channel) { Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); + args.putLong("chat_id", chatId); ChatEditActivity fragment = new ChatEditActivity(args); fragment.setInfo(chatInfo); presentFragment(fragment); } else if (id == invite_to_group) { - final TLRPC.User user = getMessagesController().getUser(user_id); + final TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } @@ -1607,14 +1623,14 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. long did = dids.get(0); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - args1.putInt("chat_id", -(int) did); + args1.putLong("chat_id", -did); if (!getMessagesController().checkCanOpenChat(args1, fragment1)) { return; } getNotificationCenter().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); - getMessagesController().addUserToChat(-(int) did, user, 0, null, ProfileActivity.this, null); + getMessagesController().addUserToChat(-did, user, 0, null, ProfileActivity.this, null); presentFragment(new ChatActivity(args1), true); removeSelfFromStack(); }); @@ -1622,8 +1638,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } else if (id == share) { try { String text = null; - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } @@ -1632,8 +1648,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } else { text = String.format("https://" + getMessagesController().linkPrefix + "/%s", user.username); } - } else if (chat_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat == null) { return; } @@ -1657,11 +1673,11 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. try { long did; if (currentEncryptedChat != null) { - did = ((long) currentEncryptedChat.id) << 32; - } else if (user_id != 0) { - did = user_id; - } else if (chat_id != 0) { - did = -chat_id; + did = DialogObject.makeEncryptedDialogId(currentEncryptedChat.id); + } else if (userId != 0) { + did = userId; + } else if (chatId != 0) { + did = -chatId; } else { return; } @@ -1670,13 +1686,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. FileLog.e(e); } } else if (id == call_item || id == video_call_item) { - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user != null) { VoIPHelper.startCall(user, id == video_call_item, userInfo != null && userInfo.video_calls_available, getParentActivity(), userInfo, getAccountInstance()); } - } else if (chat_id != 0) { - ChatObject.Call call = getMessagesController().getGroupCall(chat_id, false); + } else if (chatId != 0) { + ChatObject.Call call = getMessagesController().getGroupCall(chatId, false); if (call == null) { VoIPHelper.showGroupCallAlert(ProfileActivity.this, currentChat, null, false, getAccountInstance()); } else { @@ -1685,7 +1701,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } else if (id == search_members) { Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_USERS); args.putBoolean("open_search", true); ChatUsersActivity fragment = new ChatUsersActivity(args); @@ -1694,9 +1710,9 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } else if (id == add_member) { openAddMember(); } else if (id == statistics) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + TLRPC.Chat chat = getMessagesController().getChat(chatId); Bundle args = new Bundle(); - args.putInt("chat_id",chat_id); + args.putLong("chat_id", chatId); args.putBoolean("is_megagroup", chat.megagroup); StatisticActivity fragment = new StatisticActivity(args); presentFragment(fragment); @@ -1708,7 +1724,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. builder.setMessage(LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat)); builder.setPositiveButton(LocaleController.getString("Start", R.string.Start), (dialogInterface, i) -> { creatingChat = true; - getSecretChatHelper().startSecretChat(getParentActivity(), getMessagesController().getUser(user_id)); + getSecretChatHelper().startSecretChat(getParentActivity(), getMessagesController().getUser(userId)); }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); @@ -1731,7 +1747,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (getParentActivity() == null) { return; } - BulletinFactory.createSaveToGalleryBulletin(ProfileActivity.this, isVideo).show(); + BulletinFactory.createSaveToGalleryBulletin(ProfileActivity.this, isVideo, null).show(); }); } } else if (id == edit_name) { @@ -1768,7 +1784,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } })); - undoView.showWithAction(user_id, UndoView.ACTION_PROFILE_PHOTO_CHANGED, photo.video_sizes.isEmpty() ? null : 1); + undoView.showWithAction(userId, UndoView.ACTION_PROFILE_PHOTO_CHANGED, photo.video_sizes.isEmpty() ? null : 1); TLRPC.User user = getMessagesController().getUser(userConfig.clientUserId); TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 800); @@ -1830,7 +1846,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. inputPhoto.file_reference = new byte[0]; } getMessagesController().deleteUserPhoto(inputPhoto); - getMessagesStorage().clearUserPhoto(user_id, photo.id); + getMessagesStorage().clearUserPhoto(userId, photo.id); } if (avatarsViewPager.removePhotoAtIndex(position)) { avatarsViewPager.setVisibility(View.GONE); @@ -1860,12 +1876,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. sharedMediaLayout.onDestroy(); } final long did; - if (dialog_id != 0) { - did = dialog_id; - } else if (user_id != 0) { - did = user_id; + if (dialogId != 0) { + did = dialogId; + } else if (userId != 0) { + did = userId; } else { - did = -chat_id; + did = -chatId; } ArrayList users = chatInfo != null && chatInfo.participants != null && chatInfo.participants.participants.size() > 5 ? sortedUsers : null; sharedMediaLayout = new SharedMediaLayout(context, did, sharedMediaPreloader, userInfo != null ? userInfo.common_chats_count : 0, sortedUsers, chatInfo, users != null, this) { @@ -1934,7 +1950,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. videoCallItem = menu.addItem(video_call_item, R.drawable.profile_video); videoCallItem.setContentDescription(LocaleController.getString("VideoCall", R.string.VideoCall)); - if (chat_id != 0) { + if (chatId != 0) { callItem = menu.addItem(call_item, R.drawable.msg_voicechat2); if (ChatObject.isChannelOrGiga(currentChat)) { callItem.setContentDescription(LocaleController.getString("VoipChannelVoiceChat", R.string.VoipChannelVoiceChat)); @@ -2481,10 +2497,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } if (position == settingsKeyRow) { Bundle args = new Bundle(); - args.putInt("chat_id", (int) (dialog_id >> 32)); + args.putLong("chat_id", DialogObject.getEncryptedChatId(dialogId)); presentFragment(new IdenticonActivity(args)); } else if (position == settingsTimerRow) { - showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat).create()); + showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat, null).create()); } else if (position == notificationsRow) { if (LocaleController.isRTL && x <= AndroidUtilities.dp(76) || !LocaleController.isRTL && x >= view.getMeasuredWidth() - AndroidUtilities.dp(76)) { NotificationsCheckCell checkCell = (NotificationsCheckCell) view; @@ -2539,7 +2555,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } AlertsCreator.showCustomNotificationsDialog(ProfileActivity.this, did, -1, null, currentAccount, param -> listAdapter.notifyItemChanged(notificationsRow)); } else if (position == unblockRow) { - getMessagesController().unblockPeer(user_id); + getMessagesController().unblockPeer(userId); if (BulletinFactory.canShowBulletin(ProfileActivity.this)) { BulletinFactory.createBanBulletin(ProfileActivity.this, false).show(); } @@ -2575,7 +2591,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } else if (position == locationRow) { if (chatInfo.location instanceof TLRPC.TL_channelLocation) { LocationActivity fragment = new LocationActivity(LocationActivity.LOCATION_TYPE_GROUP_VIEW); - fragment.setChatLocation(chat_id, (TLRPC.TL_channelLocation) chatInfo.location); + fragment.setChatLocation(chatId, (TLRPC.TL_channelLocation) chatInfo.location); presentFragment(fragment); } } else if (position == joinRow) { @@ -2583,21 +2599,21 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.closeSearchByActiveAction); } else if (position == subscribersRow) { Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_USERS); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(chatInfo); presentFragment(fragment); } else if (position == administratorsRow) { Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_ADMIN); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(chatInfo); presentFragment(fragment); } else if (position == blockedUsersRow) { Bundle args = new Bundle(); - args.putInt("chat_id", chat_id); + args.putLong("chat_id", chatId); args.putInt("type", ChatUsersActivity.TYPE_BANNED); ChatUsersActivity fragment = new ChatUsersActivity(args); fragment.setInfo(chatInfo); @@ -2718,6 +2734,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. SharedConfig.lockRecordAudioVideoHint = 0; SharedConfig.stickersReorderingHintUsed = false; SharedConfig.forwardingOptionsHintShown = false; + SharedConfig.messageSeenHintCount = 3; + SharedConfig.emojiInteractionsHintCount = 3; + SharedConfig.dayNightThemeSwitchHintCount = 3; + ChatThemeController.getInstance(currentAccount).clearCache(); } else if (which == 7) { VoIPHelper.showCallDebugSettings(getParentActivity()); } else if (which == 8) { @@ -2737,7 +2757,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. SharedConfig.toggleDisableVoiceAudioEffects(); } else if (which == 14) { SharedConfig.toggleNoStatusBar(); - if (getParentActivity() != null) { + if (getParentActivity() != null && Build.VERSION.SDK_INT >= 21) { if (SharedConfig.noStatusBar) { getParentActivity().getWindow().setStatusBarColor(0); } else { @@ -2866,7 +2886,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (currentChannelParticipant == null) { TLRPC.TL_channels_getParticipant req = new TLRPC.TL_channels_getParticipant(); req.channel = MessagesController.getInputChannel(chat); - req.participant = getMessagesController().getInputPeer(user_id); + req.participant = getMessagesController().getInputPeer(userId); getConnectionsManager().sendRequest(req, (response, error) -> { if (response != null) { AndroidUtilities.runOnUIThread(() -> currentChannelParticipant = ((TLRPC.TL_channels_channelParticipant) response).participant); @@ -2886,7 +2906,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. frameLayout.addView(frameLayout1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.LEFT | Gravity.BOTTOM)); frameLayout1.setOnClickListener(v -> { - ChatRightsEditActivity fragment = new ChatRightsEditActivity(user_id, banFromGroup, null, chat.default_banned_rights, currentChannelParticipant != null ? currentChannelParticipant.banned_rights : null, "", ChatRightsEditActivity.TYPE_BANNED, true, false); + ChatRightsEditActivity fragment = new ChatRightsEditActivity(userId, banFromGroup, null, chat.default_banned_rights, currentChannelParticipant != null ? currentChannelParticipant.banned_rights : null, "", ChatRightsEditActivity.TYPE_BANNED, true, false); fragment.setDelegate(new ChatRightsEditActivity.ChatRightsEditActivityDelegate() { @Override public void didSetRights(int rights, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, String rank) { @@ -2895,7 +2915,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public void didChangeOwner(TLRPC.User user) { - undoView.showWithAction(-chat_id, currentChat.megagroup ? UndoView.ACTION_OWNER_TRANSFERED_GROUP : UndoView.ACTION_OWNER_TRANSFERED_CHANNEL, user); + undoView.showWithAction(-chatId, currentChat.megagroup ? UndoView.ACTION_OWNER_TRANSFERED_GROUP : UndoView.ACTION_OWNER_TRANSFERED_CHANNEL, user); } }); presentFragment(fragment); @@ -2936,7 +2956,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } }; AndroidUtilities.updateViewVisibilityAnimated(avatarContainer2, true, 1f, false); - frameLayout.addView(avatarContainer2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); + frameLayout.addView(avatarContainer2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.START, 0, 0, 0, 0)); avatarContainer.setPivotX(0); avatarContainer.setPivotY(0); avatarContainer2.addView(avatarContainer, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0)); @@ -3029,7 +3049,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. avatarsViewPager.onDestroy(); } overlaysView = new OverlaysView(context); - avatarsViewPager = new ProfileGalleryView(context, user_id != 0 ? user_id : -chat_id, actionBar, listView, avatarImage, getClassGuid(), overlaysView); + avatarsViewPager = new ProfileGalleryView(context, userId != 0 ? userId : -chatId, actionBar, listView, avatarImage, getClassGuid(), overlaysView); avatarsViewPager.setChatInfo(chatInfo); avatarContainer2.addView(avatarsViewPager); avatarContainer2.addView(overlaysView); @@ -3061,7 +3081,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. nameTextView[a].setScrollNonFitText(true); nameTextView[a].setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); } - avatarContainer2.addView(nameTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 0, 0)); + int rightMargin = a == 0 + ? (48 + ((callItemVisible && userId != 0) ? 48 : 0)) + : 0; + avatarContainer2.addView(nameTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, rightMargin, 0)); } for (int a = 0; a < onlineTextView.length; a++) { onlineTextView[a] = new SimpleTextView(context); @@ -3099,7 +3122,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. 0, 0); combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56)); writeButton.setBackgroundDrawable(combinedDrawable); - if (user_id != 0) { + if (userId != 0) { if (imageUpdater != null) { cameraDrawable = new RLottieDrawable(R.raw.camera_outline, "" + R.raw.camera_outline, AndroidUtilities.dp(56), AndroidUtilities.dp(56), false, null); @@ -3340,12 +3363,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } public long getDialogId() { - if (dialog_id != 0) { - return dialog_id; - } else if (user_id != 0) { - return user_id; + if (dialogId != 0) { + return dialogId; + } else if (userId != 0) { + return userId; } else { - return -chat_id; + return -chatId; } } @@ -3357,8 +3380,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (listView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) { return; } - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); if (user.photo.dc_id != 0) { @@ -3366,8 +3389,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } PhotoViewer.getInstance().openPhoto(user.photo.photo_big, provider); } - } else if (chat_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat.photo != null && chat.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); if (chat.photo.dc_id != 0) { @@ -3385,7 +3408,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } private void onWriteButtonClick() { - if (user_id != 0) { + if (userId != 0) { if (imageUpdater != null) { TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(UserConfig.getInstance(currentAccount).getClientUserId()); if (user == null) { @@ -3412,12 +3435,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (playProfileAnimation != 0 && parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2) instanceof ChatActivity) { finishFragment(); } else { - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); if (user == null || user instanceof TLRPC.TL_userEmpty) { return; } Bundle args = new Bundle(); - args.putInt("user_id", user_id); + args.putLong("user_id", userId); if (!getMessagesController().checkCanOpenChat(args, ProfileActivity.this)) { return; } @@ -3447,7 +3470,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. return; } Bundle args = new Bundle(); - args.putInt("chat_id", chatInfo.linked_chat_id); + args.putLong("chat_id", chatInfo.linked_chat_id); if (!getMessagesController().checkCanOpenChat(args, ProfileActivity.this)) { return; } @@ -3569,7 +3592,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. return false; } Bundle args = new Bundle(); - args.putInt("user_id", participant.user_id); + args.putLong("user_id", participant.user_id); args.putBoolean("preload_messages", true); presentFragment(new ProfileActivity(args)); } @@ -3578,7 +3601,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private void openRightsEdit(int action, TLRPC.User user, TLRPC.ChatParticipant participant, TLRPC.TL_chatAdminRights adminRights, TLRPC.TL_chatBannedRights bannedRights, String rank, boolean editingAdmin) { boolean[] needShowBulletin = new boolean[1]; - ChatRightsEditActivity fragment = new ChatRightsEditActivity(user.id, chat_id, adminRights, currentChat.default_banned_rights, bannedRights, rank, action, true, false) { + ChatRightsEditActivity fragment = new ChatRightsEditActivity(user.id, chatId, adminRights, currentChat.default_banned_rights, bannedRights, rank, action, true, false) { @Override protected void onTransitionAnimationEnd(boolean isOpen, boolean backward) { if (!isOpen && backward && needShowBulletin[0] && BulletinFactory.canShowBulletin(ProfileActivity.this)) { @@ -3658,7 +3681,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public void didChangeOwner(TLRPC.User user) { - undoView.showWithAction(-chat_id, currentChat.megagroup ? UndoView.ACTION_OWNER_TRANSFERED_GROUP : UndoView.ACTION_OWNER_TRANSFERED_CHANNEL, user); + undoView.showWithAction(-chatId, currentChat.megagroup ? UndoView.ACTION_OWNER_TRANSFERED_GROUP : UndoView.ACTION_OWNER_TRANSFERED_CHANNEL, user); } }); presentFragment(fragment); @@ -3667,14 +3690,14 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private boolean processOnClickOrPress(final int position) { if (position == usernameRow || position == setUsernameRow) { final String username; - if (user_id != 0) { - final TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + final TLRPC.User user = getMessagesController().getUser(userId); if (user == null || user.username == null) { return false; } username = user.username; - } else if (chat_id != 0) { - final TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + final TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat == null || chat.username == null) { return false; } @@ -3688,7 +3711,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. try { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE); String text; - if (user_id != 0) { + if (userId != 0) { text = "@" + username; BulletinFactory.of(this).createCopyBulletin(LocaleController.getString("UsernameCopied", R.string.UsernameCopied)).show(); } else { @@ -3706,7 +3729,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. showDialog(builder.create()); return true; } else if (position == phoneRow || position == numberRow) { - final TLRPC.User user = getMessagesController().getUser(user_id); + final TLRPC.User user = getMessagesController().getUser(userId); if (user == null || user.phone == null || user.phone.length() == 0 || getParentActivity() == null) { return false; } @@ -3793,7 +3816,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. getNotificationCenter().removeObserver(ProfileActivity.this, NotificationCenter.closeChats); getNotificationCenter().postNotificationName(NotificationCenter.closeChats); finishFragment(); - getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, (long) -currentChat.id, null, currentChat, param); + getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, -currentChat.id, null, currentChat, param); }); } @@ -3805,7 +3828,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. final int delay = participantsMap.size() != 0 && reload ? 300 : 0; final TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants(); - req.channel = getMessagesController().getInputChannel(chat_id); + req.channel = getMessagesController().getInputChannel(chatId); req.filter = new TLRPC.TL_channelParticipantsRecent(); req.offset = reload ? 0 : participantsMap.size(); req.limit = 200; @@ -3821,7 +3844,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. participantsMap.clear(); chatInfo.participants = new TLRPC.TL_chatParticipants(); getMessagesStorage().putUsersAndChats(res.users, res.chats, true, true); - getMessagesStorage().updateChannelUsers(chat_id, res.participants); + getMessagesStorage().updateChannelUsers(chatId, res.participants); } for (int a = 0; a < res.participants.size(); a++) { TLRPC.TL_chatChannelParticipant participant = new TLRPC.TL_chatChannelParticipant(); @@ -4000,18 +4023,18 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. private void openAddMember() { Bundle args = new Bundle(); args.putBoolean("addToGroup", true); - args.putInt("chatId", currentChat.id); + args.putLong("chatId", currentChat.id); GroupCreateActivity fragment = new GroupCreateActivity(args); fragment.setInfo(chatInfo); if (chatInfo != null && chatInfo.participants != null) { - SparseArray users = new SparseArray<>(); + LongSparseArray users = new LongSparseArray<>(); for (int a = 0; a < chatInfo.participants.participants.size(); a++) { users.put(chatInfo.participants.participants.get(a).user_id, null); } fragment.setIgnoreUsers(users); } fragment.setDelegate((users, fwdCount) -> { - HashSet currentParticipants = new HashSet<>(); + HashSet currentParticipants = new HashSet<>(); if (chatInfo.participants.participants != null) { for (int i = 0; i < chatInfo.participants.participants.size(); i++) { currentParticipants.add(chatInfo.participants.participants.get(i).user_id); @@ -4019,7 +4042,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } for (int a = 0, N = users.size(); a < N; a++) { TLRPC.User user = users.get(a); - getMessagesController().addUserToChat(chat_id, user, fwdCount, null, ProfileActivity.this, null); + getMessagesController().addUserToChat(chatId, user, fwdCount, null, ProfileActivity.this, null); if (!currentParticipants.contains(user.id)) { if (chatInfo.participants == null) { chatInfo.participants = new TLRPC.TL_chatParticipants(); @@ -4143,7 +4166,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (!openAnimationInProgress) { boolean setVisible = diff > 0.2f && !searchMode && (imageUpdater == null || setAvatarRow == -1); - if (setVisible && chat_id != 0) { + if (setVisible && chatId != 0) { setVisible = ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatInfo != null && chatInfo.linked_chat_id != 0 && infoHeaderRow != -1; } boolean currentVisible = writeButton.getTag() == null; @@ -4550,7 +4573,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (id == NotificationCenter.updateInterfaces) { int mask = (Integer) args[0]; boolean infoChanged = (mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0; - if (user_id != 0) { + if (userId != 0) { if (infoChanged) { updateProfileData(); } @@ -4562,7 +4585,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } } - } else if (chat_id != 0) { + } else if (chatId != 0) { if ((mask & MessagesController.UPDATE_MASK_CHAT) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) { if ((mask & MessagesController.UPDATE_MASK_CHAT) != 0) { updateListAnimated(true); @@ -4584,7 +4607,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } } else if (id == NotificationCenter.chatOnlineCountDidLoad) { - Integer chatId = (Integer) args[0]; + Long chatId = (Long) args[0]; if (chatInfo == null || currentChat == null || currentChat.id != chatId) { return; } @@ -4613,13 +4636,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } else if (id == NotificationCenter.blockedUsersDidLoad) { boolean oldValue = userBlocked; - userBlocked = getMessagesController().blockePeers.indexOfKey(user_id) >= 0; + userBlocked = getMessagesController().blockePeers.indexOfKey(userId) >= 0; if (oldValue != userBlocked) { createActionBarMenu(true); updateListAnimated(false); } } else if (id == NotificationCenter.groupCallUpdated) { - Integer chatId = (Integer) args[0]; + Long chatId = (Long) args[0]; if (currentChat != null && chatId == currentChat.id && ChatObject.canManageCalls(currentChat)) { TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chatId); if (chatFull != null) { @@ -4634,7 +4657,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } else if (id == NotificationCenter.chatInfoDidLoad) { TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0]; - if (chatFull.id == chat_id) { + if (chatFull.id == chatId) { boolean byChannelUsers = (Boolean) args[2]; if (chatInfo instanceof TLRPC.TL_channelFull) { if (chatFull.participants == null) { @@ -4652,7 +4675,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. avatarsViewPager.setChatInfo(chatInfo); } updateListAnimated(true); - TLRPC.Chat newChat = getMessagesController().getChat(chat_id); + TLRPC.Chat newChat = getMessagesController().getChat(chatId); if (newChat != null) { currentChat = newChat; createActionBarMenu(true); @@ -4666,13 +4689,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. removeSelfFromStack(); } else if (id == NotificationCenter.botInfoDidLoad) { TLRPC.BotInfo info = (TLRPC.BotInfo) args[0]; - if (info.user_id == user_id) { + if (info.user_id == userId) { botInfo = info; updateListAnimated(false); } } else if (id == NotificationCenter.userInfoDidLoad) { - int uid = (Integer) args[0]; - if (uid == user_id) { + long uid = (Long) args[0]; + if (uid == userId) { userInfo = (TLRPC.UserFull) args[1]; if (imageUpdater != null) { if (!TextUtils.equals(userInfo.about, currentBio)) { @@ -4701,7 +4724,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } long did = getDialogId(); if (did == (Long) args[0]) { - boolean enc = ((int) did) == 0; + boolean enc = DialogObject.isEncryptedDialog(did); ArrayList arr = (ArrayList) args[1]; for (int a = 0; a < arr.size(); a++) { MessageObject obj = arr.get(a); @@ -4933,10 +4956,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (playProfileAnimation == 2 && avatarColor != 0) { color = avatarColor; } else { - color = AvatarDrawable.getProfileBackColorForId(user_id != 0 || ChatObject.isChannel(chat_id, currentAccount) && !currentChat.megagroup ? 5 : chat_id); + color = AvatarDrawable.getProfileBackColorForId(userId != 0 || ChatObject.isChannel(chatId, currentAccount) && !currentChat.megagroup ? 5 : chatId); } - int actionBarColor = Theme.getColor(Theme.key_actionBarDefault); + int actionBarColor = actionBarAnimationColorFrom != 0 ? actionBarAnimationColorFrom : Theme.getColor(Theme.key_actionBarDefault); int r = Color.red(actionBarColor); int g = Color.green(actionBarColor); int b = Color.blue(actionBarColor); @@ -4948,7 +4971,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. int aD; topView.setBackgroundColor(Color.rgb(r + rD, g + gD, b + bD)); - color = AvatarDrawable.getIconColorForId(user_id != 0 || ChatObject.isChannel(chat_id, currentAccount) && !currentChat.megagroup ? 5 : chat_id); + color = AvatarDrawable.getIconColorForId(userId != 0 || ChatObject.isChannel(chatId, currentAccount) && !currentChat.megagroup ? 5 : chatId); int iconColor = Theme.getColor(Theme.key_actionBarDefaultIcon); r = Color.red(iconColor); g = Color.green(iconColor); @@ -4977,7 +5000,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. nameTextView[i].setTextColor(Color.argb(a + aD, r + rD, g + gD, b + bD)); } - color = isOnline[0] ? Theme.getColor(Theme.key_profile_status) : AvatarDrawable.getProfileTextColorForId(user_id != 0 || ChatObject.isChannel(chat_id, currentAccount) && !currentChat.megagroup ? 5 : chat_id); + color = isOnline[0] ? Theme.getColor(Theme.key_profile_status) : AvatarDrawable.getProfileTextColorForId(userId != 0 || ChatObject.isChannel(chatId, currentAccount) && !currentChat.megagroup ? 5 : chatId); int subtitleColor = Theme.getColor(isOnline[0] ? Theme.key_chat_status : Theme.key_actionBarDefaultSubtitle); r = Color.red(subtitleColor); g = Color.green(subtitleColor); @@ -4995,8 +5018,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. onlineTextView[i].setTextColor(Color.argb(a + aD, r + rD, g + gD, b + bD)); } extraHeight = initialAnimationExtraHeight * progress; - color = AvatarDrawable.getProfileColorForId(user_id != 0 ? user_id : chat_id); - int color2 = AvatarDrawable.getColorForId(user_id != 0 ? user_id : chat_id); + color = AvatarDrawable.getProfileColorForId(userId != 0 ? userId : chatId); + int color2 = AvatarDrawable.getColorForId(userId != 0 ? userId : chatId); if (color != color2) { rD = (int) ((Color.red(color) - Color.red(color2)) * progress); gD = (int) ((Color.green(color) - Color.green(color2)) * progress); @@ -5005,6 +5028,11 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. avatarImage.invalidate(); } + if (navigationBarAnimationColorFrom != 0) { + color = ColorUtils.blendARGB(navigationBarAnimationColorFrom, getNavigationBarColor(), progress); + setNavigationBarColor(color); + } + topView.invalidate(); needLayout(true); @@ -5082,7 +5110,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. animatingItem.setAlpha(1.0f); animators.add(ObjectAnimator.ofFloat(animatingItem, View.ALPHA, 0.0f)); } - if (callItemVisible) { + if (callItemVisible && chatId != 0) { callItem.setAlpha(0.0f); animators.add(ObjectAnimator.ofFloat(callItem, View.ALPHA, 1.0f)); } @@ -5136,7 +5164,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. animatingItem.setAlpha(0.0f); animators.add(ObjectAnimator.ofFloat(animatingItem, View.ALPHA, 1.0f)); } - if (callItemVisible) { + if (callItemVisible && chatId != 0) { callItem.setAlpha(1.0f); animators.add(ObjectAnimator.ofFloat(callItem, View.ALPHA, 0.0f)); } @@ -5313,10 +5341,10 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } - private void kickUser(int uid, TLRPC.ChatParticipant participant) { + private void kickUser(long uid, TLRPC.ChatParticipant participant) { if (uid != 0) { TLRPC.User user = getMessagesController().getUser(uid); - getMessagesController().deleteParticipantFromChat(chat_id, user, chatInfo); + getMessagesController().deleteParticipantFromChat(chatId, user, chatInfo); if (currentChat != null && user != null && BulletinFactory.canShowBulletin(this)) { BulletinFactory.createRemoveFromChatBulletin(this, user, currentChat.title).show(); } @@ -5326,18 +5354,18 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } else { getNotificationCenter().removeObserver(this, NotificationCenter.closeChats); if (AndroidUtilities.isTablet()) { - getNotificationCenter().postNotificationName(NotificationCenter.closeChats, -(long) chat_id); + getNotificationCenter().postNotificationName(NotificationCenter.closeChats, -chatId); } else { getNotificationCenter().postNotificationName(NotificationCenter.closeChats); } - getMessagesController().deleteParticipantFromChat(chat_id, getMessagesController().getUser(getUserConfig().getClientUserId()), chatInfo); + getMessagesController().deleteParticipantFromChat(chatId, getMessagesController().getUser(getUserConfig().getClientUserId()), chatInfo); playProfileAnimation = 0; finishFragment(); } } public boolean isChat() { - return chat_id != 0; + return chatId != 0; } private void updateRowsIds() { @@ -5420,11 +5448,11 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } - if (user_id != 0) { + if (userId != 0) { if (LocaleController.isRTL) { emptyRow = rowCount++; } - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); if (UserObject.isUserSelf(user)) { if (avatarBig == null && (user.photo == null || !(user.photo.photo_big instanceof TLRPC.TL_fileLocation_layer97) && !(user.photo.photo_big instanceof TLRPC.TL_fileLocationToBeDeprecated)) && (avatarsViewPager == null || avatarsViewPager.getRealCount() == 0)) { @@ -5493,7 +5521,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (phoneRow != -1 || userInfoRow != -1 || usernameRow != -1) { notificationsDividerRow = rowCount++; } - if (user_id != getUserConfig().getClientUserId()) { + if (userId != getUserConfig().getClientUserId()) { notificationsRow = rowCount++; } infoSectionRow = rowCount++; @@ -5519,7 +5547,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. lastSectionRow = rowCount++; } } - } else if (chat_id != 0) { + } else if (chatId != 0) { if (chatInfo != null && (!TextUtils.isEmpty(chatInfo.about) || chatInfo.location instanceof TLRPC.TL_channelLocation) || !TextUtils.isEmpty(currentChat.username)) { if (LocaleController.isRTL && ChatObject.isChannel(currentChat) && chatInfo != null && !currentChat.megagroup && chatInfo.linked_chat_id != 0) { emptyRow = rowCount++; @@ -5681,8 +5709,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. onlineTextOverride = null; } - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } @@ -5757,7 +5785,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (user.scam || user.fake) { rightIcon = getScamDrawable(user.scam ? 0 : 1); } else { - rightIcon = getMessagesController().isDialogMuted(dialog_id != 0 ? dialog_id : (long) user_id) ? Theme.chat_muteIconDrawable : null; + rightIcon = getMessagesController().isDialogMuted(dialogId != 0 ? dialogId : userId) ? Theme.chat_muteIconDrawable : null; } } else if (user.scam || user.fake) { rightIcon = getScamDrawable(user.scam ? 0 : 1); @@ -5769,8 +5797,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } avatarImage.getImageReceiver().setVisible(!PhotoViewer.isShowingImage(photoBig), false); - } else if (chat_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + TLRPC.Chat chat = getMessagesController().getChat(chatId); if (chat != null) { currentChat = chat; } else { @@ -5862,7 +5890,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (chat.scam || chat.fake) { nameTextView[a].setRightDrawable(getScamDrawable(chat.scam ? 0 : 1)); } else { - nameTextView[a].setRightDrawable(getMessagesController().isDialogMuted(-chat_id) ? Theme.chat_muteIconDrawable : null); + nameTextView[a].setRightDrawable(getMessagesController().isDialogMuted(-chatId) ? Theme.chat_muteIconDrawable : null); } } if (a == 0 && onlineTextOverride != null) { @@ -5942,8 +5970,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. videoCallItemVisible = false; canSearchMembers = false; boolean selfUser = false; - if (user_id != 0) { - TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } @@ -5955,7 +5983,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. callItemVisible = true; videoCallItemVisible = Build.VERSION.SDK_INT >= 18 && userInfo.video_calls_available; } - if (isBot || getContactsController().contactsDict.get(user_id) == null) { + if (isBot || getContactsController().contactsDict.get(userId) == null) { if (MessagesController.isSupportUser(user)) { if (userBlocked) { otherItem.addSubItem(block_contact, R.drawable.msg_block, LocaleController.getString("Unblock", R.string.Unblock)); @@ -5986,13 +6014,13 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. otherItem.addSubItem(edit_contact, R.drawable.msg_edit, LocaleController.getString("EditContact", R.string.EditContact)); otherItem.addSubItem(delete_contact, R.drawable.msg_delete, LocaleController.getString("DeleteContact", R.string.DeleteContact)); } - if (!UserObject.isDeleted(user) && !isBot && currentEncryptedChat == null && !userBlocked && user_id != 333000 && user_id != 777000 && user_id != 42777) { + if (!UserObject.isDeleted(user) && !isBot && currentEncryptedChat == null && !userBlocked && userId != 333000 && userId != 777000 && userId != 42777) { otherItem.addSubItem(start_secret_chat, R.drawable.msg_start_secret, LocaleController.getString("StartEncryptedChat", R.string.StartEncryptedChat)); } otherItem.addSubItem(add_shortcut, R.drawable.msg_home, LocaleController.getString("AddShortcut", R.string.AddShortcut)); } - } else if (chat_id != 0) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + } else if (chatId != 0) { + TLRPC.Chat chat = getMessagesController().getChat(chatId); hasVoiceChatItem = false; if (ChatObject.isChannel(chat)) { if (ChatObject.hasAdminRights(chat) || chat.megagroup && ChatObject.canChangeChatInfo(chat)) { @@ -6006,7 +6034,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (chatInfo.can_view_stats) { otherItem.addSubItem(statistics, R.drawable.msg_stats, LocaleController.getString("Statistics", R.string.Statistics)); } - ChatObject.Call call = getMessagesController().getGroupCall(chat_id, false); + ChatObject.Call call = getMessagesController().getGroupCall(chatId, false); callItemVisible = call != null; } if (chat.megagroup) { @@ -6032,7 +6060,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. otherItem.addSubItem(call_item, R.drawable.msg_voicechat, LocaleController.getString("StartVoipChat", R.string.StartVoipChat)); hasVoiceChatItem = true; } - ChatObject.Call call = getMessagesController().getGroupCall(chat_id, false); + ChatObject.Call call = getMessagesController().getGroupCall(chatId, false); callItemVisible = call != null; } if (ChatObject.canChangeChatInfo(chat)) { @@ -6143,15 +6171,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. long did = dids.get(0); Bundle args = new Bundle(); args.putBoolean("scrollToTopOnResume", true); - int lower_part = (int) did; - if (lower_part != 0) { - if (lower_part > 0) { - args.putInt("user_id", lower_part); - } else { - args.putInt("chat_id", -lower_part); - } - } else { - args.putInt("enc_id", (int) (did >> 32)); + if (DialogObject.isEncryptedDialog(did)) { + args.putInt("enc_id", DialogObject.getEncryptedChatId(did)); + } else if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); + } else if (DialogObject.isChatDialog(did)) { + args.putLong("chat_id", -did); } if (!getMessagesController().checkCanOpenChat(args, fragment)) { return; @@ -6161,7 +6186,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. getNotificationCenter().postNotificationName(NotificationCenter.closeChats); presentFragment(new ChatActivity(args), true); removeSelfFromStack(); - TLRPC.User user = getMessagesController().getUser(user_id); + TLRPC.User user = getMessagesController().getUser(userId); getSendMessagesHelper().sendMessage(user, did, null, null, null, null, true, 0); } @@ -6171,7 +6196,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. imageUpdater.onRequestPermissionsResultFragment(requestCode, permissions, grantResults); } if (requestCode == 101 || requestCode == 102) { - final TLRPC.User user = getMessagesController().getUser(user_id); + final TLRPC.User user = getMessagesController().getUser(userId); if (user == null) { return; } @@ -6199,7 +6224,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } } if (grantResults.length > 0 && allGranted) { - ChatObject.Call call = getMessagesController().getGroupCall(chat_id, false); + ChatObject.Call call = getMessagesController().getGroupCall(chatId, false); VoIPHelper.startCall(currentChat, null, null, call == null, getParentActivity(), ProfileActivity.this, getAccountInstance()); } else { VoIPHelper.permissionDenied(getParentActivity(), null, requestCode); @@ -6659,7 +6684,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 1: { view = new HeaderCell(mContext, 23); @@ -6769,7 +6794,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. view = sharedMediaLayout; break; } - case 14: { + case 14: + default: { TextInfoPrivacyCell cell = new TextInfoPrivacyCell(mContext, 10); cell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL); cell.getTextView().setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText3)); @@ -6885,7 +6911,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. TextDetailCell detailCell = (TextDetailCell) holder.itemView; if (position == phoneRow) { String text; - final TLRPC.User user = getMessagesController().getUser(user_id); + final TLRPC.User user = getMessagesController().getUser(userId); if (!TextUtils.isEmpty(user.phone)) { text = PhoneFormat.getInstance().format("+" + user.phone); } else { @@ -6894,8 +6920,8 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. detailCell.setTextAndValue(text, LocaleController.getString("PhoneMobile", R.string.PhoneMobile), false); } else if (position == usernameRow) { String text; - if (user_id != 0) { - final TLRPC.User user = getMessagesController().getUser(user_id); + if (userId != 0) { + final TLRPC.User user = getMessagesController().getUser(userId); if (user != null && !TextUtils.isEmpty(user.username)) { text = "@" + user.username; } else { @@ -6903,7 +6929,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } detailCell.setTextAndValue(text, LocaleController.getString("Username", R.string.Username), false); } else if (currentChat != null) { - TLRPC.Chat chat = getMessagesController().getChat(chat_id); + TLRPC.Chat chat = getMessagesController().getChat(chatId); detailCell.setTextAndValue(getMessagesController().linkPrefix + "/" + chat.username, LocaleController.getString("InviteLink", R.string.InviteLink), false); } } else if (position == locationRow) { @@ -6962,7 +6988,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. textCell.setColors(Theme.key_windowBackgroundWhiteGrayIcon, Theme.key_windowBackgroundWhiteBlackText); textCell.setTag(Theme.key_windowBackgroundWhiteBlackText); if (position == settingsTimerRow) { - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat((int) (dialog_id >> 32)); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); String value; if (encryptedChat.ttl == 0) { value = LocaleController.getString("ShortMessageLifetimeForever", R.string.ShortMessageLifetimeForever); @@ -6975,7 +7001,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. textCell.setColors(null, Theme.key_windowBackgroundWhiteRedText5); } else if (position == settingsKeyRow) { IdenticonDrawable identiconDrawable = new IdenticonDrawable(); - TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat((int) (dialog_id >> 32)); + TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(dialogId)); identiconDrawable.setEncryptedChat(encryptedChat); textCell.setTextAndValueDrawable(LocaleController.getString("EncryptionKey", R.string.EncryptionKey), identiconDrawable, false); } else if (position == joinRow) { @@ -7057,12 +7083,12 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. if (position == notificationsRow) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); long did; - if (dialog_id != 0) { - did = dialog_id; - } else if (user_id != 0) { - did = user_id; + if (dialogId != 0) { + did = dialogId; + } else if (userId != 0) { + did = userId; } else { - did = -chat_id; + did = -chatId; } boolean enabled = false; @@ -8080,7 +8106,7 @@ public class ProfileActivity extends BaseFragment implements NotificationCenter. } int oldIndex = oldPositionToItem.get(oldItemPosition, -1); int newIndex = newPositionToItem.get(newItemPosition, -1); - return oldIndex == newIndex && oldIndex >= 0; + return oldIndex == newIndex && oldIndex >= 0 && newIndex >= 0; } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java index e425379b1..18a65e899 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProfileNotificationsActivity.java @@ -31,6 +31,7 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.FileLog; @@ -70,7 +71,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi private ListAdapter adapter; private AnimatorSet animatorSet; - private long dialog_id; + private long dialogId; private boolean addingException; @@ -112,7 +113,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi public ProfileNotificationsActivity(Bundle args) { super(args); - dialog_id = args.getLong("dialog_id"); + dialogId = args.getLong("dialog_id"); addingException = args.getBoolean("exception", false); } @@ -136,14 +137,14 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } else { enableRow = -1; } - if ((int) dialog_id != 0) { + if (!DialogObject.isEncryptedDialog(dialogId)) { previewRow = rowCount++; } else { previewRow = -1; } soundRow = rowCount++; vibrateRow = rowCount++; - if ((int) dialog_id < 0) { + if (DialogObject.isChatDialog(dialogId)) { smartRow = rowCount++; } else { smartRow = -1; @@ -155,14 +156,13 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } priorityInfoRow = rowCount++; boolean isChannel; - int lower_id = (int) dialog_id; - if (lower_id < 0) { - TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); + if (DialogObject.isChatDialog(dialogId)) { + TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId); isChannel = ChatObject.isChannel(chat) && !chat.megagroup; } else { isChannel = false; } - if (lower_id != 0 && !isChannel) { + if (!DialogObject.isEncryptedDialog(dialogId) && !isChannel) { popupRow = rowCount++; popupEnabledRow = rowCount++; popupDisabledRow = rowCount++; @@ -174,7 +174,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi popupInfoRow = -1; } - if (lower_id > 0) { + if (DialogObject.isUserDialog(dialogId)) { callsRow = rowCount++; callsVibrateRow = rowCount++; ringtoneRow = rowCount++; @@ -191,15 +191,15 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi ledInfoRow = rowCount++; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - customEnabled = preferences.getBoolean("custom_" + dialog_id, false) || addingException; + customEnabled = preferences.getBoolean("custom_" + dialogId, false) || addingException; - boolean hasOverride = preferences.contains("notify2_" + dialog_id); - int value = preferences.getInt("notify2_" + dialog_id, 0); + boolean hasOverride = preferences.contains("notify2_" + dialogId); + int value = preferences.getInt("notify2_" + dialogId, 0); if (value == 0) { if (hasOverride) { notificationsEnabled = true; } else { - notificationsEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(dialog_id); + notificationsEnabled = NotificationsController.getInstance(currentAccount).isGlobalNotificationsEnabled(dialogId); } } else if (value == 1) { notificationsEnabled = true; @@ -229,25 +229,25 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi if (id == -1) { if (!addingException && notificationsEnabled && customEnabled) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - preferences.edit().putInt("notify2_" + dialog_id, 0).commit(); + preferences.edit().putInt("notify2_" + dialogId, 0).commit(); } } else if (id == done_button) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean("custom_" + dialog_id, true); + editor.putBoolean("custom_" + dialogId, true); - TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialog_id); + TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId); if (notificationsEnabled) { - editor.putInt("notify2_" + dialog_id, 0); - MessagesStorage.getInstance(currentAccount).setDialogFlags(dialog_id, 0); + editor.putInt("notify2_" + dialogId, 0); + MessagesStorage.getInstance(currentAccount).setDialogFlags(dialogId, 0); if (dialog != null) { dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); } } else { - editor.putInt("notify2_" + dialog_id, 2); - NotificationsController.getInstance(currentAccount).removeNotificationsForDialog(dialog_id); - MessagesStorage.getInstance(currentAccount).setDialogFlags(dialog_id, 1); + editor.putInt("notify2_" + dialogId, 2); + NotificationsController.getInstance(currentAccount).removeNotificationsForDialog(dialogId); + MessagesStorage.getInstance(currentAccount).setDialogFlags(dialogId, 1); if (dialog != null) { dialog.notify_settings = new TLRPC.TL_peerNotifySettings(); dialog.notify_settings.mute_until = Integer.MAX_VALUE; @@ -255,14 +255,14 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } editor.commit(); - NotificationsController.getInstance(currentAccount).updateServerNotificationsSettings(dialog_id); + NotificationsController.getInstance(currentAccount).updateServerNotificationsSettings(dialogId); if (delegate != null) { NotificationsSettingsActivity.NotificationException exception = new NotificationsSettingsActivity.NotificationException(); - exception.did = dialog_id; + exception.did = dialogId; exception.hasCustom = true; - exception.notify = preferences.getInt("notify2_" + dialog_id, 0); + exception.notify = preferences.getInt("notify2_" + dialogId, 0); if (exception.notify != 0) { - exception.muteUntil = preferences.getInt("notifyuntil_" + dialog_id, 0); + exception.muteUntil = preferences.getInt("notifyuntil_" + dialogId, 0); } delegate.didCreateNewException(exception); } @@ -299,7 +299,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); customEnabled = !customEnabled; notificationsEnabled = customEnabled; - preferences.edit().putBoolean("custom_" + dialog_id, customEnabled).commit(); + preferences.edit().putBoolean("custom_" + dialogId, customEnabled).commit(); TextCheckBoxCell cell = (TextCheckBoxCell) view; cell.setChecked(customEnabled); checkRowsEnabled(); @@ -323,7 +323,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi defaultPath = defaultUri.getPath(); } - String path = preferences.getString("sound_path_" + dialog_id, defaultPath); + String path = preferences.getString("sound_path_" + dialogId, defaultPath); if (path != null && !path.equals("NoSound")) { if (path.equals(defaultPath)) { currentSound = defaultUri; @@ -353,7 +353,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi defaultPath = defaultUri.getPath(); } - String path = preferences.getString("ringtone_path_" + dialog_id, defaultPath); + String path = preferences.getString("ringtone_path_" + dialogId, defaultPath); if (path != null && !path.equals("NoSound")) { if (path.equals(defaultPath)) { currentSound = defaultUri; @@ -368,7 +368,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi FileLog.e(e); } } else if (position == vibrateRow) { - showDialog(AlertsCreator.createVibrationSelectDialog(getParentActivity(), dialog_id, false, false, () -> { + showDialog(AlertsCreator.createVibrationSelectDialog(getParentActivity(), dialogId, false, false, () -> { if (adapter != null) { adapter.notifyItemChanged(vibrateRow); } @@ -381,16 +381,16 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } else if (position == previewRow) { TextCheckCell checkCell = (TextCheckCell) view; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - preferences.edit().putBoolean("content_preview_" + dialog_id, !checkCell.isChecked()).commit(); + preferences.edit().putBoolean("content_preview_" + dialogId, !checkCell.isChecked()).commit(); checkCell.setChecked(!checkCell.isChecked()); } else if (position == callsVibrateRow) { - showDialog(AlertsCreator.createVibrationSelectDialog(getParentActivity(), dialog_id, "calls_vibrate_" + dialog_id, () -> { + showDialog(AlertsCreator.createVibrationSelectDialog(getParentActivity(), dialogId, "calls_vibrate_" + dialogId, () -> { if (adapter != null) { adapter.notifyItemChanged(callsVibrateRow); } })); } else if (position == priorityRow) { - showDialog(AlertsCreator.createPrioritySelectDialog(getParentActivity(), dialog_id, -1, () -> { + showDialog(AlertsCreator.createPrioritySelectDialog(getParentActivity(), dialogId, -1, () -> { if (adapter != null) { adapter.notifyItemChanged(priorityRow); } @@ -401,8 +401,8 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } final Context context1 = getParentActivity(); SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2); - int notifyDelay = preferences.getInt("smart_delay_" + dialog_id, 3 * 60); + int notifyMaxCount = preferences.getInt("smart_max_count_" + dialogId, 2); + int notifyDelay = preferences.getInt("smart_delay_" + dialogId, 3 * 60); if (notifyMaxCount == 0) { notifyMaxCount = 2; } @@ -457,8 +457,8 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi int notifyMaxCount1 = position1 % 10 + 1; int notifyDelay1 = position1 / 10 + 1; SharedPreferences preferences1 = MessagesController.getNotificationsSettings(currentAccount); - preferences1.edit().putInt("smart_max_count_" + dialog_id, notifyMaxCount1).commit(); - preferences1.edit().putInt("smart_delay_" + dialog_id, notifyDelay1 * 60).commit(); + preferences1.edit().putInt("smart_max_count_" + dialogId, notifyMaxCount1).commit(); + preferences1.edit().putInt("smart_delay_" + dialogId, notifyDelay1 * 60).commit(); if (adapter != null) { adapter.notifyItemChanged(smartRow); } @@ -470,7 +470,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi builder.setPositiveButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("SmartNotificationsDisabled", R.string.SmartNotificationsDisabled), (dialog, which) -> { SharedPreferences preferences12 = MessagesController.getNotificationsSettings(currentAccount); - preferences12.edit().putInt("smart_max_count_" + dialog_id, 0).commit(); + preferences12.edit().putInt("smart_max_count_" + dialogId, 0).commit(); if (adapter != null) { adapter.notifyItemChanged(smartRow); } @@ -481,14 +481,14 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi if (getParentActivity() == null) { return; } - showDialog(AlertsCreator.createColorSelectDialog(getParentActivity(), dialog_id, -1, () -> { + showDialog(AlertsCreator.createColorSelectDialog(getParentActivity(), dialogId, -1, () -> { if (adapter != null) { adapter.notifyItemChanged(colorRow); } })); } else if (position == popupEnabledRow) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - preferences.edit().putInt("popup_" + dialog_id, 1).commit(); + preferences.edit().putInt("popup_" + dialogId, 1).commit(); ((RadioCell) view).setChecked(true, true); view = listView.findViewWithTag(2); if (view != null) { @@ -496,7 +496,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } } else if (position == popupDisabledRow) { SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - preferences.edit().putInt("popup_" + dialog_id, 2).commit(); + preferences.edit().putInt("popup_" + dialogId, 2).commit(); ((RadioCell) view).setChecked(true, true); view = listView.findViewWithTag(1); if (view != null) { @@ -543,20 +543,20 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi if (requestCode == 12) { if (name != null) { - editor.putString("sound_" + dialog_id, name); - editor.putString("sound_path_" + dialog_id, ringtone.toString()); + editor.putString("sound_" + dialogId, name); + editor.putString("sound_path_" + dialogId, ringtone.toString()); } else { - editor.putString("sound_" + dialog_id, "NoSound"); - editor.putString("sound_path_" + dialog_id, "NoSound"); + editor.putString("sound_" + dialogId, "NoSound"); + editor.putString("sound_path_" + dialogId, "NoSound"); } - getNotificationsController().deleteNotificationChannel(dialog_id); + getNotificationsController().deleteNotificationChannel(dialogId); } else if (requestCode == 13) { if (name != null) { - editor.putString("ringtone_" + dialog_id, name); - editor.putString("ringtone_path_" + dialog_id, ringtone.toString()); + editor.putString("ringtone_" + dialogId, name); + editor.putString("ringtone_path_" + dialogId, ringtone.toString()); } else { - editor.putString("ringtone_" + dialog_id, "NoSound"); - editor.putString("ringtone_path_" + dialog_id, "NoSound"); + editor.putString("ringtone_" + dialogId, "NoSound"); + editor.putString("ringtone_path_" + dialogId, "NoSound"); } } editor.commit(); @@ -739,19 +739,19 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi TextSettingsCell textCell = (TextSettingsCell) holder.itemView; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); if (position == soundRow) { - String value = preferences.getString("sound_" + dialog_id, LocaleController.getString("SoundDefault", R.string.SoundDefault)); + String value = preferences.getString("sound_" + dialogId, LocaleController.getString("SoundDefault", R.string.SoundDefault)); if (value.equals("NoSound")) { value = LocaleController.getString("NoSound", R.string.NoSound); } textCell.setTextAndValue(LocaleController.getString("Sound", R.string.Sound), value, true); } else if (position == ringtoneRow) { - String value = preferences.getString("ringtone_" + dialog_id, LocaleController.getString("DefaultRingtone", R.string.DefaultRingtone)); + String value = preferences.getString("ringtone_" + dialogId, LocaleController.getString("DefaultRingtone", R.string.DefaultRingtone)); if (value.equals("NoSound")) { value = LocaleController.getString("NoSound", R.string.NoSound); } textCell.setTextAndValue(LocaleController.getString("VoipSettingsRingtone", R.string.VoipSettingsRingtone), value, false); } else if (position == vibrateRow) { - int value = preferences.getInt("vibrate_" + dialog_id, 0); + int value = preferences.getInt("vibrate_" + dialogId, 0); if (value == 0 || value == 4) { textCell.setTextAndValue(LocaleController.getString("Vibrate", R.string.Vibrate), LocaleController.getString("VibrationDefault", R.string.VibrationDefault), smartRow != -1 || priorityRow != -1); } else if (value == 1) { @@ -762,7 +762,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi textCell.setTextAndValue(LocaleController.getString("Vibrate", R.string.Vibrate), LocaleController.getString("Long", R.string.Long), smartRow != -1 || priorityRow != -1); } } else if (position == priorityRow) { - int value = preferences.getInt("priority_" + dialog_id, 3); + int value = preferences.getInt("priority_" + dialogId, 3); if (value == 0) { textCell.setTextAndValue(LocaleController.getString("NotificationsImportance", R.string.NotificationsImportance), LocaleController.getString("NotificationsPriorityHigh", R.string.NotificationsPriorityHigh), false); } else if (value == 1 || value == 2) { @@ -775,8 +775,8 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi textCell.setTextAndValue(LocaleController.getString("NotificationsImportance", R.string.NotificationsImportance), LocaleController.getString("NotificationsPriorityMedium", R.string.NotificationsPriorityMedium), false); } } else if (position == smartRow) { - int notifyMaxCount = preferences.getInt("smart_max_count_" + dialog_id, 2); - int notifyDelay = preferences.getInt("smart_delay_" + dialog_id, 3 * 60); + int notifyMaxCount = preferences.getInt("smart_max_count_" + dialogId, 2); + int notifyDelay = preferences.getInt("smart_delay_" + dialogId, 3 * 60); if (notifyMaxCount == 0) { textCell.setTextAndValue(LocaleController.getString("SmartNotifications", R.string.SmartNotifications), LocaleController.getString("SmartNotificationsDisabled", R.string.SmartNotificationsDisabled), priorityRow != -1); } else { @@ -784,7 +784,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi textCell.setTextAndValue(LocaleController.getString("SmartNotifications", R.string.SmartNotifications), LocaleController.formatString("SmartNotificationsInfo", R.string.SmartNotificationsInfo, notifyMaxCount, minutes), priorityRow != -1); } } else if (position == callsVibrateRow) { - int value = preferences.getInt("calls_vibrate_" + dialog_id, 0); + int value = preferences.getInt("calls_vibrate_" + dialogId, 0); if (value == 0 || value == 4) { textCell.setTextAndValue(LocaleController.getString("Vibrate", R.string.Vibrate), LocaleController.getString("VibrationDefault", R.string.VibrationDefault), true); } else if (value == 1) { @@ -825,10 +825,10 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi TextColorCell textCell = (TextColorCell) holder.itemView; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); int color; - if (preferences.contains("color_" + dialog_id)) { - color = preferences.getInt("color_" + dialog_id, 0xff0000ff); + if (preferences.contains("color_" + dialogId)) { + color = preferences.getInt("color_" + dialogId, 0xff0000ff); } else { - if ((int) dialog_id < 0) { + if (DialogObject.isChatDialog(dialogId)) { color = preferences.getInt("GroupLed", 0xff0000ff); } else { color = preferences.getInt("MessagesLed", 0xff0000ff); @@ -846,9 +846,9 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi case 4: { RadioCell radioCell = (RadioCell) holder.itemView; SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount); - int popup = preferences.getInt("popup_" + dialog_id, 0); + int popup = preferences.getInt("popup_" + dialogId, 0); if (popup == 0) { - popup = preferences.getInt((int) dialog_id < 0 ? "popupGroup" : "popupAll", 0); + popup = preferences.getInt(DialogObject.isChatDialog(dialogId) ? "popupGroup" : "popupAll", 0); if (popup != 0) { popup = 1; } else { @@ -872,12 +872,11 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi } case 6: { UserCell2 userCell2 = (UserCell2) holder.itemView; - int lower_id = (int) dialog_id; TLObject object; - if (lower_id > 0) { - object = MessagesController.getInstance(currentAccount).getUser(lower_id); + if (DialogObject.isUserDialog(dialogId)) { + object = MessagesController.getInstance(currentAccount).getUser(dialogId); } else { - object = MessagesController.getInstance(currentAccount).getChat(-lower_id); + object = MessagesController.getInstance(currentAccount).getChat(-dialogId); } userCell2.setData(object, null, null, 0); break; @@ -888,7 +887,7 @@ public class ProfileNotificationsActivity extends BaseFragment implements Notifi if (position == enableRow) { checkCell.setTextAndCheck(LocaleController.getString("Notifications", R.string.Notifications), notificationsEnabled, true); } else if (position == previewRow) { - checkCell.setTextAndCheck(LocaleController.getString("MessagePreview", R.string.MessagePreview), preferences.getBoolean("content_preview_" + dialog_id, true), true); + checkCell.setTextAndCheck(LocaleController.getString("MessagePreview", R.string.MessagePreview), preferences.getBoolean("content_preview_" + dialogId, true), true); } break; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java index a356cc63e..45a285237 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProxyListActivity.java @@ -605,7 +605,7 @@ public class ProxyListActivity extends BaseFragment implements NotificationCente @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new ShadowSectionCell(mContext); @@ -627,6 +627,7 @@ public class ProxyListActivity extends BaseFragment implements NotificationCente view.setBackgroundDrawable(Theme.getThemedDrawable(mContext, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow)); break; case 5: + default: view = new TextDetailProxyCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ProxySettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ProxySettingsActivity.java index 94837757d..5b5241bb2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ProxySettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ProxySettingsActivity.java @@ -113,7 +113,7 @@ public class ProxySettingsActivity extends BaseFragment { private static final int done_button = 1; - public class TypeCell extends FrameLayout { + public static class TypeCell extends FrameLayout { private TextView textView; private ImageView checkImage; @@ -273,7 +273,7 @@ public class ProxySettingsActivity extends BaseFragment { typeCell[a].setTag(a); if (a == 0) { typeCell[a].setText(LocaleController.getString("UseProxySocks5", R.string.UseProxySocks5), a == currentType, true); - } else if (a == 1) { + } else { typeCell[a].setText(LocaleController.getString("UseProxyTelegram", R.string.UseProxyTelegram), a == currentType, false); } linearLayout2.addView(typeCell[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50)); @@ -373,7 +373,7 @@ public class ProxySettingsActivity extends BaseFragment { } } else { if (start >= 0) { - phoneField.setSelection(start <= phoneField.length() ? start : phoneField.length()); + phoneField.setSelection(Math.min(start, phoneField.length())); } } ignoreOnTextChange = false; @@ -436,7 +436,7 @@ public class ProxySettingsActivity extends BaseFragment { bottomCells[i].setBackground(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); if (i == 0) { bottomCells[i].setText(LocaleController.getString("UseProxyInfo", R.string.UseProxyInfo)); - } else if (i == 1) { + } else { bottomCells[i].setText(LocaleController.getString("UseProxyTelegramInfo", R.string.UseProxyTelegramInfo) + "\n\n" + LocaleController.getString("UseProxyTelegramInfo2", R.string.UseProxyTelegramInfo2)); bottomCells[i].setVisibility(View.GONE); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/QuickRepliesSettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/QuickRepliesSettingsActivity.java index 0c0a78267..11f6d0f9d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/QuickRepliesSettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/QuickRepliesSettingsActivity.java @@ -186,7 +186,7 @@ public class QuickRepliesSettingsActivity extends BaseFragment { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new TextInfoPrivacyCell(mContext); @@ -204,6 +204,7 @@ public class QuickRepliesSettingsActivity extends BaseFragment { textCells[viewType - 9] = (EditTextSettingsCell) view; break; case 4: + default: view = new TextCheckCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SecretMediaViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/SecretMediaViewer.java index 0092fa2bc..12f6cdb81 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/SecretMediaViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/SecretMediaViewer.java @@ -222,7 +222,7 @@ public class SecretMediaViewer implements NotificationCenter.NotificationCenterD private ImageReceiver centerImage = new ImageReceiver(); private SecretDeleteTimer secretDeleteTimer; private boolean isVisible; - private int currentChannelId; + private long currentDialogId; private AspectRatioFrameLayout aspectRatioFrameLayout; private TextureView videoTextureView; private VideoPlayer videoPlayer; @@ -337,11 +337,11 @@ public class SecretMediaViewer implements NotificationCenter.NotificationCenterD if (currentMessageObject == null) { return; } - int channelId = (Integer) args[1]; + long channelId = (Long) args[1]; if (channelId != 0) { return; } - ArrayList markAsDeletedMessages = (ArrayList)args[0]; + ArrayList markAsDeletedMessages = (ArrayList) args[0]; if (markAsDeletedMessages.contains(currentMessageObject.getId())) { if (isVideo && !videoWatchedOneTime) { closeVideoAfterWatch = true; @@ -355,21 +355,16 @@ public class SecretMediaViewer implements NotificationCenter.NotificationCenterD if (currentMessageObject == null || secretDeleteTimer == null) { return; } - SparseArray> mids = (SparseArray>)args[0]; + long dialogId = (long) args[0]; + if (dialogId != currentDialogId) { + return; + } + SparseArray> mids = (SparseArray>) args[1]; for (int i = 0; i < mids.size(); i++) { int key = mids.keyAt(i); - ArrayList arr = mids.get(key); + ArrayList arr = mids.get(key); for (int a = 0; a < arr.size(); a++) { long mid = arr.get(a); - if (a == 0) { - int channelId = (int) (mid >> 32); - if (channelId < 0) { - channelId = 0; - } - if (channelId != currentChannelId) { - return; - } - } if (currentMessageObject.getId() == mid) { currentMessageObject.messageOwner.destroyTime = key; secretDeleteTimer.invalidate(); @@ -752,7 +747,7 @@ public class SecretMediaViewer implements NotificationCenter.NotificationCenterD NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagesDeleted); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.updateMessageMedia); NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.didCreatedNewDeleteTask); - currentChannelId = messageObject.messageOwner.peer_id != null ? messageObject.messageOwner.peer_id.channel_id : 0; + currentDialogId = MessageObject.getPeerId(messageObject.messageOwner.peer_id); toggleActionBar(true, false); currentMessageObject = messageObject; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ShareActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ShareActivity.java index 570639e50..10cedb987 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ShareActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ShareActivity.java @@ -65,12 +65,12 @@ public class ShareActivity extends Activity { } SerializedData serializedData = new SerializedData(Utilities.hexToBytes(message)); TLRPC.Message mess = TLRPC.Message.TLdeserialize(serializedData, serializedData.readInt32(false), false); - mess.readAttachPath(serializedData, 0); - serializedData.cleanup(); if (mess == null) { finish(); return; } + mess.readAttachPath(serializedData, 0); + serializedData.cleanup(); String link = sharedPreferences.getString(hash + "_link", null); MessageObject messageObject = new MessageObject(UserConfig.selectedAccount, mess, false, true); messageObject.messageOwner.with_my_score = true; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/SponsoredMessageInfoView.java b/TMessagesProj/src/main/java/org/telegram/ui/SponsoredMessageInfoView.java new file mode 100644 index 000000000..f3b4c5bb2 --- /dev/null +++ b/TMessagesProj/src/main/java/org/telegram/ui/SponsoredMessageInfoView.java @@ -0,0 +1,100 @@ +package org.telegram.ui; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.telegram.messenger.AndroidUtilities; +import org.telegram.messenger.LocaleController; +import org.telegram.messenger.R; +import org.telegram.messenger.browser.Browser; +import org.telegram.ui.ActionBar.Theme; +import org.telegram.ui.Components.LayoutHelper; + +public class SponsoredMessageInfoView extends FrameLayout { + + LinearLayout linearLayout; + + public SponsoredMessageInfoView(Activity context, Theme.ResourcesProvider resourcesProvider) { + super(context); + + LinearLayout linearLayout = new LinearLayout(context); + linearLayout.setOrientation(LinearLayout.VERTICAL); + + TextView textView = new TextView(context); + textView.setText(LocaleController.getString("SponsoredMessageInfo", R.string.SponsoredMessageInfo)); + textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); + textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); + textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); + + TextView description1 = new TextView(context); + description1.setText(LocaleController.getString("SponsoredMessageInfoDescription1", R.string.SponsoredMessageInfoDescription1)); + description1.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); + description1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + description1.setLineSpacing(AndroidUtilities.dp(2), 1f); + + TextView description2 = new TextView(context); + description2.setText(LocaleController.getString("SponsoredMessageInfoDescription2", R.string.SponsoredMessageInfoDescription2)); + description2.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); + description2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + description2.setLineSpacing(AndroidUtilities.dp(2), 1f); + + TextView description3 = new TextView(context); + description3.setText(LocaleController.getString("SponsoredMessageInfoDescription3", R.string.SponsoredMessageInfoDescription3)); + description3.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); + description3.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + description3.setLineSpacing(AndroidUtilities.dp(2), 1f); + + Paint buttonPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + buttonPaint.setStyle(Paint.Style.STROKE); + buttonPaint.setColor(Theme.getColor(Theme.key_featuredStickers_addButton, resourcesProvider)); + buttonPaint.setStrokeWidth(AndroidUtilities.dp(1)); + TextView button = new TextView(context) { + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + AndroidUtilities.rectTmp.set(AndroidUtilities.dp(1), AndroidUtilities.dp(1), getMeasuredWidth() - AndroidUtilities.dp(1), getMeasuredHeight() - AndroidUtilities.dp(1)); + canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(4), AndroidUtilities.dp(4), buttonPaint); + } + }; + button.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + Browser.openUrl(context, LocaleController.getString("SponsoredMessageAlertLearnMoreUrl", R.string.SponsoredMessageAlertLearnMoreUrl)); + } + }); + + button.setPadding(AndroidUtilities.dp(12), 0, AndroidUtilities.dp(12), 0); + button.setText(LocaleController.getString("SponsoredMessageAlertLearnMoreUrl", R.string.SponsoredMessageAlertLearnMoreUrl)); + button.setTextColor(Theme.getColor(Theme.key_featuredStickers_addButton, resourcesProvider)); + button.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_dialogBackground, resourcesProvider), Theme.getColor(Theme.key_featuredStickers_addButtonPressed, resourcesProvider))); + button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + button.setGravity(Gravity.CENTER_VERTICAL); + + + TextView description4 = new TextView(context); + description4.setText(LocaleController.getString("SponsoredMessageInfoDescription4", R.string.SponsoredMessageInfoDescription4)); + description4.setLineSpacing(AndroidUtilities.dp(2), 1f); + description4.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider)); + description4.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); + + linearLayout.addView(textView); + linearLayout.addView(description1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 18, 0, 0)); + linearLayout.addView(description2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 24, 0, 0)); + linearLayout.addView(description3, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 24, 0, 0)); + linearLayout.addView(button, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 34, Gravity.CENTER_HORIZONTAL, 0, 14, 0, 0)); + linearLayout.addView(description4, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 14, 0, 0)); + + addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 22, 12, 22, 22)); + + } +} diff --git a/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java index fe5ab48c8..a8129efce 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java @@ -140,7 +140,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente public StatisticActivity(Bundle args) { super(args); - int chatId = args.getInt("chat_id"); + long chatId = args.getLong("chat_id"); isMegagroup = args.getBoolean("is_megagroup", false); this.chat = getMessagesController().getChatFull(chatId); } @@ -212,7 +212,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente if (recentPostsAll.size() > 0) { int lastPostId = recentPostsAll.get(0).counters.msg_id; int count = recentPostsAll.size(); - getMessagesStorage().getMessages(-chat.id, 0, false, count, lastPostId, 0, 0, classGuid, 0, true, false, 0, 0, true); + getMessagesStorage().getMessages(-chat.id, 0, false, count, lastPostId, 0, 0, classGuid, 0, false, 0, 0, true); } AndroidUtilities.runOnUIThread(() -> { @@ -509,7 +509,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente presentFragment(activity); } else if (i == 1) { Bundle bundle = new Bundle(); - bundle.putInt("chat_id", chat.id); + bundle.putLong("chat_id", chat.id); bundle.putInt("message_id", messageObject.getId()); bundle.putBoolean("need_remove_previous_same_chat_activity", false); ChatActivity chatActivity = new ChatActivity(bundle); @@ -2458,7 +2458,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente public static class MemberData { public TLRPC.User user; - int user_id; + long user_id; public String description; public static MemberData from(TLRPC.TL_statsGroupTopPoster poster, ArrayList users) { @@ -2515,7 +2515,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente return data; } - public static TLRPC.User find(int user_id, ArrayList users) { + public static TLRPC.User find(long user_id, ArrayList users) { for (TLRPC.User user : users) { if (user.id == user_id) { return user; @@ -2526,7 +2526,7 @@ public class StatisticActivity extends BaseFragment implements NotificationCente public void onClick(BaseFragment fragment) { Bundle bundle = new Bundle(); - bundle.putInt("user_id", user.id); + bundle.putLong("user_id", user.id); MessagesController.getInstance(UserConfig.selectedAccount).putUser(user, false); fragment.presentFragment(new ProfileActivity(bundle)); } @@ -2577,26 +2577,24 @@ public class StatisticActivity extends BaseFragment implements NotificationCente TLRPC.TL_channels_getParticipant request = new TLRPC.TL_channels_getParticipant(); request.channel = MessagesController.getInstance(UserConfig.selectedAccount).getInputChannel(chat.id); request.participant = MessagesController.getInputPeer(user); - ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(request, (response, error) -> { - AndroidUtilities.runOnUIThread(() -> { - if (fragment.isFinishing() || fragment.getFragmentView() == null) { - return; - } - if (progressDialog[0] == null) { - return; - } - if (error == null) { - TLRPC.TL_channels_channelParticipant participant = (TLRPC.TL_channels_channelParticipant) response; - TLRPC.TL_chatChannelParticipant chatChannelParticipant = new TLRPC.TL_chatChannelParticipant(); - chatChannelParticipant.channelParticipant = participant.participant; - chatChannelParticipant.user_id = user.id; - chat.participants.participants.add(0, chatChannelParticipant); - onLongClick(chat, fragment, progressDialog); - } else { - onLongClick(chat, fragment, progressDialog, false); - } - }); - }); + ConnectionsManager.getInstance(UserConfig.selectedAccount).sendRequest(request, (response, error) -> AndroidUtilities.runOnUIThread(() -> { + if (fragment.isFinishing() || fragment.getFragmentView() == null) { + return; + } + if (progressDialog[0] == null) { + return; + } + if (error == null) { + TLRPC.TL_channels_channelParticipant participant = (TLRPC.TL_channels_channelParticipant) response; + TLRPC.TL_chatChannelParticipant chatChannelParticipant = new TLRPC.TL_chatChannelParticipant(); + chatChannelParticipant.channelParticipant = participant.participant; + chatChannelParticipant.user_id = user.id; + chat.participants.participants.add(0, chatChannelParticipant); + onLongClick(chat, fragment, progressDialog); + } else { + onLongClick(chat, fragment, progressDialog, false); + } + })); return; } @@ -2688,8 +2686,8 @@ public class StatisticActivity extends BaseFragment implements NotificationCente onClick(fragment); } else { Bundle bundle = new Bundle(); - bundle.putInt("chat_id", chat.id); - bundle.putInt("search_from_user_id", user.id); + bundle.putLong("chat_id", chat.id); + bundle.putLong("search_from_user_id", user.id); fragment.presentFragment(new ChatActivity(bundle)); } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/StickersActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/StickersActivity.java index 5090c6c0d..02b78e31c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/StickersActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/StickersActivity.java @@ -287,7 +287,7 @@ public class StickersActivity extends BaseFragment implements NotificationCenter MediaDataController.getInstance(currentAccount).toggleStickerSet(getParentActivity(), stickerSet, 0, StickersActivity.this, false, false); } }; - trendingStickersAlert = new TrendingStickersAlert(context, this, new TrendingStickersLayout(context, trendingDelegate)); + trendingStickersAlert = new TrendingStickersAlert(context, this, new TrendingStickersLayout(context, trendingDelegate), null); trendingStickersAlert.show(); } else if (position == archivedRow) { presentFragment(new ArchivedStickersActivity(currentType)); @@ -790,7 +790,7 @@ public class StickersActivity extends BaseFragment implements NotificationCenter @Override @SuppressLint("ClickableViewAccessibility") public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = null; + View view; switch (viewType) { case 0: view = new StickerSetCell(mContext, 1); @@ -856,6 +856,7 @@ public class StickersActivity extends BaseFragment implements NotificationCenter view = new ShadowSectionCell(mContext); break; case 4: + default: view = new TextCheckCell(mContext); view.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); break; @@ -946,7 +947,7 @@ public class StickersActivity extends BaseFragment implements NotificationCenter if (!SharedConfig.stickersReorderingHintUsed) { SharedConfig.setStickersReorderingHintUsed(true); final String stickersReorderHint = LocaleController.getString("StickersReorderHint", R.string.StickersReorderHint); - Bulletin.make(parentLayout, new ReorderingBulletinLayout(mContext, stickersReorderHint), ReorderingHintDrawable.DURATION * 2 + 250).show(); + Bulletin.make(parentLayout, new ReorderingBulletinLayout(mContext, stickersReorderHint, null), ReorderingHintDrawable.DURATION * 2 + 250).show(); } } } else if (actionModeShowed) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/TextMessageEnterTransition.java b/TMessagesProj/src/main/java/org/telegram/ui/TextMessageEnterTransition.java index c861a17db..8098a8484 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/TextMessageEnterTransition.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/TextMessageEnterTransition.java @@ -105,9 +105,11 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain int fromColor; int toColor; + private final Theme.ResourcesProvider resourcesProvider; @SuppressLint("WrongConstant") - public TextMessageEnterTransition(ChatMessageCell messageView, ChatActivity chatActivity, RecyclerListView listView, MessageEnterTransitionContainer container) { + public TextMessageEnterTransition(ChatMessageCell messageView, ChatActivity chatActivity, RecyclerListView listView, MessageEnterTransitionContainer container, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; currentAccount = UserConfig.selectedAccount; if (messageView.getMessageObject().textLayoutBlocks.size() > 1 || messageView.getMessageObject().textLayoutBlocks.get(0).textLayout.getLineCount() > 10) { return; @@ -218,13 +220,13 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain int normalLinesCount = 0; int rtlLinesCount = 0; - if (Math.abs(ColorUtils.calculateLuminance(Theme.getColor(Theme.key_chat_messageTextOut)) - ColorUtils.calculateLuminance(Theme.getColor(Theme.key_chat_messagePanelText))) > 0.2f) { + if (Math.abs(ColorUtils.calculateLuminance(getThemedColor(Theme.key_chat_messageTextOut)) - ColorUtils.calculateLuminance(getThemedColor(Theme.key_chat_messagePanelText))) > 0.2f) { crossfade = true; changeColor = true; } - fromColor = Theme.getColor(Theme.key_chat_messagePanelText); - toColor = Theme.getColor(Theme.key_chat_messageTextOut); + fromColor = getThemedColor(Theme.key_chat_messagePanelText); + toColor = getThemedColor(Theme.key_chat_messageTextOut); if (messageTextLayout.getLineCount() == layout.getLineCount()) { n = messageTextLayout.getLineCount(); @@ -372,7 +374,7 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_HIGH) { Theme.MessageDrawable drawable = messageView.getCurrentBackgroundDrawable(true); if (drawable != null) { - fromMessageDrawable = drawable.getTransitionDrawable(Theme.getColor(Theme.key_chat_messagePanelBackground)); + fromMessageDrawable = drawable.getTransitionDrawable(getThemedColor(Theme.key_chat_messagePanelBackground)); } } } @@ -506,17 +508,17 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain int replyOwnerMessageColor; int replyLineColor; if (currentMessageObject.hasValidReplyMessageObject() && (currentMessageObject.replyMessageObject.type == 0 || !TextUtils.isEmpty(currentMessageObject.replyMessageObject.caption)) && !(currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame || currentMessageObject.replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice)) { - replyMessageColor = Theme.getColor(Theme.key_chat_outReplyMessageText); + replyMessageColor = getThemedColor(Theme.key_chat_outReplyMessageText); } else { - replyMessageColor = Theme.getColor(Theme.key_chat_outReplyMediaMessageText); + replyMessageColor = getThemedColor(Theme.key_chat_outReplyMediaMessageText); } if (currentMessageObject.isOutOwner()) { - replyOwnerMessageColor = Theme.getColor(Theme.key_chat_outReplyNameText); - replyLineColor = Theme.getColor(Theme.key_chat_outReplyLine); + replyOwnerMessageColor = getThemedColor(Theme.key_chat_outReplyNameText); + replyLineColor = getThemedColor(Theme.key_chat_outReplyLine); } else { - replyOwnerMessageColor = Theme.getColor(Theme.key_chat_inReplyNameText); - replyLineColor = Theme.getColor(Theme.key_chat_inReplyLine); + replyOwnerMessageColor = getThemedColor(Theme.key_chat_inReplyNameText); + replyLineColor = getThemedColor(Theme.key_chat_inReplyLine); } Theme.chat_replyTextPaint.setColor(ColorUtils.blendARGB(replayObjectFromColor, replyMessageColor, progress)); @@ -589,10 +591,11 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain canvas.drawBitmap(textLayoutBitmap, 0, 0, bitmapPaint); } else { if (crossfade && changeColor) { - int oldColor = Theme.chat_msgTextPaint.getColor(); - Theme.chat_msgTextPaint.setColor(ColorUtils.blendARGB(fromColor, toColor, alphaProgress)); + int oldColor = layout.getPaint().getColor(); + int oldAlpha = Color.alpha(oldColor); + layout.getPaint().setColor(ColorUtils.setAlphaComponent(ColorUtils.blendARGB(fromColor, toColor, alphaProgress), (int) (oldAlpha * (1f - alphaProgress)))); layout.draw(canvas); - Theme.chat_msgTextPaint.setColor(oldColor); + layout.getPaint().setColor(oldColor); } else if (crossfade) { int oldAlpha = Theme.chat_msgTextPaint.getAlpha(); Theme.chat_msgTextPaint.setAlpha((int) (oldAlpha * (1f - alphaProgress))); @@ -615,15 +618,16 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain canvas.drawBitmap(textLayoutBitmapRtl, 0, 0, bitmapPaint); } else { if (crossfade && changeColor) { - int oldColor = Theme.chat_msgTextPaint.getColor(); - Theme.chat_msgTextPaint.setColor(ColorUtils.blendARGB(fromColor, toColor, alphaProgress)); + int oldColor = rtlLayout.getPaint().getColor(); + int oldAlpha = Color.alpha(oldColor); + rtlLayout.getPaint().setColor(ColorUtils.setAlphaComponent(ColorUtils.blendARGB(fromColor, toColor, alphaProgress), (int) (oldAlpha * (1f - alphaProgress)))); rtlLayout.draw(canvas); - Theme.chat_msgTextPaint.setColor(oldColor); + rtlLayout.getPaint().setColor(oldColor); } else if (crossfade) { - int oldAlpha = Theme.chat_msgTextPaint.getAlpha(); - Theme.chat_msgTextPaint.setAlpha((int) (oldAlpha * (1f - alphaProgress))); + int oldAlpha = rtlLayout.getPaint().getAlpha(); + rtlLayout.getPaint().setAlpha((int) (oldAlpha * (1f - alphaProgress))); rtlLayout.draw(canvas); - Theme.chat_msgTextPaint.setAlpha(oldAlpha); + rtlLayout.getPaint().setAlpha(oldAlpha); } else { rtlLayout.draw(canvas); } @@ -672,4 +676,9 @@ public class TextMessageEnterTransition implements MessageEnterTransitionContain canvas.restore(); } } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ThemeActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ThemeActivity.java index 9efda1264..a8d2d3120 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ThemeActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ThemeActivity.java @@ -84,6 +84,7 @@ import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.SeekBarView; import org.telegram.ui.Components.ShareAlert; +import org.telegram.ui.Components.SwipeGestureSettingsView; import org.telegram.ui.Components.ThemeEditorView; import java.io.File; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ThemePreviewActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ThemePreviewActivity.java index ffc43bda4..ec797bb0f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ThemePreviewActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ThemePreviewActivity.java @@ -36,6 +36,7 @@ import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; +import androidx.collection.LongSparseArray; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -45,7 +46,6 @@ import androidx.viewpager.widget.ViewPager; import android.os.SystemClock; import android.text.TextPaint; import android.text.TextUtils; -import android.util.LongSparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -59,6 +59,8 @@ import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; +import com.google.android.exoplayer2.util.Log; + import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.BuildVars; @@ -70,6 +72,7 @@ import org.telegram.messenger.ImageLocation; import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; +import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesStorage; @@ -127,7 +130,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro public static final int SCREEN_TYPE_CHANGE_BACKGROUND = 2; private final int screenType; - private boolean useDefaultThemeForButtons = true; + public boolean useDefaultThemeForButtons = true; private ActionBarMenuItem dropDownContainer; private ActionBarMenuItem saveItem; @@ -139,6 +142,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro private Theme.ThemeAccent accent; private boolean removeBackgroundOverride; private int backupAccentColor; + private int backupAccentColor2; private int backupMyMessagesAccentColor; private int backupMyMessagesGradientAccentColor1; private int backupMyMessagesGradientAccentColor2; @@ -155,6 +159,11 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro private long watchForKeyboardEndTime; private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener; + Theme.MessageDrawable msgOutDrawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, true, false); + Theme.MessageDrawable msgOutDrawableSelected = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, true, true); + Theme.MessageDrawable msgOutMediaDrawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, true, false); + Theme.MessageDrawable msgOutMediaDrawableSelected = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_MEDIA, true, true); + private ColorPicker colorPicker; private int lastPickedColor; private int lastPickedColorNum = -1; @@ -297,6 +306,10 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro } } } + msgOutDrawable.themePreview = true; + msgOutMediaDrawable.themePreview = true; + msgOutDrawableSelected.themePreview = true; + msgOutMediaDrawableSelected.themePreview = true; } public ThemePreviewActivity(Theme.ThemeInfo themeInfo) { @@ -315,6 +328,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro accent = applyingTheme.getAccent(!edit); useDefaultThemeForButtons = false; backupAccentColor = accent.accentColor; + backupAccentColor2 = accent.accentColor2; backupMyMessagesAccentColor = accent.myMessagesAccentColor; backupMyMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor1; backupMyMessagesGradientAccentColor2 = accent.myMessagesGradientAccentColor2; @@ -328,6 +342,9 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro backupSlug = accent.patternSlug; backupBackgroundRotation = accent.backgroundRotation; } else { + if (screenType == SCREEN_TYPE_PREVIEW) { + useDefaultThemeForButtons = false; + } accent = applyingTheme.getAccent(false); if (accent != null) { selectedPattern = accent.pattern; @@ -341,6 +358,10 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro Theme.applyThemeTemporary(applyingTheme, true); } NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.goingToPreviewTheme); + msgOutDrawable.themePreview = true; + msgOutMediaDrawable.themePreview = true; + msgOutDrawableSelected.themePreview = true; + msgOutMediaDrawableSelected.themePreview = true; } public void setInitialModes(boolean blur, boolean motion) { @@ -348,6 +369,11 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro isMotion = motion; } + @Override + public int getNavigationBarColor() { + return super.getNavigationBarColor(); + } + @SuppressLint("Recycle") @Override public View createView(Context context) { @@ -554,6 +580,18 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro accent.patternSlug = selectedPattern != null ? selectedPattern.slug : ""; accent.patternIntensity = currentIntensity; accent.patternMotion = isMotion; + if ((int) accent.backgroundOverrideColor == 0) { + accent.backgroundOverrideColor = 0x100000000L; + } + if ((int) accent.backgroundGradientOverrideColor1 == 0) { + accent.backgroundGradientOverrideColor1 = 0x100000000L; + } + if ((int) accent.backgroundGradientOverrideColor2 == 0) { + accent.backgroundGradientOverrideColor2 = 0x100000000L; + } + if ((int) accent.backgroundGradientOverrideColor3 == 0) { + accent.backgroundGradientOverrideColor3 = 0x100000000L; + } saveAccentWallpaper(); NotificationCenter.getGlobalInstance().removeObserver(ThemePreviewActivity.this, NotificationCenter.wallpapersDidLoad); Theme.saveThemeAccents(applyingTheme, true, false, false, true); @@ -1473,8 +1511,8 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro rotation -= 45; messagesPlayAnimationImageView.animate().rotationBy(-45).setDuration(300).setInterpolator(CubicBezierInterpolator.EASE_OUT).start(); if (accent.myMessagesAnimated) { - if (Theme.chat_msgOutDrawable.getMotionBackgroundDrawable() != null) { - Theme.chat_msgOutDrawable.getMotionBackgroundDrawable().switchToNextPosition(); + if (msgOutDrawable.getMotionBackgroundDrawable() != null) { + msgOutDrawable.getMotionBackgroundDrawable().switchToNextPosition(); } } else { int temp; @@ -1840,9 +1878,12 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro colorPicker.setMinBrightness(0.05f); colorPicker.setMaxBrightness(0.8f); } - - colorPicker.setType(1, hasChanges(1), false, 1, false, 0, false); + int colorsCount = accent.accentColor2 != 0 ? 2 : 1; + colorPicker.setType(1, hasChanges(1), 2, colorsCount, false, 0, false); colorPicker.setColor(accent.accentColor, 0); + if (accent.accentColor2 != 0) { + colorPicker.setColor(accent.accentColor2, 1); + } } else { patternLayout[a].addView(colorPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL, 0, 0, 0, 48)); } @@ -2167,8 +2208,12 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro switch (id) { case 1: dropDown.setText(LocaleController.getString("ColorPickerMainColor", R.string.ColorPickerMainColor)); - colorPicker.setType(1, hasChanges(1), false, 1, false, 0, false); + int colorsCount = accent.accentColor2 != 0 ? 2 : 1; + colorPicker.setType(1, hasChanges(1), 2, colorsCount, false, 0, false); colorPicker.setColor(accent.accentColor, 0); + if (accent.accentColor2 != 0) { + colorPicker.setColor(accent.accentColor2, 1); + } if (prevType == 2 || prevType == 3 && accent.myMessagesGradientAccentColor2 != 0) { messagesAdapter.notifyItemRemoved(0); } @@ -2206,7 +2251,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro } else { count = 1; } - colorPicker.setType(2, hasChanges(2), true, count, false, accent.backgroundRotation, false); + colorPicker.setType(2, hasChanges(2), 4, count, false, accent.backgroundRotation, false); colorPicker.setColor(backgroundGradientOverrideColor3 != 0 ? backgroundGradientOverrideColor3 : defaultGradient3, 3); colorPicker.setColor(backgroundGradientOverrideColor2 != 0 ? backgroundGradientOverrideColor2 : defaultGradient2, 2); colorPicker.setColor(backgroundGradientOverrideColor1 != 0 ? backgroundGradientOverrideColor1 : defaultGradient1, 1); @@ -2233,7 +2278,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro } else { count = 1; } - colorPicker.setType(2, hasChanges(3), true, count, true, 0, false); + colorPicker.setType(2, hasChanges(3), 4, count, true, 0, false); colorPicker.setColor(accent.myMessagesGradientAccentColor3, 3); colorPicker.setColor(accent.myMessagesGradientAccentColor2, 2); colorPicker.setColor(accent.myMessagesGradientAccentColor1, 1); @@ -2305,20 +2350,8 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro Drawable background = backgroundImage.getBackground(); Bitmap bitmap = backgroundImage.getImageReceiver().getBitmap(); - Bitmap dst = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(dst); - if (!(background instanceof MotionBackgroundDrawable)) { - background.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); - background.draw(canvas); - } - - Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); - paint.setColorFilter(new PorterDuffColorFilter(patternColor, blendMode)); - paint.setAlpha((int) (255 * Math.abs(currentIntensity))); - canvas.drawBitmap(bitmap, 0, 0, paint); - FileOutputStream stream = new FileOutputStream(toFile); - dst.compress(background instanceof MotionBackgroundDrawable ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 87, stream); + bitmap.compress(background instanceof MotionBackgroundDrawable ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 87, stream); stream.close(); } catch (Throwable e) { FileLog.e(e); @@ -2377,6 +2410,9 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro } } if (type == 1 || type == 3) { + if (backupAccentColor != accent.accentColor2) { + return true; + } if (backupMyMessagesAccentColor != 0) { if (backupMyMessagesAccentColor != accent.myMessagesAccentColor) { return true; @@ -2423,6 +2459,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro private boolean checkDiscard() { if (screenType == SCREEN_TYPE_ACCENT_COLOR && ( accent.accentColor != backupAccentColor || + accent.accentColor2 != backupAccentColor2 || accent.myMessagesAccentColor != backupMyMessagesAccentColor || accent.myMessagesGradientAccentColor1 != backupMyMessagesGradientAccentColor1 || accent.myMessagesGradientAccentColor2 != backupMyMessagesGradientAccentColor2 || @@ -2680,14 +2717,11 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro for (int a = 0, N = arrayList.size(); a < N; a++) { TLRPC.WallPaper wallPaper = arrayList.get(a); if (wallPaper instanceof TLRPC.TL_wallPaper) { - int high_id = (int) (wallPaper.id >> 32); - int lower_id = (int) wallPaper.id; - acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L; - acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L; + acc = MediaDataController.calcHash(acc, wallPaper.id); } } TLRPC.TL_account_getWallPapers req = new TLRPC.TL_account_getWallPapers(); - req.hash = (int) acc; + req.hash = acc; int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_account_wallPapers) { TLRPC.TL_account_wallPapers res = (TLRPC.TL_account_wallPapers) response; @@ -2760,6 +2794,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro if (screenType == SCREEN_TYPE_ACCENT_COLOR) { if (editingTheme) { accent.accentColor = backupAccentColor; + accent.accentColor2 = backupAccentColor2; accent.myMessagesAccentColor = backupMyMessagesAccentColor; accent.myMessagesGradientAccentColor1 = backupMyMessagesGradientAccentColor1; accent.myMessagesGradientAccentColor2 = backupMyMessagesGradientAccentColor2; @@ -2880,8 +2915,16 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro private void applyColor(int color, int num) { if (colorType == 1) { - accent.accentColor = color; - Theme.refreshThemeColors(); + if (num == 0) { + accent.accentColor = color; + Theme.refreshThemeColors(); + } else if (num == 1) { + accent.accentColor2 = color; + Theme.refreshThemeColors(true, true); + listView2.invalidateViews(); + colorPicker.setHasChanges(hasChanges(colorType)); + updatePlayAnimationView(true); + } } else if (colorType == 2) { if (lastPickedColorNum == 0) { accent.backgroundOverrideColor = color; @@ -3168,7 +3211,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro } else { count = 1; } - colorPicker.setType(0, false, true, count, false, previousBackgroundRotation, false); + colorPicker.setType(0, false, 4, count, false, previousBackgroundRotation, false); colorPicker.setColor(backgroundGradientColor3, 3); colorPicker.setColor(backgroundGradientColor2, 2); colorPicker.setColor(backgroundGradientColor1, 1); @@ -3908,10 +3951,10 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { - View view = null; + View view; if (viewType == 0) { view = new DialogCell(null, mContext, false, false); - } else if (viewType == 1) { + } else { view = new LoadingCell(mContext); } view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); @@ -4059,6 +4102,8 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro message.out = true; message.peer_id = new TLRPC.TL_peerUser(); message.peer_id.user_id = 0; + + MessageObject message1 = new MessageObject(UserConfig.selectedAccount, message, true, false); message1.resetLayout(); message1.eventId = 1; @@ -4079,9 +4124,11 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro message.peer_id.user_id = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); MessageObject message2 = new MessageObject(UserConfig.selectedAccount, message, true, false); message2.customReplyName = LocaleController.getString("NewThemePreviewName", R.string.NewThemePreviewName); + message1.customReplyName = "Test User"; message2.eventId = 1; message2.resetLayout(); message2.replyMessageObject = replyMessageObject; + message1.replyMessageObject = message2; messages.add(message2); messages.add(replyMessageObject); @@ -4324,9 +4371,31 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { - View view = null; + View view; if (viewType == 0) { - view = new ChatMessageCell(mContext); + view = new ChatMessageCell(mContext, new Theme.ResourcesProvider() { + @Override + public Integer getColor(String key) { + return Theme.getColor(key); + } + + @Override + public Drawable getDrawable(String drawableKey) { + if (drawableKey.equals(Theme.key_drawable_msgOut)) { + return msgOutDrawable; + } + if (drawableKey.equals(Theme.key_drawable_msgOutSelected)) { + return msgOutDrawableSelected; + } + if (drawableKey.equals(Theme.key_drawable_msgOutMedia)) { + return msgOutMediaDrawable; + } + if (drawableKey.equals(Theme.key_drawable_msgOutMediaSelected)) { + return msgOutMediaDrawableSelected; + } + return Theme.getThemeDrawable(drawableKey); + } + }); ChatMessageCell chatMessageCell = (ChatMessageCell) view; chatMessageCell.setDelegate(new ChatMessageCell.ChatMessageCellDelegate() { @@ -4348,7 +4417,7 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro }; frameLayout.addView(backgroundButtonsContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 76, Gravity.CENTER)); view = frameLayout; - } else if (viewType == 3) { + } else { if (messagesButtonsContainer.getParent() != null) { ((ViewGroup) messagesButtonsContainer.getParent()).removeView(messagesButtonsContainer); } @@ -4624,10 +4693,10 @@ public class ThemePreviewActivity extends BaseFragment implements DownloadContro items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgInSelectedDrawable, Theme.chat_msgInMediaSelectedDrawable}, null, Theme.key_chat_inBubbleSelected)); items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgInMediaDrawable.getShadowDrawables(), null, Theme.key_chat_inBubbleShadow)); - items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); - items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); - items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); - items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutDrawable, Theme.chat_msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); + items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubble)); + items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient1)); + items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient2)); + items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{msgOutDrawable, msgOutMediaDrawable}, null, Theme.key_chat_outBubbleGradient3)); items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, new Drawable[]{Theme.chat_msgOutSelectedDrawable, Theme.chat_msgOutMediaSelectedDrawable}, null, Theme.key_chat_outBubbleSelected)); items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); items.add(new ThemeDescription(listView2, 0, new Class[]{ChatMessageCell.class}, null, Theme.chat_msgOutMediaDrawable.getShadowDrawables(), null, Theme.key_chat_outBubbleShadow)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/TooManyCommunitiesActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/TooManyCommunitiesActivity.java index 66ad2c979..06da6e1a6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/TooManyCommunitiesActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/TooManyCommunitiesActivity.java @@ -67,7 +67,7 @@ public class TooManyCommunitiesActivity extends BaseFragment { private int buttonAnimation; - private Set selectedIds = new HashSet<>(); + private Set selectedIds = new HashSet<>(); private TooManyCommunitiesHintCell hintCell; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/VoiceMessageEnterTransition.java b/TMessagesProj/src/main/java/org/telegram/ui/VoiceMessageEnterTransition.java index 42db77a02..50c1b223f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/VoiceMessageEnterTransition.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/VoiceMessageEnterTransition.java @@ -40,8 +40,10 @@ public class VoiceMessageEnterTransition implements MessageEnterTransitionContai private final LinearGradient gradientShader; private final int messageId; MessageEnterTransitionContainer container; + private final Theme.ResourcesProvider resourcesProvider; - public VoiceMessageEnterTransition(ChatMessageCell messageView, ChatActivityEnterView chatActivityEnterView, RecyclerListView listView, MessageEnterTransitionContainer container) { + public VoiceMessageEnterTransition(ChatMessageCell messageView, ChatActivityEnterView chatActivityEnterView, RecyclerListView listView, MessageEnterTransitionContainer container, Theme.ResourcesProvider resourcesProvider) { + this.resourcesProvider = resourcesProvider; this.messageView = messageView; this.container = container; this.listView = listView; @@ -130,7 +132,7 @@ public class VoiceMessageEnterTransition implements MessageEnterTransitionContai canvas.save(); } - circlePaint.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_chat_messagePanelVoiceBackground), Theme.getColor(messageView.getRadialProgress().getCircleColorKey()), progress)); + circlePaint.setColor(ColorUtils.blendARGB(getThemedColor(Theme.key_chat_messagePanelVoiceBackground), getThemedColor(messageView.getRadialProgress().getCircleColorKey()), progress)); recordCircle.drawWaves(canvas, cx, cy, 1f - hideWavesProgress); @@ -160,4 +162,9 @@ public class VoiceMessageEnterTransition implements MessageEnterTransitionContai recordCircle.drawIcon(canvas, (int) fromCx, (int) fromCy, 1f - moveProgress); } + + private int getThemedColor(String key) { + Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null; + return color != null ? color : Theme.getColor(key); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/WallpapersListActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/WallpapersListActivity.java index 491388012..28cb40691 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/WallpapersListActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/WallpapersListActivity.java @@ -42,10 +42,12 @@ import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ApplicationLoader; +import org.telegram.messenger.DialogObject; import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLog; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MediaController; +import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MessagesController; import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.R; @@ -601,20 +603,16 @@ public class WallpapersListActivity extends BaseFragment implements Notification fragment1.finishFragment(); } else { long did = dids.get(0); - int lower_part = (int) did; - int high_part = (int) (did >> 32); Bundle args1 = new Bundle(); args1.putBoolean("scrollToTopOnResume", true); - if (lower_part != 0) { - if (lower_part > 0) { - args1.putInt("user_id", lower_part); - } else if (lower_part < 0) { - args1.putInt("chat_id", -lower_part); - } + if (DialogObject.isEncryptedDialog(did)) { + args1.putInt("enc_id", DialogObject.getEncryptedChatId(did)); } else { - args1.putInt("enc_id", high_part); - } - if (lower_part != 0) { + if (DialogObject.isUserDialog(did)) { + args1.putLong("user_id", did); + } else if (DialogObject.isChatDialog(did)) { + args1.putLong("chat_id", -did); + } if (!MessagesController.getInstance(currentAccount).checkCanOpenChat(args1, fragment1)) { return; } @@ -1057,14 +1055,11 @@ public class WallpapersListActivity extends BaseFragment implements Notification if (wallPaper.id < 0) { continue; } - int high_id = (int) (wallPaper.id >> 32); - int lower_id = (int) wallPaper.id; - acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L; - acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L; + acc = MediaDataController.calcHash(acc, wallPaper.id); } } TLRPC.TL_account_getWallPapers req = new TLRPC.TL_account_getWallPapers(); - req.hash = (int) acc; + req.hash = acc; int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { if (response instanceof TLRPC.TL_account_wallPapers) { TLRPC.TL_account_wallPapers res = (TLRPC.TL_account_wallPapers) response; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/WebviewActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/WebviewActivity.java index c08374a01..9a3de24c8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/WebviewActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/WebviewActivity.java @@ -349,7 +349,7 @@ public class WebviewActivity extends BaseFragment { } loadStats = true; TLRPC.TL_messages_getStatsURL req = new TLRPC.TL_messages_getStatsURL(); - req.peer = MessagesController.getInstance(currentAccount).getInputPeer((int) currentDialogId); + req.peer = MessagesController.getInstance(currentAccount).getInputPeer(currentDialogId); req.params = params != null ? params : ""; req.dark = Theme.getCurrentTheme().isDark(); ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { diff --git a/TMessagesProj/src/main/res/drawable-hdpi/msg_arrow_back.png b/TMessagesProj/src/main/res/drawable-hdpi/msg_arrow_back.png new file mode 100644 index 000000000..ef6d15a50 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/msg_arrow_back.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/msg_colors.png b/TMessagesProj/src/main/res/drawable-hdpi/msg_colors.png new file mode 100644 index 000000000..0cb63dda5 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/msg_colors.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/msg_panel_reply.png b/TMessagesProj/src/main/res/drawable-hdpi/msg_panel_reply.png old mode 100755 new mode 100644 index 7f01b9abd..91e1db242 Binary files a/TMessagesProj/src/main/res/drawable-hdpi/msg_panel_reply.png and b/TMessagesProj/src/main/res/drawable-hdpi/msg_panel_reply.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/msg_played.png b/TMessagesProj/src/main/res/drawable-hdpi/msg_played.png new file mode 100644 index 000000000..ab5087f15 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/msg_played.png differ diff --git a/TMessagesProj/src/main/res/drawable-hdpi/msg_seen.png b/TMessagesProj/src/main/res/drawable-hdpi/msg_seen.png new file mode 100644 index 000000000..24ee4b7bc Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-hdpi/msg_seen.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/msg_arrow_back.png b/TMessagesProj/src/main/res/drawable-mdpi/msg_arrow_back.png new file mode 100644 index 000000000..b83793877 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/msg_arrow_back.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/msg_colors.png b/TMessagesProj/src/main/res/drawable-mdpi/msg_colors.png new file mode 100644 index 000000000..3ac6db33a Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/msg_colors.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/msg_panel_reply.png b/TMessagesProj/src/main/res/drawable-mdpi/msg_panel_reply.png old mode 100755 new mode 100644 index 1fdd6af8c..480e426b9 Binary files a/TMessagesProj/src/main/res/drawable-mdpi/msg_panel_reply.png and b/TMessagesProj/src/main/res/drawable-mdpi/msg_panel_reply.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/msg_played.png b/TMessagesProj/src/main/res/drawable-mdpi/msg_played.png new file mode 100644 index 000000000..ac87b01ed Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/msg_played.png differ diff --git a/TMessagesProj/src/main/res/drawable-mdpi/msg_seen.png b/TMessagesProj/src/main/res/drawable-mdpi/msg_seen.png new file mode 100644 index 000000000..1ba2726ba Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-mdpi/msg_seen.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/msg_arrow_back.png b/TMessagesProj/src/main/res/drawable-xhdpi/msg_arrow_back.png new file mode 100644 index 000000000..8b9659369 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/msg_arrow_back.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/msg_colors.png b/TMessagesProj/src/main/res/drawable-xhdpi/msg_colors.png new file mode 100644 index 000000000..8a7a63341 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/msg_colors.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/msg_panel_reply.png b/TMessagesProj/src/main/res/drawable-xhdpi/msg_panel_reply.png old mode 100755 new mode 100644 index 077cbf068..872a55454 Binary files a/TMessagesProj/src/main/res/drawable-xhdpi/msg_panel_reply.png and b/TMessagesProj/src/main/res/drawable-xhdpi/msg_panel_reply.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/msg_played.png b/TMessagesProj/src/main/res/drawable-xhdpi/msg_played.png new file mode 100644 index 000000000..d85718dcf Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/msg_played.png differ diff --git a/TMessagesProj/src/main/res/drawable-xhdpi/msg_seen.png b/TMessagesProj/src/main/res/drawable-xhdpi/msg_seen.png new file mode 100644 index 000000000..bc15e499f Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xhdpi/msg_seen.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_arrow_back.png b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_arrow_back.png new file mode 100644 index 000000000..39862c8ba Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_arrow_back.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_colors.png b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_colors.png new file mode 100644 index 000000000..e3a0d0538 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_colors.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_panel_reply.png b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_panel_reply.png old mode 100755 new mode 100644 index a36b29779..96a8b798f Binary files a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_panel_reply.png and b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_panel_reply.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_played.png b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_played.png new file mode 100644 index 000000000..d61a99502 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_played.png differ diff --git a/TMessagesProj/src/main/res/drawable-xxhdpi/msg_seen.png b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_seen.png new file mode 100644 index 000000000..0f9626a17 Binary files /dev/null and b/TMessagesProj/src/main/res/drawable-xxhdpi/msg_seen.png differ diff --git a/TMessagesProj/src/main/res/drawable/theme_preview_image.jpg b/TMessagesProj/src/main/res/drawable/theme_preview_image.jpg index a929ceeea..6dec52c7e 100644 Binary files a/TMessagesProj/src/main/res/drawable/theme_preview_image.jpg and b/TMessagesProj/src/main/res/drawable/theme_preview_image.jpg differ diff --git a/TMessagesProj/src/main/res/raw/db_migration_placeholder.tgs b/TMessagesProj/src/main/res/raw/db_migration_placeholder.tgs new file mode 100644 index 000000000..cd0cb6a26 --- /dev/null +++ b/TMessagesProj/src/main/res/raw/db_migration_placeholder.tgs @@ -0,0 +1 @@ + {"tgs":1,"v":"5.5.2","fr":60,"ip":0,"op":180,"w":512,"h":512,"nm":"_007_OPEN_YL","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"Layer 19","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[360]}]},"p":{"a":0,"k":[250.346,388.469,0]},"a":{"a":0,"k":[-3.828,136.874,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[11.556,0],[0,11.557],[-11.556,0],[0,-11.557]],"o":[[-11.556,0],[0,-11.557],[11.556,0],[0,11.557]],"v":[[-3.829,157.832],[-24.787,136.874],[-3.829,115.916],[17.13,136.874]],"c":true}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0.843,2.099],[0,0],[0,0],[0,0],[1.803,1.418],[0,0],[0,0],[0,0],[2.31,0.328],[0,0],[0,0],[0,0],[2.099,-0.843],[0,0],[0,0],[0,0],[1.418,-1.803],[0,0],[0,0],[0,0],[0.328,-2.31],[0,0],[0,0],[0,0],[-0.843,-2.099],[0,0],[0,0],[0,0],[-1.803,-1.418],[0,0],[0,0],[0,0],[-2.31,-0.328],[0,0],[0,0],[0,0],[-2.099,0.843],[0,0],[0,0],[0,0],[-1.418,1.803],[0,0],[0,0],[0,0],[-0.328,2.31]],"o":[[0,0],[0,0],[-0.328,-2.31],[0,0],[0,0],[0,0],[-1.418,-1.803],[0,0],[0,0],[0,0],[-2.099,-0.843],[0,0],[0,0],[0,0],[-2.31,0.328],[0,0],[0,0],[0,0],[-1.803,1.418],[0,0],[0,0],[0,0],[-0.843,2.099],[0,0],[0,0],[0,0],[0.328,2.31],[0,0],[0,0],[0,0],[1.418,1.803],[0,0],[0,0],[0,0],[2.099,0.843],[0,0],[0,0],[0,0],[2.31,-0.328],[0,0],[0,0],[0,0],[1.803,-1.418],[0,0],[0,0],[0,0],[0.843,-2.099],[0,0]],"v":[[31.951,139.5],[31.951,134.248],[24.616,132.804],[22.841,126.175],[28.47,121.259],[25.844,116.71],[18.766,119.129],[13.916,114.28],[16.335,107.201],[11.787,104.575],[6.871,110.204],[0.241,108.43],[-1.202,101.095],[-6.454,101.095],[-7.898,108.43],[-14.528,110.204],[-19.444,104.575],[-23.992,107.201],[-21.573,114.28],[-26.422,119.129],[-33.501,116.71],[-36.127,121.259],[-30.498,126.175],[-32.272,132.804],[-39.608,134.248],[-39.608,139.5],[-32.272,140.944],[-30.498,147.573],[-36.127,152.489],[-33.501,157.038],[-26.422,154.619],[-21.573,159.468],[-23.992,166.547],[-19.444,169.173],[-14.527,163.543],[-7.898,165.318],[-6.454,172.653],[-1.202,172.653],[0.241,165.318],[6.87,163.543],[11.787,169.173],[16.335,166.547],[13.916,159.468],[18.765,154.619],[25.844,157.038],[28.47,152.489],[22.841,147.573],[24.615,140.944]],"c":true}},"nm":"Path 2","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"Layer 18","sr":1,"ks":{"p":{"a":0,"k":[250.346,388.469,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[5.27,0],[0,-5.27],[-5.27,0],[0,5.27]],"o":[[-5.27,0],[0,5.27],[5.27,0],[0,-5.27]],"v":[[0,-9.543],[-9.543,0],[0,9.543],[9.543,0]],"c":true}},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Layer 17","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[-360]}]},"p":{"a":0,"k":[204.91,327.237,0]},"a":{"a":0,"k":[-39.608,87.931,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,-4.853],[4.853,0],[0,4.853],[-4.853,0]],"o":[[0,4.853],[-4.853,0],[0,-4.853],[4.853,0]],"v":[[-30.807,87.931],[-39.608,96.732],[-48.409,87.931],[-39.608,79.13]],"c":true}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0.355,1.008],[0,0],[0,0],[0,0],[0.814,0.701],[0,0],[0,0],[0,0],[1.07,0.201],[0,0],[0,0],[0,0],[1.008,-0.355],[0,0],[0,0],[0,0],[0.701,-0.814],[0,0],[0,0],[0,0],[0.201,-1.07],[0,0],[0,0],[0,0],[-0.355,-1.008],[0,0],[0,0],[0,0],[-0.814,-0.701],[0,0],[0,0],[0,0],[-1.07,-0.201],[0,0],[0,0],[0,0],[-1.008,0.355],[0,0],[0,0],[0,0],[-0.701,0.814],[0,0],[0,0],[0,0],[-0.201,1.07]],"o":[[0,0],[0,0],[-0.201,-1.07],[0,0],[0,0],[0,0],[-0.701,-0.814],[0,0],[0,0],[0,0],[-1.008,-0.355],[0,0],[0,0],[0,0],[-1.07,0.201],[0,0],[0,0],[0,0],[-0.814,0.701],[0,0],[0,0],[0,0],[-0.355,1.008],[0,0],[0,0],[0,0],[0.201,1.07],[0,0],[0,0],[0,0],[0.701,0.814],[0,0],[0,0],[0,0],[1.008,0.355],[0,0],[0,0],[0,0],[1.07,-0.201],[0,0],[0,0],[0,0],[0.814,-0.701],[0,0],[0,0],[0,0],[0.355,-1.008],[0,0]],"v":[[-9.582,90.135],[-9.582,85.727],[-18.553,83.962],[-19.389,80.841],[-12.502,74.826],[-14.706,71.009],[-23.37,73.97],[-25.647,71.693],[-22.686,63.029],[-26.503,60.826],[-32.518,67.712],[-35.638,66.876],[-37.404,57.905],[-41.811,57.905],[-43.577,66.876],[-46.698,67.712],[-52.712,60.826],[-56.529,63.029],[-53.568,71.693],[-55.845,73.97],[-64.509,71.009],[-66.713,74.826],[-59.826,80.841],[-60.663,83.962],[-69.634,85.727],[-69.634,90.135],[-60.663,91.9],[-59.826,95.021],[-66.713,101.035],[-64.509,104.852],[-55.845,101.892],[-53.568,104.168],[-56.529,112.832],[-52.712,115.036],[-46.697,108.149],[-43.577,108.985],[-41.811,117.957],[-37.404,117.957],[-35.638,108.985],[-32.518,108.149],[-26.503,115.036],[-22.686,112.832],[-25.647,104.168],[-23.37,101.892],[-14.706,104.852],[-12.502,101.035],[-19.389,95.021],[-18.553,91.9]],"c":true}},"nm":"Path 2","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"Layer 11","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[720]}]},"p":{"a":0,"k":[247.222,290.909,0]},"a":{"a":0,"k":[-6.431,55.574,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[1.523,0],[0,1.523],[-1.523,0],[0,-1.523]],"o":[[-1.523,0],[0,-1.523],[1.523,0],[0,1.523]],"v":[[-0.987,58.333],[-3.745,55.574],[-0.987,52.816],[1.771,55.574]],"c":true}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[1.523,0],[0,1.523],[-1.523,0],[0,-1.523]],"o":[[-1.523,0],[0,-1.523],[1.523,0],[0,1.523]],"v":[[-6.431,63.777],[-9.19,61.018],[-6.431,58.26],[-3.673,61.018]],"c":true}},"nm":"Path 2","hd":false},{"ind":2,"ty":"sh","ks":{"a":0,"k":{"i":[[1.523,0],[0,1.523],[-1.523,0],[0,-1.523]],"o":[[-1.523,0],[0,-1.523],[1.523,0],[0,1.523]],"v":[[-11.875,58.333],[-14.634,55.574],[-11.875,52.816],[-9.117,55.574]],"c":true}},"nm":"Path 3","hd":false},{"ind":3,"ty":"sh","ks":{"a":0,"k":{"i":[[-1.523,0],[0,-1.523],[1.523,0],[0,1.523]],"o":[[1.523,0],[0,1.523],[-1.523,0],[0,-1.523]],"v":[[-6.431,47.372],[-3.673,50.13],[-6.431,52.888],[-9.19,50.13]],"c":true}},"nm":"Path 4","hd":false},{"ind":4,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0.842,1.332],[0,0],[0,0],[0,0],[1.584,0.357],[0,0],[0,0],[0,0],[1.332,-0.842],[0,0],[0,0],[0,0],[0.357,-1.584],[0,0],[0,0],[0,0],[-0.842,-1.332],[0,0],[0,0],[0,0],[-1.584,-0.357],[0,0],[0,0],[0,0],[-1.332,0.842],[0,0],[0,0],[0,0],[-0.357,1.584]],"o":[[0,0],[0,0],[-0.357,-1.584],[0,0],[0,0],[0,0],[-1.332,-0.842],[0,0],[0,0],[0,0],[-1.584,0.357],[0,0],[0,0],[0,0],[-0.842,1.332],[0,0],[0,0],[0,0],[0.357,1.584],[0,0],[0,0],[0,0],[1.332,0.842],[0,0],[0,0],[0,0],[1.584,-0.357],[0,0],[0,0],[0,0],[0.842,-1.332],[0,0]],"v":[[12.276,57.68],[12.276,53.469],[7.292,52.467],[5.467,48.072],[8.286,43.835],[5.308,40.857],[1.071,43.676],[-3.324,41.851],[-4.326,36.867],[-8.536,36.867],[-9.539,41.851],[-13.934,43.676],[-18.171,40.857],[-21.148,43.835],[-18.33,48.072],[-20.154,52.467],[-25.139,53.469],[-25.139,57.68],[-20.154,58.682],[-18.33,63.077],[-21.148,67.314],[-18.171,70.291],[-13.934,67.473],[-9.539,69.297],[-8.536,74.282],[-4.326,74.282],[-3.324,69.297],[1.071,67.473],[5.308,70.291],[8.286,67.314],[5.467,63.077],[7.292,58.682]],"c":true}},"nm":"Path 5","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":5,"ty":4,"nm":"Layer 12","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[765]}]},"p":{"a":0,"k":[162.224,379.579,0]},"a":{"a":0,"k":[-77.263,129.466,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[3.653,-0.657],[0,0],[0,0]],"o":[[0,0],[0,0],[-0.657,3.653]],"v":[[-75.677,138.237],[-75.677,131.052],[-68.492,131.052]],"c":true}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0.657,3.653],[0,0],[0,0]],"o":[[0,0],[0,0],[-3.653,-0.657]],"v":[[-86.035,131.052],[-78.85,131.052],[-78.85,138.237]],"c":true}},"nm":"Path 2","hd":false},{"ind":2,"ty":"sh","ks":{"a":0,"k":{"i":[[-3.653,0.657],[0,0],[0,0]],"o":[[0,0],[0,0],[0.657,-3.653]],"v":[[-78.85,120.694],[-78.85,127.879],[-86.035,127.879]],"c":true}},"nm":"Path 3","hd":false},{"ind":3,"ty":"sh","ks":{"a":0,"k":{"i":[[-0.657,-3.653],[0,0],[0,0]],"o":[[0,0],[0,0],[3.653,0.657]],"v":[[-68.492,127.879],[-75.677,127.879],[-75.677,120.694]],"c":true}},"nm":"Path 4","hd":false},{"ind":4,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[0.842,1.332],[0,0],[0,0],[0,0],[1.584,0.357],[0,0],[0,0],[0,0],[1.332,-0.842],[0,0],[0,0],[0,0],[0.357,-1.584],[0,0],[0,0],[0,0],[-0.842,-1.332],[0,0],[0,0],[0,0],[-1.584,-0.357],[0,0],[0,0],[0,0],[-1.332,0.842],[0,0],[0,0],[0,0],[-0.357,1.584]],"o":[[0,0],[0,0],[-0.357,-1.584],[0,0],[0,0],[0,0],[-1.332,-0.842],[0,0],[0,0],[0,0],[-1.584,0.357],[0,0],[0,0],[0,0],[-0.842,1.332],[0,0],[0,0],[0,0],[0.357,1.584],[0,0],[0,0],[0,0],[1.332,0.842],[0,0],[0,0],[0,0],[1.584,-0.357],[0,0],[0,0],[0,0],[0.842,-1.332],[0,0]],"v":[[-58.556,131.571],[-58.556,127.36],[-63.54,126.358],[-65.365,121.963],[-62.547,117.726],[-65.524,114.749],[-69.761,117.567],[-74.156,115.743],[-75.158,110.758],[-79.369,110.758],[-80.371,115.742],[-84.766,117.567],[-89.003,114.749],[-91.98,117.726],[-89.162,121.963],[-90.986,126.358],[-95.971,127.36],[-95.971,131.571],[-90.986,132.573],[-89.162,136.968],[-91.98,141.205],[-89.003,144.182],[-84.766,141.364],[-80.371,143.189],[-79.369,148.173],[-75.158,148.173],[-74.156,143.189],[-69.761,141.364],[-65.524,144.182],[-62.547,141.205],[-65.365,136.968],[-63.54,132.573]],"c":true}},"nm":"Path 5","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":6,"ty":4,"nm":"Layer 13","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[-540]}]},"p":{"a":0,"k":[187.735,418.888,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0],[0,0],[1.07,1.693],[0,0],[0,0],[0,0],[2.013,0.454],[0,0],[0,0],[0,0],[1.693,-1.07],[0,0],[0,0],[0,0],[0.454,-2.013],[0,0],[0,0],[0,0],[-1.07,-1.693],[0,0],[0,0],[0,0],[-2.013,-0.454],[0,0],[0,0],[0,0],[-1.693,1.07],[0,0],[0,0],[0,0],[-0.454,2.013]],"o":[[0,0],[0,0],[-0.454,-2.013],[0,0],[0,0],[0,0],[-1.693,-1.07],[0,0],[0,0],[0,0],[-2.013,0.454],[0,0],[0,0],[0,0],[-1.07,1.693],[0,0],[0,0],[0,0],[0.454,2.013],[0,0],[0,0],[0,0],[1.693,1.07],[0,0],[0,0],[0,0],[2.013,-0.454],[0,0],[0,0],[0,0],[1.07,-1.693],[0,0]],"v":[[23.78,2.676],[23.78,-2.676],[17.444,-3.95],[15.125,-9.537],[18.707,-14.923],[14.923,-18.707],[9.537,-15.125],[3.95,-17.444],[2.676,-23.78],[-2.676,-23.78],[-3.95,-17.444],[-9.537,-15.125],[-14.923,-18.707],[-18.707,-14.923],[-15.125,-9.537],[-17.444,-3.95],[-23.78,-2.676],[-23.78,2.676],[-17.444,3.95],[-15.125,9.537],[-18.707,14.923],[-14.923,18.707],[-9.537,15.125],[-3.95,17.444],[-2.676,23.78],[2.676,23.78],[3.95,17.444],[9.537,15.125],[14.923,18.707],[18.707,14.923],[15.125,9.537],[17.444,3.95]],"c":true}},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":7,"ty":4,"nm":"Layer 14","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[360]}]},"p":{"a":0,"k":[360.38,357.13,0]},"a":{"a":0,"k":[87.867,110.758,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[4.853,0],[0,4.853],[-4.853,0],[0,-4.853]],"o":[[-4.853,0],[0,-4.853],[4.853,0],[0,4.853]],"v":[[87.867,119.559],[79.066,110.758],[87.867,101.957],[96.668,110.758]],"c":true}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0.355,1.008],[0,0],[1.194,1.604],[0,0],[0.814,0.701],[0,0],[1.857,0.804],[0,0],[1.07,0.201],[0,0],[1.018,0],[0.988,-0.113],[0,0],[1.008,-0.355],[0,0],[1.604,-1.194],[0,0],[0.701,-0.814],[0,0],[0.804,-1.857],[0,0],[0.201,-1.07],[0,0],[0,-1.018],[-0.113,-0.988],[0,0],[-0.355,-1.008],[0,0],[-1.194,-1.604],[0,0],[-0.814,-0.701],[0,0],[-1.857,-0.804],[0,0],[-1.07,-0.201],[0,0],[-1.018,0],[-0.988,0.113],[0,0],[-1.008,0.355],[0,0],[-1.604,1.194],[0,0],[-0.701,0.814],[0,0],[-0.804,1.857],[0,0],[-0.201,1.07],[0,0],[0,1.018],[0.113,0.988],[0,0]],"o":[[0,0],[-0.804,-1.857],[0,0],[-0.701,-0.814],[0,0],[-1.604,-1.194],[0,0],[-1.008,-0.355],[0,0],[-0.988,-0.113],[-1.018,0],[0,0],[-1.07,0.201],[0,0],[-1.857,0.804],[0,0],[-0.814,0.701],[0,0],[-1.194,1.604],[0,0],[-0.355,1.008],[0,0],[-0.113,0.988],[0,1.018],[0,0],[0.201,1.07],[0,0],[0.804,1.857],[0,0],[0.701,0.814],[0,0],[1.604,1.194],[0,0],[1.008,0.355],[0,0],[0.988,0.113],[1.018,0],[0,0],[1.07,-0.201],[0,0],[1.857,-0.804],[0,0],[0.814,-0.701],[0,0],[1.194,-1.604],[0,0],[0.355,-1.008],[0,0],[0.113,-0.988],[0,-1.018],[0,0],[-0.201,-1.07]],"v":[[108.086,103.668],[111.839,100.391],[108.83,95.183],[104.105,96.797],[101.828,94.521],[103.443,89.796],[98.235,86.786],[94.957,90.54],[91.836,89.703],[90.876,84.82],[87.867,84.643],[84.859,84.82],[83.898,89.703],[80.777,90.54],[77.499,86.786],[72.292,89.796],[73.906,94.521],[71.63,96.798],[66.904,95.183],[63.895,100.391],[67.648,103.668],[66.812,106.789],[61.929,107.75],[61.752,110.758],[61.93,113.767],[66.812,114.728],[67.649,117.848],[63.896,121.126],[66.905,126.334],[71.63,124.719],[73.906,126.995],[72.292,131.721],[77.499,134.73],[80.777,130.977],[83.898,131.813],[84.859,136.696],[87.867,136.874],[90.876,136.696],[91.837,131.813],[94.957,130.977],[98.235,134.73],[103.443,131.721],[101.828,126.995],[104.104,124.719],[108.83,126.334],[111.839,121.126],[108.086,117.848],[108.922,114.728],[113.805,113.767],[113.983,110.758],[113.805,107.75],[108.922,106.789]],"c":true}},"nm":"Path 2","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":8,"ty":4,"nm":"Layer 15","sr":1,"ks":{"p":{"a":0,"k":[300.082,377.416,0]},"s":{"a":0,"k":[120,120,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[11.95,26.657],[28.23,-6.057],[0,0],[0,0],[0,0],[2.809,-9.793],[-15.255,-4.376],[-5.263,1.714],[-0.001,0]],"o":[[-9.358,-20.877],[-0.01,0.002],[0,0],[0,0],[-9.092,2.7],[-4.376,15.255],[5.721,1.641],[0.001,0],[28.622,-10.637]],"v":[[67.841,-25.078],[7.174,-30.525],[-49.557,-18.353],[-49.602,-18.343],[-49.601,-18.34],[-69.069,1.286],[-49.371,36.832],[-32.574,36.545],[15.083,19.692]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":6},"lc":2,"lj":2,"bm":0,"d":[{"n":"d","nm":"dash","v":{"a":0,"k":10}},{"n":"g","nm":"gap","v":{"a":0,"k":10}},{"n":"o","nm":"offset","v":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":0,"s":[0]},{"t":180,"s":[220]}]}}],"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":9,"ty":4,"nm":"beak_bl 2","parent":10,"sr":1,"ks":{"r":{"a":0,"k":19.264},"p":{"a":0,"k":[-47.668,-13.644,0]},"a":{"a":0,"k":[24.706,21.598,0]},"s":{"a":0,"k":[45.097,45.465,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[-14.352,8.65]],"o":[[-13.425,-9.565],[0,0]],"v":[[60.942,3.525],[63.885,-36.746]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,0.705882352941,0.517647058824,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[24.706,22.107]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[5]},{"t":132,"s":[0]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[100]},{"t":132,"s":[95]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":10,"ty":4,"nm":"Layer 16","sr":1,"ks":{"p":{"a":0,"k":[300.432,339.737,0]},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":40,"s":[120,120,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":45,"s":[144,144,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":50,"s":[114,114,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":55,"s":[144,144,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":60,"s":[114,114,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":65,"s":[120,120,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":90,"s":[120,120,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":95,"s":[144,144,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":100,"s":[114,114,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":105,"s":[144,144,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":110,"s":[114,114,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":115,"s":[120,120,100]},{"t":185,"s":[120,120,100]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[11.072,-22.144],[-9.048,-21.866],[-7.677,-5.399],[-3.484,7.708]],"o":[[-10.868,-21.737],[3.285,7.94],[11.023,-8.07],[9.956,-22.028]],"v":[[-0.006,-15.313],[-27.752,0.737],[-0.006,25.702],[27.427,1.457]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.811764705882,0.207843137255,0.007843137255,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":3},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[1,0.364705882353,0.121568627451,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.811764705882,0.207843137255,0.007843137255,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 2","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":11,"ty":4,"nm":"Shape Layer 3","sr":1,"ks":{"p":{"a":0,"k":[437.169,477.82,0]},"a":{"a":0,"k":[192.965,224.82,0]},"s":{"a":0,"k":[90,90,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,-11.046],[0,0],[11.046,0],[0,0],[0,11.046],[0,0],[-11.046,0],[0,0]],"o":[[0,0],[0,11.046],[0,0],[-11.046,0],[0,0],[0,-11.046],[0,0],[11.046,0]],"v":[[256.954,-92.201],[256.755,154.868],[236.755,174.868],[-236.755,174.868],[-256.755,154.868],[-256.556,-92.201],[-236.556,-112.201],[236.954,-112.201]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.836580882353,0.470464549345,0.083158268648,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[-8.434,65.508]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Rectangle 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":12,"ty":4,"nm":"Shape Layer 1","sr":1,"ks":{"p":{"a":0,"k":[437.169,480.82,0]},"a":{"a":0,"k":[192.965,224.82,0]},"s":{"a":0,"k":[90,90,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,-11.046],[0,0],[11.046,0],[0,0],[0,11.046],[0,0],[-11.046,0],[0,0]],"o":[[0,0],[0,11.046],[0,0],[-11.046,0],[0,0],[0,-11.046],[0,0],[11.046,0]],"v":[[256.954,-92.201],[256.755,154.868],[236.755,174.868],[-236.755,174.868],[-256.755,154.868],[-256.556,-92.201],[-236.556,-112.201],[236.954,-112.201]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.596078431373,0.164705882353,0.019607843137,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":25},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[-8.434,65.508]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Rectangle 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":13,"ty":4,"nm":"ruchka 2","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":35,"s":[-0.794]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":47,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"t":132,"s":[0]}]},"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[458.6,325.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":0.667},"o":{"x":0.333,"y":0.333},"t":47,"s":[453.6,295.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[453.6,295.865,0],"to":[0,0,0],"ti":[0,0,0]},{"t":132,"s":[453.6,325.865,0]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,15.214],[0,0],[0,-15.215],[0,0]],"o":[[0,0],[0,-15.197],[0,0],[0,15.197]],"v":[[-14.225,27.092],[-14.225,-27.091],[14.225,-27.091],[14.225,27.092]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":0},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":14,"ty":4,"nm":"Layer 20","sr":1,"ks":{"p":{"a":0,"k":[453.6,8,0]},"a":{"a":0,"k":[217.6,-248,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[222.7,32.6],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":47,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]},{"t":132,"s":[{"i":[[-22.8,15.6],[0,0]],"o":[[22.8,-15.6],[0,0]],"v":[[214.2,30.6],[217.6,-248]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"d":[{"n":"d","nm":"dash","v":{"a":0,"k":12}},{"n":"o","nm":"offset","v":{"a":0,"k":0}}],"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":0,"k":0},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":35,"s":[20]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":47,"s":[3]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[3]},{"t":132,"s":[20]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":15,"ty":4,"nm":"wing_r 6","parent":21,"sr":1,"ks":{"r":{"a":0,"k":2},"p":{"a":0,"k":[-116.688,-3.209,0]},"a":{"a":0,"k":[59.284,127.767,0]},"s":{"a":0,"k":[100.653,99.355,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.833,"y":1},"o":{"x":0.333,"y":0},"t":37,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]},{"i":{"x":0.833,"y":0.833},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]},{"t":129,"s":[{"i":[[25.211,-11.578],[4.349,-2.887],[-6.379,13.565],[-26.048,19.281]],"o":[[-22.723,10.5],[-7.432,4.933],[10.089,-21.453],[18.211,-13.472]],"v":[[59.284,130.356],[-0.227,155.976],[-7.423,145.006],[43.859,81.452]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":16,"ty":4,"nm":"Shape Layer 39","sr":1,"ks":{"p":{"a":0,"k":[256,256,0]}},"ao":0,"shapes":[],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":17,"ty":4,"nm":"head 4","parent":21,"sr":1,"ks":{"r":{"a":0,"k":-11},"p":{"a":0,"k":[14.858,-33.738,0]},"a":{"a":0,"k":[-5.057,138.647,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0.434,27.889]],"o":[[-18.548,-21.091],[-0.108,-6.931]],"v":[[-132.592,102.307],[-162.032,27.776]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":18,"ty":4,"nm":"head 3","parent":21,"sr":1,"ks":{"r":{"a":0,"k":-11},"p":{"a":0,"k":[14.858,-33.738,0]},"a":{"a":0,"k":[-5.057,138.647,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[2.138,-4.748],[21.073,-12.398]],"o":[[-9.905,22.001],[0,0]],"v":[[141.373,86.619],[93.976,138.647]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":19,"ty":4,"nm":"head 2","parent":21,"sr":1,"ks":{"r":{"a":0,"k":-11},"p":{"a":0,"k":[14.858,-33.738,0]},"a":{"a":0,"k":[-5.057,138.647,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[1.149,29.462],[3.208,-6.515],[19.05,-11.209]],"o":[[-16.295,-18.529],[-0.226,-5.802],[-10.362,21.047],[0,0]],"v":[[-132.592,102.308],[-161.398,26.642],[139.04,88.259],[93.976,138.647]],"c":false}},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":20,"ty":4,"nm":"wing_r 5","parent":21,"sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":35,"s":[27.383]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":47,"s":[0.592]},{"t":120,"s":[0.592]}]},"p":{"a":0,"k":[118.365,-52.77,0]},"a":{"a":0,"k":[138.929,91.115,0]},"s":{"a":0,"k":[100.653,99.355,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-29.986,14.167],[-7.027,10.015],[26.791,-12.882],[24.108,4.848]],"o":[[20.406,-9.641],[10.173,-14.501],[-27.193,13.075],[-24.605,-4.948]],"v":[[187.232,122.185],[217.447,93.048],[204.08,70.158],[128.203,80.053]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":47,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]},{"t":132,"s":[{"i":[[-32.922,-3.999],[-9.301,24.895],[23.051,-18.771],[12.562,14.245]],"o":[[31.524,3.829],[6.199,-16.593],[-23.051,18.771],[-16.6,-18.824]],"v":[[160.505,147.872],[214.633,105.998],[194.273,89.025],[139.759,74.805]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":21,"ty":4,"nm":"body 2","sr":1,"ks":{"p":{"a":0,"k":[255.802,466.133,0]},"a":{"a":0,"k":[-0.198,100.428,0]},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":35,"s":[110,106,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":42,"s":[108,108,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":120,"s":[108,108,100]},{"t":132,"s":[110,106,100]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[73.573,0],[-1.394,47.485],[-20.053,22.327],[-35.323,0],[-31.856,-39.22],[-2.032,-45.681]],"o":[[-73.2,0],[0.075,-46.215],[34.151,-38.025],[48.069,0],[17.909,22.049],[2.352,56.047]],"v":[[-0.228,100.1],[-159.499,43.717],[-125.687,-57.104],[-3.591,-104.294],[127.186,-56.843],[159.032,42.73]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843137255,0.498039215686,0.780392156863,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":36,"op":129,"st":0,"bm":0},{"ddd":0,"ind":22,"ty":4,"nm":"Shape Layer 38","parent":23,"sr":1,"ks":{"o":{"a":1,"k":[{"t":35,"s":[0],"h":1},{"t":36,"s":[100],"h":1},{"t":129,"s":[0],"h":1}]},"r":{"a":0,"k":90},"p":{"a":0,"k":[-6.667,0,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-3,-252],[-3,244]],"c":false}},"nm":"Path 7","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[37,-252],[37,244]],"c":false}},"nm":"Path 8","hd":false},{"ind":2,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[77,-252],[77,244]],"c":false}},"nm":"Path 9","hd":false},{"ind":3,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[117,-252],[117,244]],"c":false}},"nm":"Path 10","hd":false},{"ind":4,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[157,-252],[157,244]],"c":false}},"nm":"Path 11","hd":false},{"ind":5,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[197,-252],[197,244]],"c":false}},"nm":"Path 12","hd":false},{"ind":6,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[237,-241.474],[237,233.474]],"c":false}},"nm":"Path 13","hd":false},{"ty":"st","c":{"a":0,"k":[0.470588265213,0.662745098039,0.850980451995,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":5},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":23,"ty":4,"nm":"Shape Layer 37","sr":1,"ks":{"o":{"a":1,"k":[{"t":35,"s":[0],"h":1},{"t":36,"s":[100],"h":1},{"t":129,"s":[0],"h":1}]},"p":{"a":0,"k":[261,269,0]},"s":{"a":0,"k":[95,95,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-242.842,-25.684],[-243,244]],"c":false}},"nm":"Path 1","hd":false},{"ind":1,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-202.842,-35.158],[-203,244]],"c":false}},"nm":"Path 2","hd":false},{"ind":2,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-162.842,-35.158],[-163,244]],"c":false}},"nm":"Path 3","hd":false},{"ind":3,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-122.842,-35.158],[-123,244]],"c":false}},"nm":"Path 4","hd":false},{"ind":4,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-82.842,-35.158],[-83,244]],"c":false}},"nm":"Path 5","hd":false},{"ind":5,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-42.842,-35.158],[-43,244]],"c":false}},"nm":"Path 6","hd":false},{"ind":6,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[-2.842,-35.158],[-3,244]],"c":false}},"nm":"Path 7","hd":false},{"ind":7,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[37.158,-35.158],[37,244]],"c":false}},"nm":"Path 8","hd":false},{"ind":8,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[77.158,-35.158],[77,244]],"c":false}},"nm":"Path 9","hd":false},{"ind":9,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[117.158,-35.158],[117,244]],"c":false}},"nm":"Path 10","hd":false},{"ind":10,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[157.158,-35.158],[157,244]],"c":false}},"nm":"Path 11","hd":false},{"ind":11,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[197.158,-35.158],[197,244]],"c":false}},"nm":"Path 12","hd":false},{"ind":12,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[237.158,-25.684],[237,244]],"c":false}},"nm":"Path 13","hd":false},{"ty":"st","c":{"a":0,"k":[0.470588235294,0.662745098039,0.850980392157,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":5},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":24,"ty":4,"nm":"Shape Layer 36","parent":12,"sr":1,"ks":{"o":{"a":1,"k":[{"t":35,"s":[0],"h":1},{"t":36,"s":[100],"h":1},{"t":129,"s":[0],"h":1}]},"p":{"a":0,"k":[-8.434,65.508,0]},"a":{"a":0,"k":[-8.434,65.508,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,-11.046],[0,0],[11.046,0],[0,0],[0,11.046],[0,0],[-11.046,0],[0,0]],"o":[[0,0],[0,11.046],[0,0],[-11.046,0],[0,0],[0,-11.046],[0,0],[11.046,0]],"v":[[256.954,-92.201],[256.755,154.868],[236.755,174.868],[-236.755,174.868],[-256.755,154.868],[-256.556,-92.201],[-236.556,-112.201],[236.954,-112.201]],"c":true}},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.207843152214,0.498039245605,0.780392216701,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.596078431373,0.164705882353,0.019607843137,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":2},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 2","hd":false},{"ty":"tr","p":{"a":0,"k":[-8.434,65.508]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Rectangle 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":25,"ty":4,"nm":"Layer 10","parent":27,"sr":1,"ks":{"o":{"a":0,"k":33},"p":{"a":0,"k":[5.507,12.462,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,-15.129],[0,15.129]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":26,"ty":4,"nm":"Layer 9","parent":27,"sr":1,"ks":{"p":{"a":0,"k":[-4.921,-5.829,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,-22.48],[0,22.48]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":27,"ty":4,"nm":"ruchka","sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[10.389]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":25,"s":[-17.087]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":35,"s":[-0.794]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":47,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[0]},{"t":145,"s":[0]}]},"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[453.6,295.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[433.6,305.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[433.6,215.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[458.6,325.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":0.667},"o":{"x":0.333,"y":0.333},"t":47,"s":[453.6,295.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[453.6,295.865,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":132,"s":[453.6,325.865,0],"to":[0,0,0],"ti":[0,0,0]},{"t":145,"s":[453.6,295.865,0]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,15.214],[0,0],[0,-15.215],[0,0]],"o":[[0,0],[0,-15.197],[0,0],[0,15.197]],"v":[[-14.225,27.092],[-14.225,-27.091],[14.225,-27.091],[14.225,27.092]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.207843139768,0.207843139768,0.207843139768,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8.638},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.40000000596,0.40000000596,0.40000000596,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":28,"ty":4,"nm":"Layer 8","sr":1,"ks":{"p":{"a":0,"k":[453.6,8,0]},"a":{"a":0,"k":[217.6,-248,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[-27.507,6.877],[0,0]],"o":[[38.4,-9.6],[0,0]],"v":[[205.6,10.6],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[9.991,26.535],[14.6,169]],"o":[[-31.1,-82.6],[-14.6,-169]],"v":[[186.1,-77.4],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[222.7,32.6],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":47,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":132,"s":[{"i":[[-22.8,15.6],[0,0]],"o":[[22.8,-15.6],[0,0]],"v":[[214.2,30.6],[217.6,-248]],"c":false}]},{"t":145,"s":[{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[217.6,-0.4],[217.6,-248]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.207843139768,0.207843139768,0.207843139768,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"d":[{"n":"d","nm":"dash","v":{"a":0,"k":12}},{"n":"o","nm":"offset","v":{"a":0,"k":0}}],"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":29,"ty":4,"nm":"wing_r 4","parent":30,"sr":1,"ks":{"r":{"a":0,"k":-0.026},"p":{"a":0,"k":[33.892,137.629,0]},"a":{"a":0,"k":[33.889,137.604,0]},"s":{"a":0,"k":[100.003,99.997,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":14,"s":[{"i":[[-10.643,11.92],[-12.575,9.668]],"o":[[12.221,-13.688],[16.287,-12.522]],"v":[[15.039,151.613],[47.734,123.769]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":27,"s":[{"i":[[-15.957,0.858],[-15.515,-2.942]],"o":[[16.777,-0.903],[20.185,3.827]],"v":[[2.857,117.574],[52.613,119.923]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":37,"s":[{"i":[[-10.643,11.92],[-12.575,9.668]],"o":[[12.221,-13.688],[16.287,-12.522]],"v":[[15.039,151.613],[47.734,123.769]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[-10.643,11.92],[-12.575,9.668]],"o":[[12.221,-13.688],[16.287,-12.522]],"v":[[15.039,151.613],[47.734,123.769]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":129,"s":[{"i":[[-13.92,7.848],[-16.063,6.299]],"o":[[11.874,-6.695],[19.127,-7.5]],"v":[[11.664,136.687],[52.613,119.923]],"c":false}]},{"t":138,"s":[{"i":[[-10.643,11.92],[-12.575,9.668]],"o":[[12.221,-13.688],[16.287,-12.522]],"v":[[15.039,151.613],[47.734,123.769]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.988235294118,0.933333333333,0.129411764706,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":30,"ty":4,"nm":"wing_r 2","parent":46,"sr":1,"ks":{"r":{"a":0,"k":2},"p":{"a":0,"k":[-116.688,-3.209,0]},"a":{"a":0,"k":[59.284,127.767,0]},"s":{"a":0,"k":[100.653,99.355,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":14,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":27,"s":[{"i":[[28.418,-2.604],[5.557,-0.391],[-13.063,9.235],[-31.607,10.185]],"o":[[-25.283,2.317],[-9.496,0.668],[20.66,-14.606],[22.128,-7.131]],"v":[[59.284,130.356],[-18.178,127.801],[-19.083,113.828],[43.859,81.452]],"c":false}]},{"i":{"x":0.833,"y":1},"o":{"x":0.333,"y":0},"t":37,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]},{"i":{"x":0.833,"y":0.833},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.167,"y":0.167},"t":129,"s":[{"i":[[25.211,-11.578],[4.349,-2.887],[-6.379,13.565],[-26.048,19.281]],"o":[[-22.723,10.5],[-7.432,4.933],[10.089,-21.453],[18.211,-13.472]],"v":[[59.284,130.356],[-0.227,155.976],[-7.423,145.006],[43.859,81.452]],"c":false}]},{"t":138,"s":[{"i":[[23.631,-15.999],[3.754,-4.116],[-3.087,15.697],[-23.311,23.761]],"o":[[-21.462,14.53],[-6.415,7.034],[4.882,-24.826],[16.281,-16.596]],"v":[[59.284,130.356],[8.614,169.853],[-1.68,160.362],[43.859,81.452]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.980392156863,0.564705882353,0.086274509804,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.996078431373,0.847058823529,0.129411764706,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":31,"ty":4,"nm":"Shape Layer 35","sr":1,"ks":{"p":{"a":0,"k":[256,256,0]}},"ao":0,"shapes":[],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":32,"ty":4,"nm":"mouth","parent":34,"sr":1,"ks":{"p":{"a":0,"k":[0,14.621,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-17.269,-7.486],[-25.99,24.028]],"o":[[32.081,19.847],[14.782,-13.666]],"v":[[-56.183,-9.509],[70.976,-18.573]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[-17.269,-7.486],[-25.99,24.028]],"o":[[32.081,19.847],[14.782,-13.666]],"v":[[-56.183,-9.509],[70.976,-18.573]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[-17.269,-3.243],[-26.184,7.12]],"o":[[35.094,3.602],[15.365,-4.178]],"v":[[-55.944,-6.696],[70.976,-14.252]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-17.269,-7.486],[-25.99,24.028]],"o":[[32.081,19.847],[14.782,-13.666]],"v":[[-56.183,-9.509],[70.976,-18.573]],"c":false}]},{"t":42,"s":[{"i":[[-17.269,-7.486],[-25.99,24.028]],"o":[[32.081,19.847],[14.782,-13.666]],"v":[[-56.183,-9.509],[70.976,-18.573]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.490196078431,0.035294117647,0.035294117647,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":7.2},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":33,"ty":4,"nm":"beak_bl","parent":34,"sr":1,"ks":{"r":{"a":0,"k":11.894},"p":{"a":0,"k":[16.33,2.196,0]},"a":{"a":0,"k":[24.706,21.598,0]},"s":{"a":0,"k":[108.675,108.675,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[0,0],[5.957,9.194]],"o":[[-10.87,1.332],[0,0]],"v":[[22.269,-13.558],[-5.23,-27.348]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[0,0],[5.957,9.194]],"o":[[-10.87,1.332],[0,0]],"v":[[22.269,-13.558],[-6.027,-29.834]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[0,0],[5.957,9.194]],"o":[[-10.87,1.332],[0,0]],"v":[[21.317,-17.631],[-6.027,-29.834]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[0,0],[5.957,9.194]],"o":[[-10.87,1.332],[0,0]],"v":[[22.269,-13.558],[-6.027,-29.834]],"c":false}]},{"t":42,"s":[{"i":[[0,0],[5.957,9.194]],"o":[[-10.87,1.332],[0,0]],"v":[[22.269,-13.558],[-5.23,-27.348]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,0.705882352941,0.517647058824,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[24.706,22.107]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":168,"s":[5]},{"t":180,"s":[0]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":168,"s":[100]},{"t":180,"s":[95]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":0,"op":220,"st":0,"bm":0},{"ddd":0,"ind":34,"ty":4,"nm":"beak","parent":41,"sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":65,"s":[12.936]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":75,"s":[22.936]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":85,"s":[22.936]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":95,"s":[2.936]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":105,"s":[2.936]},{"t":115,"s":[12.936]}]},"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[1.885,0.316,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[-1.715,18.837,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[6.958,-25.782,0],"to":[0,0,0],"ti":[0,0,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[-0.242,11.26,0],"to":[0,0,0],"ti":[0,0,0]},{"t":42,"s":[1.885,0.316,0]}]},"a":{"a":0,"k":[7.715,-4.465,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-23.707,16.925],[4.433,6.816],[11.14,-1.166],[25.457,0],[33.695,2.564],[1.014,-5.86],[-8.647,-4.607]],"o":[[18.173,-12.974],[-2.919,-4.488],[-35.752,3.742],[-25.457,0],[-16.014,-1.219],[-0.912,5.267],[34.066,18.127]],"v":[[69.026,14.253],[85.547,-12.349],[65.493,-15.496],[5.821,-42.893],[-49.252,-6.247],[-71.579,3.027],[-57.963,21.054]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[-23.707,16.925],[4.433,6.816],[11.14,-1.166],[25.457,0],[33.695,2.564],[1.014,-5.86],[-8.647,-4.607]],"o":[[18.173,-12.974],[-2.919,-4.488],[-35.752,3.742],[-25.457,0],[-16.014,-1.219],[-0.912,5.267],[34.066,18.127]],"v":[[69.026,14.253],[85.547,-12.349],[65.493,-15.496],[5.706,-50.912],[-49.252,-6.247],[-71.579,3.027],[-57.963,21.054]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[-28.388,8.094],[2.456,7.751],[11.048,1.845],[25.457,0],[33.185,-6.376],[-0.561,-5.92],[-9.694,-1.423]],"o":[[21.474,-6.122],[-1.617,-5.104],[-35.457,-5.92],[-25.457,0],[-15.772,3.03],[0.504,5.322],[30.29,4.445]],"v":[[66.808,16.439],[89.82,-4.799],[71.329,-13.176],[6.005,-40.462],[-54.875,-4.097],[-73.982,10.715],[-56.109,24.532]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-23.707,16.925],[4.433,6.816],[11.14,-1.166],[25.457,0],[33.695,2.564],[1.014,-5.86],[-8.647,-4.607]],"o":[[18.173,-12.974],[-2.919,-4.488],[-35.752,3.742],[-25.457,0],[-16.014,-1.219],[-0.912,5.267],[34.066,18.127]],"v":[[69.026,14.253],[85.547,-12.349],[65.493,-15.496],[5.706,-50.912],[-49.252,-6.247],[-71.579,3.027],[-57.963,21.054]],"c":true}]},{"t":42,"s":[{"i":[[-23.707,16.925],[4.433,6.816],[11.14,-1.166],[25.457,0],[33.695,2.564],[1.014,-5.86],[-8.647,-4.607]],"o":[[18.173,-12.974],[-2.919,-4.488],[-35.752,3.742],[-25.457,0],[-16.014,-1.219],[-0.912,5.267],[34.066,18.127]],"v":[[69.026,14.253],[85.547,-12.349],[65.493,-15.496],[5.821,-42.893],[-49.252,-6.247],[-71.579,3.027],[-57.963,21.054]],"c":true}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.811764705882,0.207843137255,0.007843137255,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[1,0.364705882353,0.121568627451,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":35,"ty":4,"nm":"eye_lbl 2","parent":36,"sr":1,"ks":{"p":{"a":0,"k":[150.541,-124.606,0]},"s":{"a":0,"k":[80,80,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":5,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":10,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":30,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":40,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":45,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":50,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":90,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":95,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"t":100,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]}]},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":1,"k":[{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":0,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":5,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":10,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":30,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":35,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":40,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":45,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":50,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":90,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":95,"s":[0,0,0,1]},{"t":100,"s":[1,1,1,1]}]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":36,"ty":4,"nm":"eye_l 2","parent":34,"sr":1,"ks":{"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[77.966,-48.739,0],"to":[-0.027,-0.786,0],"ti":[0.001,0.029,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[77.806,-53.453,0],"to":[-0.001,-0.029,0],"ti":[-0.051,-1.514,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[77.96,-48.911,0],"to":[0.051,1.514,0],"ti":[-0.001,-0.029,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[78.113,-44.368,0],"to":[0.001,0.029,0],"ti":[0.025,0.729,0]},{"t":42,"s":[77.966,-48.739,0]}]},"a":{"a":0,"k":[145.426,-113.831,0]},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":0,"s":[119.983,100,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":12,"s":[119.983,120,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":25,"s":[119.983,90,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":35,"s":[119.983,100,100]},{"t":42,"s":[119.983,100,100]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":5,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":10,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":30,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":35,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":40,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":45,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.333,"y":0},"t":50,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":90,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":95,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"t":100,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]}]},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0.079},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1]},"o":{"a":0,"k":100},"w":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":5,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":10,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":30,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":35,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":40,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":45,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":50,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":90,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":95,"s":[5]},{"t":100,"s":[0]}]},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":37,"ty":4,"nm":"eye_lbl","parent":38,"sr":1,"ks":{"p":{"a":0,"k":[150.541,-124.606,0]},"s":{"a":0,"k":[80,80,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":5,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":10,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":30,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":40,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":45,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":50,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":90,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":95,"s":[{"i":[[-4.728,0.12],[0.138,2.914],[4.728,-0.12],[-0.138,-2.914]],"o":[[4.728,-0.12],[-0.138,-2.914],[-4.728,0.12],[0.138,2.914]],"v":[[-5.633,16.107],[2.677,10.613],[-6.133,5.555],[-14.443,11.049]],"c":true}]},{"t":100,"s":[{"i":[[-4.728,0.164],[0.138,3.974],[4.728,-0.164],[-0.138,-3.974]],"o":[[4.728,-0.164],[-0.138,-3.974],[-4.728,0.164],[0.138,3.974]],"v":[[-5.177,35.209],[3.133,27.717],[-5.677,20.818],[-13.987,28.311]],"c":true}]}]},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":1,"k":[{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":0,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":5,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":10,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":30,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":35,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":40,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":45,"s":[0,0,0,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":50,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":90,"s":[1,1,1,1]},{"i":{"x":[0],"y":[1]},"o":{"x":[1],"y":[0]},"t":95,"s":[0,0,0,1]},{"t":100,"s":[1,1,1,1]}]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":38,"ty":4,"nm":"eye_l","parent":34,"sr":1,"ks":{"p":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[-66.498,-39.558,0],"to":[-0.027,-0.786,0],"ti":[0.001,0.029,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[-66.658,-44.272,0],"to":[-0.001,-0.029,0],"ti":[-0.051,-1.514,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[-66.504,-39.729,0],"to":[0.051,1.514,0],"ti":[-0.001,-0.029,0]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[-66.351,-35.186,0],"to":[0.001,0.029,0],"ti":[0.025,0.729,0]},{"t":42,"s":[-66.498,-39.558,0]}]},"a":{"a":0,"k":[145.426,-113.831,0]},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":0,"s":[119.983,100,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":12,"s":[119.983,120,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":25,"s":[119.983,90,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":35,"s":[119.983,100,100]},{"t":42,"s":[119.983,100,100]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":0,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":5,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":10,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":30,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":35,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":40,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":45,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.333,"y":0},"t":50,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":90,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]},{"i":{"x":0.833,"y":1},"o":{"x":0.167,"y":0},"t":95,"s":[{"i":[[-10.684,0.233],[-2.632,-3.499],[1.122,-1.344],[1.795,0.991],[8.586,-0.126],[3.107,-1.473],[1.229,1.942],[-2.232,1.987]],"o":[[10.413,-0.228],[1.675,2.227],[-1.146,1.373],[-3.063,-1.691],[-9.061,0.133],[-1.953,0.926],[-1.285,-2.03],[3.295,-2.934]],"v":[[145.928,-119.439],[165.64,-112.673],[165.96,-107.395],[161.144,-107.302],[145.069,-112.13],[128.64,-106.742],[123.491,-107.302],[125.065,-113.381]],"c":true}]},{"t":100,"s":[{"i":[[-8.853,0],[-2.952,-9.049],[0,-3.067],[0.83,-2.631],[8.768,0],[3.175,8.471],[0,3.485],[-0.777,2.556]],"o":[[8.689,0],[0.881,2.699],[0,2.973],[-2.896,9.18],[-8.336,0],[-1.122,-2.993],[0,-2.873],[2.834,-9.32]],"v":[[145.426,-138],[164.488,-122.531],[165.852,-113.831],[164.568,-105.379],[145.426,-89.662],[126.745,-104.041],[125,-113.831],[126.201,-122.015]],"c":true}]}]},"nm":"Path 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1]},"o":{"a":0,"k":100},"w":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":5,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":10,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":30,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":35,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":40,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":45,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":50,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":90,"s":[0]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":95,"s":[5]},{"t":100,"s":[0]}]},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":39,"ty":4,"nm":"body_bl6","parent":41,"sr":1,"ks":{"r":{"a":0,"k":-107.887},"p":{"a":0,"k":[-109.48,-48.459,0]},"a":{"a":0,"k":[-43.496,-46.01,0]},"s":{"a":0,"k":[107.905,99.334,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[21.961,21.23]],"o":[[-2.122,-29.935],[-8.989,-8.69]],"v":[[-56.865,-39.585],[-94.624,-121.32]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.988235294118,0.933333333333,0.129411764706,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[35.688,48.14]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[0]},{"t":180,"s":[5]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[100]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[95]},{"t":180,"s":[100]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":0,"op":224,"st":0,"bm":0},{"ddd":0,"ind":40,"ty":4,"nm":"body_bl5","parent":41,"sr":1,"ks":{"r":{"a":0,"k":-15.313},"p":{"a":0,"k":[76.139,-70.072,0]},"a":{"a":0,"k":[-43.496,-46.01,0]},"s":{"a":0,"k":[107.905,99.334,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[39.737,16.789]],"o":[[-2.99,-42.189],[-16.834,-11.985]],"v":[[-56.865,-39.585],[-125.533,-142.012]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[35.688,48.14]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[0]},{"t":180,"s":[5]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[100]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[95]},{"t":180,"s":[100]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":0,"op":224,"st":0,"bm":0},{"ddd":0,"ind":41,"ty":4,"nm":"head","parent":46,"sr":1,"ks":{"r":{"a":0,"k":-11},"p":{"a":0,"k":[14.858,-33.738,0]},"a":{"a":0,"k":[-5.057,138.647,0]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[-5.826,36.108],[-85.805,-13.845],[12.377,-76.706],[29.903,-17.594]],"o":[[-23.158,-26.333],[12.377,-76.706],[85.804,13.845],[-5.842,36.205],[0,0]],"v":[[-132.592,102.307],[-160.469,6.583],[19.454,-120.563],[150.255,56.72],[93.976,138.647]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.980392156863,0.564705882353,0.086274509804,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.996078431373,0.847058823529,0.129411764706,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":42,"ty":4,"nm":"body_bl4","parent":46,"sr":1,"ks":{"r":{"a":0,"k":11.886},"p":{"a":0,"k":[-113.737,73.171,0]},"a":{"a":0,"k":[-267.897,75.232,0]},"s":{"a":0,"k":[107.905,99.334,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[13.538,-0.462],[7.459,5.031]],"o":[[-19.898,0.68],[-12.973,-10.431]],"v":[[-282.9,28.674],[-322.188,20.816]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.988235294118,0.933333333333,0.129411764706,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[35.688,48.14]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[0]},{"t":180,"s":[5]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[100]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[95]},{"t":180,"s":[100]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":0,"op":224,"st":0,"bm":0},{"ddd":0,"ind":43,"ty":4,"nm":"body_bl2","parent":46,"sr":1,"ks":{"r":{"a":0,"k":11.886},"p":{"a":0,"k":[131.646,2.641,0]},"a":{"a":0,"k":[-48.097,-45.336,0]},"s":{"a":0,"k":[107.905,99.334,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[0,0],[7.001,17.02]],"o":[[29.925,-11.609],[-16.834,-11.985]],"v":[[-101.861,-7.776],[-67.194,-63.781]],"c":false}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":8},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[35.688,48.14]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[5]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[0]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[5]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[0]},{"t":180,"s":[5]}]},"e":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":12,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":24,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":36,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":48,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":60,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":72,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":84,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":96,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":108,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":132,"s":[100]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":144,"s":[95]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":156,"s":[100]},{"i":{"x":[0.833],"y":[1]},"o":{"x":[0.167],"y":[0]},"t":168,"s":[95]},{"t":180,"s":[100]}]},"o":{"a":0,"k":0},"m":1,"nm":"Trim Paths 1","hd":false}],"ip":0,"op":224,"st":0,"bm":0},{"ddd":0,"ind":44,"ty":4,"nm":"wing_r 3","parent":45,"sr":1,"ks":{"r":{"a":0,"k":0.013},"p":{"a":0,"k":[185.758,92.671,0]},"a":{"a":0,"k":[185.75,92.65,0]},"s":{"a":0,"k":[100.001,99.999,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.167,"y":0},"t":0,"s":[{"i":[[12.769,-28.604],[10.233,-5.246]],"o":[[-8.678,19.442],[-22.709,11.642]],"v":[[205.793,81.124],[169.521,117.182]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[8.414,-30.174],[15.852,-1.942]],"o":[[-5.904,21.173],[-25.33,3.104]],"v":[[196.436,91.675],[166.535,130.614]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[8.414,-30.174],[10.516,-9.26]],"o":[[-5.904,21.173],[-19.152,16.865]],"v":[[198.446,66.032],[158.534,124.963]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[24.247,-19.832],[10.497,-4.443]],"o":[[-10.985,8.984],[-23.501,9.948]],"v":[[208.11,91.939],[178.64,110.631]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":47,"s":[{"i":[[8.414,-30.174],[8.88,-7.572]],"o":[[-5.904,21.173],[-19.419,16.557]],"v":[[201.978,68.117],[169.521,117.182]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[8.414,-30.174],[8.88,-7.572]],"o":[[-5.904,21.173],[-19.419,16.557]],"v":[[201.978,68.117],[169.521,117.182]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":132,"s":[{"i":[[8.414,-30.174],[15.852,-1.942]],"o":[[-5.904,21.173],[-25.33,3.104]],"v":[[204.222,102.037],[166.535,130.614]],"c":false}]},{"t":145,"s":[{"i":[[12.769,-28.604],[10.233,-5.246]],"o":[[-8.678,19.442],[-22.709,11.642]],"v":[[205.793,81.124],[169.521,117.182]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":45,"ty":4,"nm":"wing_r","parent":46,"sr":1,"ks":{"r":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[0.592]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":25,"s":[-26.911]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":35,"s":[27.383]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":47,"s":[0.592]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":120,"s":[0.592]},{"t":145,"s":[0.592]}]},"p":{"a":0,"k":[118.365,-52.77,0]},"a":{"a":0,"k":[138.929,91.115,0]},"s":{"a":0,"k":[100.653,99.355,100]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":1,"k":[{"i":{"x":0.667,"y":1},"o":{"x":0.167,"y":0},"t":0,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":12,"s":[{"i":[[-32.9,-4.174],[-3.254,26.376],[18.051,-23.619],[12.562,14.245]],"o":[[44.545,5.651],[2.169,-17.58],[-18.051,23.619],[-16.6,-18.824]],"v":[[153.731,147.943],[204.093,90.17],[180.343,78.399],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":25,"s":[{"i":[[-32.04,8.56],[-9.301,24.895],[23.051,-18.771],[15.792,-5.274]],"o":[[38.575,-10.305],[6.199,-16.593],[-23.051,18.771],[-23.805,7.951]],"v":[[139.77,150.718],[213.854,66.846],[193.494,49.872],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":35,"s":[{"i":[[-29.986,14.167],[-7.027,10.015],[26.791,-12.882],[24.108,4.848]],"o":[[20.406,-9.641],[10.173,-14.501],[-27.193,13.075],[-24.605,-4.948]],"v":[[187.232,122.185],[217.447,93.048],[204.08,70.158],[128.203,80.053]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":47,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":120,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]},{"i":{"x":0.667,"y":1},"o":{"x":0.333,"y":0},"t":132,"s":[{"i":[[-32.922,-3.999],[-9.301,24.895],[23.051,-18.771],[12.562,14.245]],"o":[[31.524,3.829],[6.199,-16.593],[-23.051,18.771],[-16.6,-18.824]],"v":[[160.505,147.872],[214.633,105.998],[194.273,89.025],[139.759,74.805]],"c":false}]},{"t":145,"s":[{"i":[[-29.138,15.837],[-9.301,24.895],[24.878,-16.272],[11.554,0.968]],"o":[[29.438,-16],[6.199,-16.593],[-20.214,13.221],[-25.01,-2.096]],"v":[[160.045,140.108],[216.827,87.784],[196.467,70.811],[138.929,81.935]],"c":false}]}]},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.980392156863,0.564705882353,0.086274509804,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.996078431373,0.847058823529,0.129411764706,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Shape 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0},{"ddd":0,"ind":46,"ty":4,"nm":"body","sr":1,"ks":{"p":{"a":0,"k":[255.802,466.133,0]},"a":{"a":0,"k":[-0.198,100.428,0]},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":0,"s":[108,108,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":12,"s":[110,106,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":25,"s":[108,110,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":35,"s":[110,106,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":42,"s":[108,108,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":120,"s":[108,108,100]},{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":132,"s":[110,106,100]},{"t":145,"s":[108,108,100]}]}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ks":{"a":0,"k":{"i":[[73.573,0],[-1.394,47.485],[-20.053,22.327],[-35.323,0],[-31.856,-39.22],[-2.032,-45.681]],"o":[[-73.2,0],[0.075,-46.215],[34.151,-38.025],[48.069,0],[17.909,22.049],[2.352,56.047]],"v":[[-0.228,100.1],[-159.499,43.717],[-125.687,-57.104],[-3.591,-104.294],[127.186,-56.843],[159.032,42.73]],"c":true}},"nm":"Path 1","hd":false},{"ty":"st","c":{"a":0,"k":[0.980392156863,0.564705882353,0.086274509804,1]},"o":{"a":0,"k":100},"w":{"a":0,"k":10},"lc":2,"lj":2,"bm":0,"nm":"Stroke 1","hd":false},{"ty":"fl","c":{"a":0,"k":[0.996078431373,0.847058823529,0.129411764706,1]},"o":{"a":0,"k":100},"r":1,"bm":0,"nm":"Fill 1","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0]},"a":{"a":0,"k":[0,0]},"s":{"a":0,"k":[100,100]},"r":{"a":0,"k":0},"o":{"a":0,"k":100},"sk":{"a":0,"k":0},"sa":{"a":0,"k":0},"nm":"Transform"}],"nm":"Group 1","bm":0,"hd":false}],"ip":0,"op":180,"st":0,"bm":0}]} \ No newline at end of file diff --git a/TMessagesProj/src/main/res/raw/sun_outline.tgs b/TMessagesProj/src/main/res/raw/sun_outline.tgs new file mode 100644 index 000000000..48a7c6e8f --- /dev/null +++ b/TMessagesProj/src/main/res/raw/sun_outline.tgs @@ -0,0 +1 @@ +{"v":"5.6.5","fr":60,"ip":0,"op":36,"w":100,"h":100,"nm":"Sun Lottie 2","ddd":0,"assets":[{"id":"comp_0","layers":[{"ddd":0,"ind":2,"ty":4,"nm":"Path 25","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[68,102.75,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,-100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Path 24","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[33.625,68.5,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[-100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":90,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"Path 43","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":-15,"ix":10},"p":{"a":0,"k":[44.303,92.581,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[-100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":120,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":5,"ty":4,"nm":"Path 41","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":15,"ix":10},"p":{"a":0,"k":[92.437,92.956,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":120,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":6,"ty":4,"nm":"Path 18","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":15,"ix":10},"p":{"a":0,"k":[92.375,44.125,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,-100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":150,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":7,"ty":4,"nm":"Path 39","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":-15,"ix":10},"p":{"a":0,"k":[43.688,44.25,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[-100,-100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":150,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":8,"ty":4,"nm":"Path 15","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[100.625,68.5,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":90,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":13,"bm":0},{"ddd":0,"ind":9,"ty":4,"nm":"Path 14","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[68,34.5,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0,0]],"o":[[0,0],[0,0]],"v":[[0,2.5],[0,-2.5]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":2,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[30]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[30]},{"t":54,"s":[0]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[1]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[18]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[0]},{"t":54,"s":[1]}],"ix":2},"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":3,"s":[0]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":12,"s":[120]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":22,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":35,"s":[172]},{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":45,"s":[120]},{"t":54,"s":[0]}],"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":-5,"op":89,"st":6,"bm":0}]}],"layers":[{"ddd":0,"ind":1,"ty":0,"nm":"Sunny","refId":"comp_0","sr":1,"ks":{"o":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.167],"y":[0.167]},"t":14,"s":[0]},{"t":21,"s":[100]}],"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.316],"y":[1]},"o":{"x":[0.3],"y":[0]},"t":12,"s":[-50]},{"t":36,"s":[0]}],"ix":10},"p":{"a":0,"k":[50,50,0],"ix":2},"a":{"a":0,"k":[68,68,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.38,0.38,0.833],"y":[1,1,1]},"o":{"x":[0.215,0.215,0.167],"y":[0,0,0]},"t":12,"s":[110,110,100]},{"t":23,"s":[100,100,100]}],"ix":6}},"ao":0,"w":136,"h":136,"ip":14,"op":36,"st":13.5,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"Path","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.4],"y":[1]},"o":{"x":[0.3],"y":[0]},"t":0,"s":[0]},{"t":20,"s":[80]}],"ix":10},"p":{"a":0,"k":[53.448,53.382,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.667,0.667,0.667],"y":[1,1,1]},"o":{"x":[0.6,0.6,0.333],"y":[0,0,0]},"t":1,"s":[76.666,76.666,100]},{"i":{"x":[0.833,0.833,0.833],"y":[1,1,1]},"o":{"x":[0.333,0.333,0.333],"y":[0,0,0]},"t":18,"s":[71,71,100]},{"t":35,"s":[76,76,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":1,"k":[{"i":{"x":0.735,"y":1},"o":{"x":0.857,"y":0},"t":0,"s":[{"i":[[2.91,2.05],[0,-0.35],[4.26,-3.65],[1.74,0.68],[-0.19,-0.35],[-4.28,0],[0,5.33]],"o":[[-0.41,-0.29],[0,1.49],[-4.26,3.65],[-0.46,-0.18],[1.93,3.75],[5.2,0],[0,-3.49]],"v":[[4.526,-9.188],[3.736,-8.738],[0.696,1.182],[-9.534,2.962],[-10.154,3.662],[-0.854,9.292],[9.036,-0.678]],"c":true}]},{"t":18,"s":[{"i":[[1.88,1.32],[0.45,0.17],[2.33,-2.14],[-0.21,-0.94],[-0.12,-0.23],[-2.59,0],[0,3.44]],"o":[[-0.26,-0.19],[-1.68,-0.65],[-2.32,2.14],[0.09,0.44],[1.25,2.42],[3.36,0],[0,-1.93]],"v":[[2.586,-4.585],[1.186,-5.325],[-5.654,-3.965],[-7.484,2.185],[-6.974,3.615],[-0.964,7.245],[5.356,0.755]],"c":true}]}],"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":1.4,"ix":5},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0.25,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[447.223,436.847],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":36,"st":0,"bm":0},{"ddd":0,"ind":4,"ty":4,"nm":"Path 11","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[43.875,40.625,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.84,0.84,0.667],"y":[1,1,1]},"o":{"x":[0.607,0.607,0.333],"y":[0,0,0]},"t":1,"s":[100,100,100]},{"i":{"x":[0.514,0.514,0.833],"y":[1,1,1]},"o":{"x":[0.167,0.167,0.167],"y":[0,0,0]},"t":6,"s":[120,120,100]},{"t":13,"s":[0,0,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,-0.08],[0.08,0],[0,-0.67],[0.08,0],[0,0.08],[0.67,0],[0,0.08],[-0.08,0],[0,0.67],[-0.07,0],[0,-0.08],[-0.67,0]],"o":[[0,0.08],[-0.67,0],[0,0.08],[-0.07,0],[0,-0.67],[-0.08,0],[0,-0.08],[0.67,0],[0,-0.08],[0.08,0],[0,0.67],[0.08,0]],"v":[[1.5,0],[1.36,0.14],[0.14,1.36],[0,1.5],[-0.14,1.36],[-1.36,0.14],[-1.5,0],[-1.36,-0.14],[-0.14,-1.36],[0,-1.5],[0.14,-1.36],[1.36,-0.14]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":36,"st":-2,"bm":0},{"ddd":0,"ind":5,"ty":4,"nm":"Path 10","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[25.875,28.625,0],"ix":2},"a":{"a":0,"k":[0,0,0],"ix":1},"s":{"a":1,"k":[{"i":{"x":[0.84,0.84,0.667],"y":[1,1,1]},"o":{"x":[0.607,0.607,0.333],"y":[0,0,0]},"t":0,"s":[100,100,100]},{"i":{"x":[0.5,0.5,0.833],"y":[1,1,1]},"o":{"x":[0.167,0.167,0.167],"y":[0,0,0]},"t":5,"s":[120,120,100]},{"t":12,"s":[0,0,100]}],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,-0.1],[0.1,0],[0,-0.9],[0.1,0],[0,0.1],[0.9,0],[0,0.1],[-0.1,0],[0,0.9],[-0.1,0],[0,-0.1],[-0.9,0]],"o":[[0,0.1],[-0.9,0],[0,0.1],[-0.1,0],[0,-0.9],[-0.1,0],[0,-0.1],[0.9,0],[0,-0.1],[0.1,0],[0,0.9],[0.1,0]],"v":[[2,0],[1.82,0.18],[0.18,1.82],[0,2],[-0.18,1.82],[-1.82,0.18],[-2,0],[-1.82,-0.18],[-0.18,-1.82],[0,-2],[0.18,-1.82],[1.82,-0.18]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[1,1,1,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[400,400],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Path","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":36,"st":-2,"bm":0}],"markers":[]} \ No newline at end of file diff --git a/TMessagesProj/src/main/res/values/strings.xml b/TMessagesProj/src/main/res/values/strings.xml index d5ff58a68..ad0941e86 100644 --- a/TMessagesProj/src/main/res/values/strings.xml +++ b/TMessagesProj/src/main/res/values/strings.xml @@ -900,6 +900,10 @@ OPEN BOT sponsored What are sponsored\nmessages? + Unlike other apps, Telegram never uses your private data to target ads. You are seeing this message only because someone chose this public one-to-many channel as a space to promote their messages. This means that no user data is mined or analyzed to display ads, and every user viewing a channel on Telegram sees the same sponsored message. + Unlike other apps, Telegram doesn\'t track whether you tapped on a sponsored message and doesn\'t profile you based on your activity. We also prevent external links in sponsored messages to ensure that third parties can’t spy on our users. We believe that everyone has the right to privacy, and technological platforms should respect that. + Telegram offers free and unlimited service to hundreds of millions of users, which involves significant server and traffic costs. In order to remain independent and stay true to its values, Telegram developed a paid tool to promote messages with user privacy in mind. We welcome responsible advertisers at: + Ads should no longer be synonymous with abuse of user privacy. Let us redefine how a tech company should operate – together. Sponsored messages See https://telegram.org LEARN MORE @@ -3708,8 +3712,8 @@ Do you want to stop recording this live stream? Start recording Do you want to start recording this chat and save the result into an audio file?\n\nOther members will see that the chat is being recorded. - Do you want to start recording this chat and save the result into an video file?\n\nOther members will see that the chat is being recorded. - Do you want to start recording this live stream and save the result into an video file?\n\nOther members will see that the stream is being recorded. + Do you want to start recording this chat and save the result into a video file?\n\nOther members will see that the chat is being recorded. + Do you want to start recording this live stream and save the result into a video file?\n\nOther members will see that the stream is being recorded. Recording Title Audio saved to **Saved Messages**. Video saved to **Saved Messages**. @@ -3793,8 +3797,8 @@ Enabled Disabled Video is only available\nfor the first %1$s - The voice chat is over %1$s.\nNew participants only have access to the audio stream. - The live stream is over %1$s.\nNew participants only have access to the audio stream. + The video chat has over %1$s.\nNew participants must use the latest version of Telegram to view video. + The live stream is over %1$s.\nNew participants must use the latest version of Telegram to view video. AUDIO ONLY PORTRAIT VIDEO LANDSCAPE VIDEO @@ -4501,6 +4505,20 @@ %1$d Dialogs unpinned %1$d Dialogs unpinned %1$d Dialogs unpinned + + %1$d Seen + Seen + %1$d Seen + %1$d Seen + %1$d Seen + %1$d Seen + + %1$d Played + Played + %1$d Played + %1$d Played + %1$d Played + %1$d Played Group Channel @@ -4701,4 +4719,28 @@ Show caption Hide caption Tap here for forwarding options + Change colors + Select theme + Apply Theme + Reset Theme + No Theme + You changed the chat theme to %1$s + %1$s changed the chat theme to %2$s + %1$s disabled the chat theme + You disabled the chat theme + Save changes? + Do you want to apply the new theme for this chat? + Apply + Discard + Optimizing Telegram... + This may take a while, depending on the size of the database. Please keep the app open until the process is finished. + Sorry for the inconvenience. + Do No Set Theme + **oo** watching %1$s + %1$s is **oo** watching %2$s + Theme will be also applied for **%s**. + Theme will be also disabled for **%s**. + To protect privacy, views are only stored for **7 days** + If **%s** were viewing the chat now, they would also see this animation. + Tap here to view how **%s** will see this theme when using night mode.