Update to 8.0.1 (2428)

This commit is contained in:
xaxtix 2021-09-20 08:54:41 +03:00
parent 368822d20f
commit 42feed0f42
351 changed files with 22083 additions and 13428 deletions

View file

@ -299,7 +299,7 @@ android {
} }
} }
defaultConfig.versionCode = 2406 defaultConfig.versionCode = 2428
applicationVariants.all { variant -> applicationVariants.all { variant ->
variant.outputs.all { output -> variant.outputs.all { output ->
@ -318,7 +318,7 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 16 minSdkVersion 16
targetSdkVersion 29 targetSdkVersion 29
versionName "8.0.0" versionName "8.0.1"
vectorDrawables.generatedDensities = ['mdpi', 'hdpi', 'xhdpi', 'xxhdpi'] vectorDrawables.generatedDensities = ['mdpi', 'hdpi', 'xhdpi', 'xxhdpi']

View file

@ -1,11 +1,11 @@
cmake_minimum_required(VERSION 3.6.0) cmake_minimum_required(VERSION 3.6.0)
set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID") set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID -g")
set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1") set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1 -g")
set(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp") set(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_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}/libswscale.a,
${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavformat.a, ${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavformat.a,
${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavcodec.a, ${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavcodec.a,

View file

@ -190,7 +190,7 @@ jint getConnectionState(JNIEnv *env, jclass c, jint instanceNum) {
return ConnectionsManager::getInstance(instanceNum).getConnectionState(); 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); 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 *deviceModelStr = env->GetStringUTFChars(deviceModel, 0);
const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0); const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0);
const char *appVersionStr = env->GetStringUTFChars(appVersion, 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_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_setProxySettings", "(ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", (void *) setProxySettings},
{"native_getConnectionState", "(I)I", (void *) getConnectionState}, {"native_getConnectionState", "(I)I", (void *) getConnectionState},
{"native_setUserId", "(II)V", (void *) setUserId}, {"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;IIZZI)V", (void *) init}, {"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_setLangCode", "(ILjava/lang/String;)V", (void *) setLangCode},
{"native_setRegId", "(ILjava/lang/String;)V", (void *) setRegId}, {"native_setRegId", "(ILjava/lang/String;)V", (void *) setRegId},
{"native_setSystemLangCode", "(ILjava/lang/String;)V", (void *) setSystemLangCode}, {"native_setSystemLangCode", "(ILjava/lang/String;)V", (void *) setSystemLangCode},

View file

@ -366,10 +366,10 @@ void TL_restrictionReason::serializeToStream(NativeByteBuffer *stream) {
User *User::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error) { User *User::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error) {
User *result = nullptr; User *result = nullptr;
switch (constructor) { switch (constructor) {
case 0x200250ba: case 0xd3bc4b7a:
result = new TL_userEmpty(); result = new TL_userEmpty();
break; break;
case 0x938458c1: case 0x3ff6ecb0:
result = new TL_user(); result = new TL_user();
break; break;
default: 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) { 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) { void TL_userEmpty::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(id); stream->writeInt64(id);
} }
void TL_user::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { void TL_user::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
flags = stream->readInt32(&error); flags = stream->readInt32(&error);
id = stream->readInt32(&error); id = stream->readInt64(&error);
if ((flags & 1) != 0) { if ((flags & 1) != 0) {
access_hash = stream->readInt64(&error); 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) { void TL_user::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(flags); stream->writeInt32(flags);
stream->writeInt32(id); stream->writeInt64(id);
if ((flags & 1) != 0) { if ((flags & 1) != 0) {
stream->writeInt64(access_hash); stream->writeInt64(access_hash);
} }
@ -491,19 +491,19 @@ InputPeer *InputPeer::TLdeserialize(NativeByteBuffer *stream, uint32_t construct
case 0x7da07ec9: case 0x7da07ec9:
result = new TL_inputPeerSelf(); result = new TL_inputPeerSelf();
break; break;
case 0x7b8e7de6: case 0xdde8a54c:
result = new TL_inputPeerUser(); result = new TL_inputPeerUser();
break; break;
case 0x179be863: case 0x35a95cb9:
result = new TL_inputPeerChat(); result = new TL_inputPeerChat();
break; break;
case 0x17bae2e6: case 0xa87b0a1c:
result = new TL_inputPeerUserFromMessage(); result = new TL_inputPeerUserFromMessage();
break; break;
case 0x9c95f7bb: case 0xbd2a0840:
result = new TL_inputPeerChannelFromMessage(); result = new TL_inputPeerChannelFromMessage();
break; break;
case 0x20adaef8: case 0x27bcbbfc:
result = new TL_inputPeerChannel(); result = new TL_inputPeerChannel();
break; break;
case 0x7f3b18ea: case 0x7f3b18ea:
@ -523,59 +523,59 @@ void TL_inputPeerSelf::serializeToStream(NativeByteBuffer *stream) {
} }
void TL_inputPeerUser::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { 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); access_hash = stream->readInt64(&error);
} }
void TL_inputPeerUser::serializeToStream(NativeByteBuffer *stream) { void TL_inputPeerUser::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(user_id); stream->writeInt64(user_id);
stream->writeInt64(access_hash); stream->writeInt64(access_hash);
} }
void TL_inputPeerChat::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { 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) { void TL_inputPeerChat::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(chat_id); stream->writeInt64(chat_id);
} }
void TL_inputPeerUserFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { void TL_inputPeerUserFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error));
msg_id = stream->readInt32(&error); msg_id = stream->readInt32(&error);
user_id = stream->readInt32(&error); user_id = stream->readInt64(&error);
} }
void TL_inputPeerUserFromMessage::serializeToStream(NativeByteBuffer *stream) { void TL_inputPeerUserFromMessage::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
peer->serializeToStream(stream); peer->serializeToStream(stream);
stream->writeInt32(msg_id); stream->writeInt32(msg_id);
stream->writeInt32(user_id); stream->writeInt64(user_id);
} }
void TL_inputPeerChannelFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { void TL_inputPeerChannelFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error));
msg_id = stream->readInt32(&error); msg_id = stream->readInt32(&error);
channel_id = stream->readInt32(&error); channel_id = stream->readInt64(&error);
} }
void TL_inputPeerChannelFromMessage::serializeToStream(NativeByteBuffer *stream) { void TL_inputPeerChannelFromMessage::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
peer->serializeToStream(stream); peer->serializeToStream(stream);
stream->writeInt32(msg_id); stream->writeInt32(msg_id);
stream->writeInt32(channel_id); stream->writeInt64(channel_id);
} }
void TL_inputPeerChannel::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { 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); access_hash = stream->readInt64(&error);
} }
void TL_inputPeerChannel::serializeToStream(NativeByteBuffer *stream) { void TL_inputPeerChannel::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(channel_id); stream->writeInt64(channel_id);
stream->writeInt64(access_hash); stream->writeInt64(access_hash);
} }
@ -589,13 +589,13 @@ InputUser *InputUser::TLdeserialize(NativeByteBuffer *stream, uint32_t construct
case 0xf7c1b13f: case 0xf7c1b13f:
result = new TL_inputUserSelf(); result = new TL_inputUserSelf();
break; break;
case 0xd8292816: case 0xf21158c6:
result = new TL_inputUser(); result = new TL_inputUser();
break; break;
case 0xb98886cf: case 0xb98886cf:
result = new TL_inputUserEmpty(); result = new TL_inputUserEmpty();
break; break;
case 0x2d117597: case 0x1da448e2:
result = new TL_inputUserFromMessage(); result = new TL_inputUserFromMessage();
break; break;
default: default:
@ -612,13 +612,13 @@ void TL_inputUserSelf::serializeToStream(NativeByteBuffer *stream) {
} }
void TL_inputUser::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { 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); access_hash = stream->readInt64(&error);
} }
void TL_inputUser::serializeToStream(NativeByteBuffer *stream) { void TL_inputUser::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(user_id); stream->writeInt64(user_id);
stream->writeInt64(access_hash); 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) { void TL_inputUserFromMessage::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error)); peer = std::unique_ptr<InputPeer>(InputPeer::TLdeserialize(stream, stream->readUint32(&error), instanceNum, error));
msg_id = stream->readInt32(&error); msg_id = stream->readInt32(&error);
user_id = stream->readInt32(&error); user_id = stream->readInt64(&error);
} }
void TL_inputUserFromMessage::serializeToStream(NativeByteBuffer *stream) { void TL_inputUserFromMessage::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
peer->serializeToStream(stream); peer->serializeToStream(stream);
stream->writeInt32(msg_id); 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) { 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: case 0xfa04579d:
result = new TL_messageEntityMention(); result = new TL_messageEntityMention();
break; break;
case 0x352dca58: case 0xdc7b1140:
result = new TL_messageEntityMentionName(); result = new TL_messageEntityMentionName();
break; break;
case 0x208e68c9: case 0x208e68c9:
@ -800,14 +800,14 @@ void TL_messageEntityMention::serializeToStream(NativeByteBuffer *stream) {
void TL_messageEntityMentionName::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { void TL_messageEntityMentionName::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
offset = stream->readInt32(&error); offset = stream->readInt32(&error);
length = stream->readInt32(&error); length = stream->readInt32(&error);
user_id = stream->readInt32(&error); user_id = stream->readInt64(&error);
} }
void TL_messageEntityMentionName::serializeToStream(NativeByteBuffer *stream) { void TL_messageEntityMentionName::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(offset); stream->writeInt32(offset);
stream->writeInt32(length); stream->writeInt32(length);
stream->writeInt32(user_id); stream->writeInt64(user_id);
} }
void TL_inputMessageEntityMentionName::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) { 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) { void TL_auth_exportedAuthorization::readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error) {
id = stream->readInt32(&error); id = stream->readInt64(&error);
bytes = std::unique_ptr<ByteArray>(stream->readByteArray(&error)); bytes = std::unique_ptr<ByteArray>(stream->readByteArray(&error));
} }
@ -1072,7 +1072,7 @@ TLObject *TL_auth_importAuthorization::deserializeResponse(NativeByteBuffer *str
void TL_auth_importAuthorization::serializeToStream(NativeByteBuffer *stream) { void TL_auth_importAuthorization::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(constructor); stream->writeInt32(constructor);
stream->writeInt32(id); stream->writeInt64(id);
stream->writeByteArray(bytes.get()); stream->writeByteArray(bytes.get());
} }

View file

@ -295,7 +295,7 @@ public:
class User : public TLObject { class User : public TLObject {
public: public:
int32_t id; int64_t id;
std::string first_name; std::string first_name;
std::string last_name; std::string last_name;
std::string username; std::string username;
@ -315,7 +315,7 @@ public:
class TL_userEmpty : public User { class TL_userEmpty : public User {
public: public:
static const uint32_t constructor = 0x200250ba; static const uint32_t constructor = 0xd3bc4b7a;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -324,7 +324,7 @@ public:
class TL_user : public User { class TL_user : public User {
public: public:
static const uint32_t constructor = 0x938458c1; static const uint32_t constructor = 0x3ff6ecb0;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -333,9 +333,9 @@ public:
class InputPeer : public TLObject { class InputPeer : public TLObject {
public: public:
int32_t user_id; int64_t user_id;
int32_t chat_id; int64_t chat_id;
int32_t channel_id; int64_t channel_id;
int64_t access_hash; int64_t access_hash;
static InputPeer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); static InputPeer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error);
@ -352,7 +352,7 @@ public:
class TL_inputPeerUser : public InputPeer { class TL_inputPeerUser : public InputPeer {
public: public:
static const uint32_t constructor = 0x7b8e7de6; static const uint32_t constructor = 0xdde8a54c;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -361,7 +361,7 @@ public:
class TL_inputPeerChat : public InputPeer { class TL_inputPeerChat : public InputPeer {
public: public:
static const uint32_t constructor = 0x179be863; static const uint32_t constructor = 0x35a95cb9;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -370,7 +370,7 @@ public:
class TL_inputPeerUserFromMessage : public InputPeer { class TL_inputPeerUserFromMessage : public InputPeer {
public: public:
static const uint32_t constructor = 0x17bae2e6; static const uint32_t constructor = 0xa87b0a1c;
std::unique_ptr<InputPeer> peer; std::unique_ptr<InputPeer> peer;
int32_t msg_id; int32_t msg_id;
@ -382,7 +382,7 @@ public:
class TL_inputPeerChannelFromMessage : public InputPeer { class TL_inputPeerChannelFromMessage : public InputPeer {
public: public:
static const uint32_t constructor = 0x9c95f7bb; static const uint32_t constructor = 0xbd2a0840;
std::unique_ptr<InputPeer> peer; std::unique_ptr<InputPeer> peer;
int32_t msg_id; int32_t msg_id;
@ -394,7 +394,7 @@ public:
class TL_inputPeerChannel : public InputPeer { class TL_inputPeerChannel : public InputPeer {
public: public:
static const uint32_t constructor = 0x20adaef8; static const uint32_t constructor = 0x27bcbbfc;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -411,7 +411,7 @@ public:
class InputUser : public TLObject { class InputUser : public TLObject {
public: public:
int32_t user_id; int64_t user_id;
int64_t access_hash; int64_t access_hash;
static InputUser *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); static InputUser *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error);
@ -428,7 +428,7 @@ public:
class TL_inputUser : public InputUser { class TL_inputUser : public InputUser {
public: public:
static const uint32_t constructor = 0xd8292816; static const uint32_t constructor = 0xf21158c6;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error); void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -445,7 +445,7 @@ public:
class TL_inputUserFromMessage : public InputUser { class TL_inputUserFromMessage : public InputUser {
public: public:
static const uint32_t constructor = 0x2d117597; static const uint32_t constructor = 0x1da448e2;
std::unique_ptr<InputPeer> peer; std::unique_ptr<InputPeer> peer;
int32_t msg_id; int32_t msg_id;
@ -539,9 +539,9 @@ public:
class TL_messageEntityMentionName : public MessageEntity { class TL_messageEntityMentionName : public MessageEntity {
public: 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 readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream); void serializeToStream(NativeByteBuffer *stream);
@ -693,9 +693,9 @@ public:
class TL_auth_exportedAuthorization : public TLObject { class TL_auth_exportedAuthorization : public TLObject {
public: public:
static const uint32_t constructor = 0xdf969c2d; static const uint32_t constructor = 0xb434e2b8;
int32_t id; int64_t id;
std::unique_ptr<ByteArray> bytes; std::unique_ptr<ByteArray> bytes;
static TL_auth_exportedAuthorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error); 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 { class TL_auth_importAuthorization : public TLObject {
public: public:
static const uint32_t constructor = 0xe3ef9613; static const uint32_t constructor = 0xa57a7dad;
int32_t id; int64_t id;
std::unique_ptr<ByteArray> bytes; std::unique_ptr<ByteArray> bytes;
bool isNeedLayer(); bool isNeedLayer();

View file

@ -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] { scheduleTask([&, userId] {
int32_t oldUserId = currentUserId; int32_t oldUserId = currentUserId;
currentUserId = userId; 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; currentVersion = version;
currentLayer = layer; currentLayer = layer;
currentApiId = apiId; currentApiId = apiId;

View file

@ -57,13 +57,13 @@ public:
void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port); void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port);
void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate); void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate);
ConnectionState getConnectionState(); ConnectionState getConnectionState();
void setUserId(int32_t userId); void setUserId(int64_t userId);
void switchBackend(bool restart); void switchBackend(bool restart);
void resumeNetwork(bool partial); void resumeNetwork(bool partial);
void pauseNetwork(); void pauseNetwork();
void setNetworkAvailable(bool value, int32_t type, bool slow); void setNetworkAvailable(bool value, int32_t type, bool slow);
void setIpStrategy(uint8_t value); 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 setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret);
void setLangCode(std::string langCode); void setLangCode(std::string langCode);
void setRegId(std::string regId); void setRegId(std::string regId);
@ -222,7 +222,7 @@ private:
std::string currentSystemLangCode; std::string currentSystemLangCode;
std::string currentConfigPath; std::string currentConfigPath;
std::string currentLogPath; std::string currentLogPath;
int32_t currentUserId = 0; int64_t currentUserId = 0;
bool registeredForInternalPush = false; bool registeredForInternalPush = false;
bool pushConnectionEnabled = true; bool pushConnectionEnabled = true;

View file

@ -17,7 +17,7 @@
#include "ByteArray.h" #include "ByteArray.h"
#define USE_DEBUG_SESSION false #define USE_DEBUG_SESSION false
#define READ_BUFFER_SIZE 1024 * 128 #define READ_BUFFER_SIZE 1024 * 1024 * 2
//#define DEBUG_VERSION //#define DEBUG_VERSION
#define PFS_ENABLED 1 #define PFS_ENABLED 1
#define DEFAULT_DATACENTER_ID INT_MAX #define DEFAULT_DATACENTER_ID INT_MAX

View file

@ -340,16 +340,6 @@
<action android:name="android.media.browse.MediaBrowserService"/> <action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter> </intent-filter>
</service> </service>
<service android:name=".WearDataLayerListenerService">
<intent-filter>
<!-- listeners receive events that match the action and data filters -->
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.CAPABILITY_CHANGED" />
<action android:name="com.google.android.gms.wearable.CHANNEL_EVENT" />
<data android:scheme="wear" android:host="*" />
</intent-filter>
</service>
<service android:name=".voip.TelegramConnectionService" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"> <service android:name=".voip.TelegramConnectionService" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter> <intent-filter>
<action android:name="android.telecom.ConnectionService" /> <action android:name="android.telecom.ConnectionService" />

View file

@ -80,8 +80,8 @@ dialogTextGray4=-7565423
chat_attachContactText=-2121728 chat_attachContactText=-2121728
chat_searchPanelIcons=-12937244 chat_searchPanelIcons=-12937244
windowBackgroundWhiteLinkText=-13990712 windowBackgroundWhiteLinkText=-13990712
chat_outVenueInfoText=-8216913 chat_outVenueInfoText=-9396792
chat_outContactPhoneText=-8612185 chat_outContactPhoneText=-9396792
chat_inAudioTitleText=-15061445 chat_inAudioTitleText=-15061445
chat_messageLinkIn=-16090691 chat_messageLinkIn=-16090691
chat_inBubbleSelected=-1509892 chat_inBubbleSelected=-1509892
@ -92,7 +92,7 @@ chat_outSiteNameText=-14515511
dialogTextGray=-7565423 dialogTextGray=-7565423
chat_messageLinkOut=-16155709 chat_messageLinkOut=-16155709
avatar_backgroundArchived=-4998207 avatar_backgroundArchived=-4998207
chat_outFileInfoSelectedText=-8674358 chat_outFileInfoSelectedText=-9396792
chat_outAudioDurationSelectedText=-8674358 chat_outAudioDurationSelectedText=-8674358
avatar_backgroundArchivedHidden=-10832396 avatar_backgroundArchivedHidden=-10832396
statisticChartLine_orange=-1853657 statisticChartLine_orange=-1853657
@ -105,7 +105,7 @@ chat_outReplyLine=-13133085
chat_inAudioSeekbarFill=-10572824 chat_inAudioSeekbarFill=-10572824
chat_inContactBackground=-431707662 chat_inContactBackground=-431707662
progressCircle=-14375188 progressCircle=-14375188
chat_outVenueInfoSelectedText=-8674358 chat_outVenueInfoSelectedText=-9396792
chats_menuItemIcon=-7433063 chats_menuItemIcon=-7433063
wallpaperFileOffset=-1 wallpaperFileOffset=-1
chat_outBubbleShadow=-16699318 chat_outBubbleShadow=-16699318
@ -130,8 +130,8 @@ chat_outBubbleSelected=-2690305
chat_inFileNameText=-15654091 chat_inFileNameText=-15654091
statisticChartLine_blue=-13467675 statisticChartLine_blue=-13467675
chat_inInstantSelected=-14707230 chat_inInstantSelected=-14707230
chat_outFileInfoText=-7953740 chat_outFileInfoText=-9396792
chat_outContactPhoneSelectedText=-9725764 chat_outContactPhoneSelectedText=-9396792
chat_wallpaper=-11300655 chat_wallpaper=-11300655
chat_outMenuSelected=-7026959 chat_outMenuSelected=-7026959
chat_outLoaderPhotoSelected=-263935502 chat_outLoaderPhotoSelected=-263935502
@ -142,14 +142,14 @@ avatar_actionBarSelectorBlue=-12091735
switchTrackChecked=-11424793 switchTrackChecked=-11424793
chat_inLoader=-431707662 chat_inLoader=-431707662
chat_outPreviewInstantSelectedText=-14514998 chat_outPreviewInstantSelectedText=-14514998
chat_outTimeText=-141776195 chat_outTimeText=-143614520
chat_attachAudioText=-2209977 chat_attachAudioText=-2209977
chat_outBubble=-1641732 chat_outBubble=-1641732
chat_attachHideBackground=-4866356 chat_attachHideBackground=-4866356
chats_menuItemText=-12632257 chats_menuItemText=-12632257
chat_outReplyNameText=-14382642 chat_outReplyNameText=-14382642
chats_menuTopBackgroundCats=-10906430 chats_menuTopBackgroundCats=-10906430
chat_outReplyMediaMessageText=-7558467 chat_outReplyMediaMessageText=-9396792
actionBarTabSelector=-12554340 actionBarTabSelector=-12554340
chat_outLoaderPhotoIcon=-263935502 chat_outLoaderPhotoIcon=-263935502
chat_attachFileText=-15423260 chat_attachFileText=-15423260
@ -178,9 +178,9 @@ chats_actionPressedBackground=-11166764
chat_replyPanelName=-13397538 chat_replyPanelName=-13397538
windowBackgroundWhiteValueText=-13003565 windowBackgroundWhiteValueText=-13003565
chat_outAudioDurationText=-7558467 chat_outAudioDurationText=-7558467
chat_outMenu=-5716778 chat_outMenu=-5782571
statisticChartActiveLine=335544320 statisticChartActiveLine=335544320
chat_outReplyMediaMessageSelectedText=-8674357 chat_outReplyMediaMessageSelectedText=-9396792
chats_attachMessage=-14843710 chats_attachMessage=-14843710
chat_outSentClock=-594761027 chat_outSentClock=-594761027
chat_searchPanelText=-12609056 chat_searchPanelText=-12609056

View file

@ -44,7 +44,7 @@ chat_outFileProgressSelected=-1
chat_outTimeSelectedText=-7023626 chat_outTimeSelectedText=-7023626
chat_inFileProgressSelected=-1 chat_inFileProgressSelected=-1
changephoneinfo_image=-11184811 changephoneinfo_image=-11184811
chat_inAudioPerfomerText=-8618883 chat_inAudioPerfomerText=-8749955
statisticChartBackZoomColor=-12145938 statisticChartBackZoomColor=-12145938
player_button=-1 player_button=-1
key_sheet_other=1140850687 key_sheet_other=1140850687
@ -61,7 +61,7 @@ player_actionBarTitle=-1
dialogGrayLine=-12040120 dialogGrayLine=-12040120
chat_outFileIcon=-12689015 chat_outFileIcon=-12689015
chats_nameMessage_threeLines=-1315861 chats_nameMessage_threeLines=-1315861
chat_adminText=-8355711 chat_adminText=-8552575
chat_inFileProgress=-1 chat_inFileProgress=-1
dialogIcon=-7566196 dialogIcon=-7566196
chat_emojiPanelEmptyText=-8553090 chat_emojiPanelEmptyText=-8553090
@ -79,8 +79,8 @@ chat_inReplyMediaMessageSelectedText=-7490861
avatar_actionBarSelectorOrange=-12758164 avatar_actionBarSelectorOrange=-12758164
dialogCheckboxSquareUnchecked=-10855846 dialogCheckboxSquareUnchecked=-10855846
chat_inMediaIconSelected=-1 chat_inMediaIconSelected=-1
chat_inBubble=-14540253 chat_inBubble=-14737117
chat_outSentCheckRead=-5841921 chat_outSentCheckRead=-506859265
chat_emojiPanelStickerPackSelector=181267199 chat_emojiPanelStickerPackSelector=181267199
chat_unreadMessagesStartArrowIcon=-9605777 chat_unreadMessagesStartArrowIcon=-9605777
avatar_backgroundActionBarOrange=-14602949 avatar_backgroundActionBarOrange=-14602949
@ -106,7 +106,7 @@ dialogInputField=-8553091
windowBackgroundWhiteInputFieldActivated=-9522449 windowBackgroundWhiteInputFieldActivated=-9522449
chat_attachGalleryBackground=-11692299 chat_attachGalleryBackground=-11692299
chat_outInstantSelected=-1 chat_outInstantSelected=-1
chat_outSentCheck=-251658241 chat_outSentCheck=-506859265
key_graySectionText=-8158332 key_graySectionText=-8158332
player_placeholder=-10197916 player_placeholder=-10197916
chat_outFileSelectedIcon=-13925429 chat_outFileSelectedIcon=-13925429
@ -116,7 +116,7 @@ dialogButton=-10177041
contextProgressInner1=-11184811 contextProgressInner1=-11184811
chat_inLoaderPhotoIconSelected=-1 chat_inLoaderPhotoIconSelected=-1
actionBarDefaultSubtitle=-7895161 actionBarDefaultSubtitle=-7895161
chat_inContactPhoneText=-8355711 chat_inContactPhoneText=-8486783
chat_inlineResultIcon=-8796932 chat_inlineResultIcon=-8796932
chat_outBubbleGradientSelectedOverlay=352321535 chat_outBubbleGradientSelectedOverlay=352321535
chats_draft=-637778102 chats_draft=-637778102
@ -164,7 +164,7 @@ switchThumb=-12034697
windowBackgroundWhiteRedText2=-955034 windowBackgroundWhiteRedText2=-955034
passport_authorizeBackground=-12352582 passport_authorizeBackground=-12352582
chats_nameIcon=-1250068 chats_nameIcon=-1250068
chat_inSentClock=-10263709 chat_inSentClock=-11050909
key_chats_menuTopShadow=789516 key_chats_menuTopShadow=789516
avatar_nameInMessageRed=-21124 avatar_nameInMessageRed=-21124
chat_outLoaderPhoto=-12623479 chat_outLoaderPhoto=-12623479
@ -280,7 +280,7 @@ chats_unreadCounterMuted=-12237499
chat_outVoiceSeekbarFill=-1 chat_outVoiceSeekbarFill=-1
chat_outReplyLine=-8466689 chat_outReplyLine=-8466689
chat_messagePanelIcons=-8947847 chat_messagePanelIcons=-8947847
chat_inReplyMediaMessageText=-8355711 chat_inReplyMediaMessageText=-8421247
inappPlayerTitle=-8618626 inappPlayerTitle=-8618626
chat_emojiPanelIconSelected=-10177041 chat_emojiPanelIconSelected=-10177041
progressCircle=-10177027 progressCircle=-10177027
@ -429,7 +429,7 @@ dialogSearchIcon=-8882056
chat_inPreviewInstantText=-8796932 chat_inPreviewInstantText=-8796932
chats_archiveBackground=-12219694 chats_archiveBackground=-12219694
dialog_liveLocationProgress=-9919529 dialog_liveLocationProgress=-9919529
chat_inViews=-8355712 chat_inViews=-8881024
chat_outLoaderSelected=-1 chat_outLoaderSelected=-1
dialogButtonSelector=-13158601 dialogButtonSelector=-13158601
chats_archivePinBackground=-13619152 chats_archivePinBackground=-13619152
@ -447,7 +447,7 @@ windowBackgroundWhiteGrayText5=-8549479
windowBackgroundWhiteGrayText6=-8553091 windowBackgroundWhiteGrayText6=-8553091
windowBackgroundWhiteGrayText3=-8553091 windowBackgroundWhiteGrayText3=-8553091
windowBackgroundWhiteGrayText4=-10987432 windowBackgroundWhiteGrayText4=-10987432
chat_inTimeText=-8355711 chat_inTimeText=-8552575
dialogRadioBackground=-10855846 dialogRadioBackground=-10855846
statisticChartRipple=748994002 statisticChartRipple=748994002
chat_outBubbleGradient=-12874567 chat_outBubbleGradient=-12874567
@ -474,7 +474,7 @@ chat_outAudioDurationText=-7023626
chat_outMenu=-7420685 chat_outMenu=-7420685
chat_goDownButton=-14606046 chat_goDownButton=-14606046
chats_secretName=-9316522 chats_secretName=-9316522
chat_inMenu=-10197916 chat_inMenu=-10656924
chat_recordVoiceCancel=-8553090 chat_recordVoiceCancel=-8553090
chat_inFileSelectedIcon=-15056797 chat_inFileSelectedIcon=-15056797
chat_outReplyMediaMessageSelectedText=-7023626 chat_outReplyMediaMessageSelectedText=-7023626
@ -484,8 +484,7 @@ dialogRedIcon=-554801041
avatar_subtitleInProfileCyan=-7628894 avatar_subtitleInProfileCyan=-7628894
chats_attachMessage=-8224126 chats_attachMessage=-8224126
chat_topPanelBackground=-15066597 chat_topPanelBackground=-15066597
chat_outSentClock=-8213557 chat_outSentClock=-6698513
dialogBackgroundGray=-14013910 dialogBackgroundGray=-14013910
chat_searchPanelText=-10767620 chat_searchPanelText=-10767620
chat_inContactIcon=-1 chat_inContactIcon=-1
voipgroup_topPanelGray=-10521727

View file

@ -15,13 +15,12 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat; import androidx.core.view.ViewCompat;
import com.google.android.exoplayer2.util.Log;
import org.telegram.messenger.BuildVars; import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.SharedConfig; import org.telegram.messenger.SharedConfig;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.BotHelpCell; import org.telegram.ui.Cells.BotHelpCell;
import org.telegram.ui.Cells.ChatMessageCell; import org.telegram.ui.Cells.ChatMessageCell;
import org.telegram.ui.ChatActivity; import org.telegram.ui.ChatActivity;
@ -57,8 +56,10 @@ public class ChatListItemAnimator extends DefaultItemAnimator {
private ChatGreetingsView chatGreetingsView; private ChatGreetingsView chatGreetingsView;
private boolean reversePositions; 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.activity = activity;
this.recyclerListView = listView; this.recyclerListView = listView;
translationInterpolator = DEFAULT_INTERPOLATOR; translationInterpolator = DEFAULT_INTERPOLATOR;
@ -293,12 +294,12 @@ public class ChatListItemAnimator extends DefaultItemAnimator {
if (activity.getChatActivityEnterView().canShowMessageTransition()) { if (activity.getChatActivityEnterView().canShowMessageTransition()) {
if (chatMessageCell.getMessageObject().isVoice()) { if (chatMessageCell.getMessageObject().isVoice()) {
if (Math.abs(view.getTranslationY()) < view.getMeasuredHeight() * 3f) { 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(); transition.start();
} }
} else { } else {
if (SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_LOW && Math.abs(view.getTranslationY()) < recyclerListView.getMeasuredHeight()) { 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(); transition.start();
} }
} }

View file

@ -243,6 +243,8 @@ public class AndroidUtilities {
R.drawable.media_doc_yellow_b R.drawable.media_doc_yellow_b
}; };
public static final String STICKERS_PLACEHOLDER_PACK_NAME = "tg_placeholders_android";
private static boolean containsUnsupportedCharacters(String text) { private static boolean containsUnsupportedCharacters(String text) {
if (text.contains("\u202C")) { if (text.contains("\u202C")) {
return true; return true;
@ -337,13 +339,13 @@ public class AndroidUtilities {
return str; return str;
} }
public static CharSequence highlightText(CharSequence str, ArrayList<String> query) { public static CharSequence highlightText(CharSequence str, ArrayList<String> query, Theme.ResourcesProvider resourcesProvider) {
if (query == null) { if (query == null) {
return null; return null;
} }
int emptyCount = 0; int emptyCount = 0;
for (int i = 0; i < query.size(); i++) { 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) { if (strTmp != null) {
str = strTmp; str = strTmp;
} else { } else {
@ -356,7 +358,7 @@ public class AndroidUtilities {
return str; 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)) { if (TextUtils.isEmpty(query) || TextUtils.isEmpty(str)) {
return null; return null;
} }
@ -365,7 +367,7 @@ public class AndroidUtilities {
int i = s.indexOf(query); int i = s.indexOf(query);
while (i >= 0) { while (i >= 0) {
try { 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) { } catch (Exception e) {
FileLog.e(e); FileLog.e(e);
} }
@ -1616,6 +1618,15 @@ public class AndroidUtilities {
return -1; 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) { public static float dpf2(float value) {
if (value == 0) { if (value == 0) {
return 0; return 0;
@ -2231,12 +2242,33 @@ public class AndroidUtilities {
}*/ }*/
public static void startAppCenter(Activity context) { 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; private static long lastUpdateCheckTime;
public static void checkForUpdates() { 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) { 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()) { if (f != null && f.exists()) {
String realMimeType = null; String realMimeType = null;
Intent intent = new Intent(Intent.ACTION_VIEW); 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()) { 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.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("ApkRestricted", R.string.ApkRestricted)); builder.setMessage(LocaleController.getString("ApkRestricted", R.string.ApkRestricted));
builder.setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialogInterface, i) -> { builder.setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialogInterface, i) -> {
@ -2860,7 +2892,7 @@ public class AndroidUtilities {
return false; return false;
} }
public static boolean openForView(MessageObject message, Activity activity) { public static boolean openForView(MessageObject message, Activity activity, Theme.ResourcesProvider resourcesProvider) {
File f = null; File f = null;
if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) { if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
f = new File(message.messageOwner.attachPath); f = new File(message.messageOwner.attachPath);
@ -2869,13 +2901,13 @@ public class AndroidUtilities {
f = FileLoader.getPathToMessage(message.messageOwner); f = FileLoader.getPathToMessage(message.messageOwner);
} }
String mimeType = message.type == 9 || message.type == 0 ? message.getMimeType() : null; 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) { public static boolean openForView(TLRPC.Document document, boolean forceCache, Activity activity) {
String fileName = FileLoader.getAttachFileName(document); String fileName = FileLoader.getAttachFileName(document);
File f = FileLoader.getPathToAttach(document, true); 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) { public static CharSequence replaceNewLines(CharSequence original) {
@ -3740,4 +3772,12 @@ public class AndroidUtilities {
view.setTag(null); 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);
}
}
} }

View file

@ -169,8 +169,7 @@ public class ApplicationLoader extends Application {
ContactsController.getInstance(a).checkAppAccount(); ContactsController.getInstance(a).checkAppAccount();
DownloadController.getInstance(a); DownloadController.getInstance(a);
} }
ChatThemeController.init();
WearDataLayerListenerService.updateWatchConnectionState();
} }
public ApplicationLoader() { public ApplicationLoader() {

View file

@ -22,11 +22,9 @@ import android.os.IBinder;
public class AuthenticatorService extends Service { public class AuthenticatorService extends Service {
private static class Authenticator extends AbstractAccountAuthenticator { private static class Authenticator extends AbstractAccountAuthenticator {
private final Context context;
public Authenticator(Context context) { public Authenticator(Context context) {
super(context); super(context);
this.context = context;
} }
@Override @Override

View file

@ -19,40 +19,38 @@ public class AutoMessageHeardReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
ApplicationLoader.postInitApplication(); ApplicationLoader.postInitApplication();
long dialog_id = intent.getLongExtra("dialog_id", 0); long dialogId = intent.getLongExtra("dialog_id", 0);
int max_id = intent.getIntExtra("max_id", 0); int maxId = intent.getIntExtra("max_id", 0);
int currentAccount = intent.getIntExtra("currentAccount", 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; return;
} }
int lowerId = (int) dialog_id;
int highId = (int) (dialog_id >> 32);
AccountInstance accountInstance = AccountInstance.getInstance(currentAccount); AccountInstance accountInstance = AccountInstance.getInstance(currentAccount);
if (lowerId > 0) { if (DialogObject.isUserDialog(dialogId)) {
TLRPC.User user = accountInstance.getMessagesController().getUser(lowerId); TLRPC.User user = accountInstance.getMessagesController().getUser(dialogId);
if (user == null) { if (user == null) {
Utilities.globalQueue.postRunnable(() -> { Utilities.globalQueue.postRunnable(() -> {
TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(lowerId); TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(dialogId);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
accountInstance.getMessagesController().putUser(user1, true); 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; return;
} }
} else if (lowerId < 0) { } else if (DialogObject.isChatDialog(dialogId)) {
TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-lowerId); TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialogId);
if (chat == null) { if (chat == null) {
Utilities.globalQueue.postRunnable(() -> { Utilities.globalQueue.postRunnable(() -> {
TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-lowerId); TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-dialogId);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
accountInstance.getMessagesController().putChat(chat1, true); 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; 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);
} }
} }

View file

@ -12,6 +12,8 @@ import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.text.TextUtils;
import androidx.core.app.RemoteInput; import androidx.core.app.RemoteInput;
public class AutoMessageReplyReceiver extends BroadcastReceiver { public class AutoMessageReplyReceiver extends BroadcastReceiver {
@ -24,16 +26,16 @@ public class AutoMessageReplyReceiver extends BroadcastReceiver {
return; return;
} }
CharSequence text = remoteInput.getCharSequence(NotificationsController.EXTRA_VOICE_REPLY); CharSequence text = remoteInput.getCharSequence(NotificationsController.EXTRA_VOICE_REPLY);
if (text == null || text.length() == 0) { if (TextUtils.isEmpty(text)) {
return; return;
} }
long dialog_id = intent.getLongExtra("dialog_id", 0); long dialogId = intent.getLongExtra("dialog_id", 0);
int max_id = intent.getIntExtra("max_id", 0); int maxId = intent.getIntExtra("max_id", 0);
int currentAccount = intent.getIntExtra("currentAccount", 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; return;
} }
SendMessagesHelper.getInstance(currentAccount).sendMessage(text.toString(), dialog_id, null, null, null, true, null, null, null, true, 0, null); SendMessagesHelper.getInstance(currentAccount).sendMessage(text.toString(), dialogId, 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); MessagesController.getInstance(currentAccount).markDialogAsRead(dialogId, maxId, maxId, 0, false, 0, 0, true, 0);
} }
} }

View file

@ -19,13 +19,10 @@ public class BuildVars {
public static boolean USE_CLOUD_STRINGS = true; public static boolean USE_CLOUD_STRINGS = true;
public static boolean CHECK_UPDATES = true; public static boolean CHECK_UPDATES = true;
public static boolean NO_SCOPED_STORAGE = true/* || Build.VERSION.SDK_INT <= 28*/; public static boolean NO_SCOPED_STORAGE = true/* || Build.VERSION.SDK_INT <= 28*/;
public static int BUILD_VERSION = 2406; public static int BUILD_VERSION = 2428;
public static String BUILD_VERSION_STRING = "8.0.0"; public static String BUILD_VERSION_STRING = "8.0.1";
public static int APP_ID = 4; public static int APP_ID = 4;
public static String APP_HASH = "014b35b6184100b085b0d0572f9b5103"; 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 SMS_HASH = isStandaloneApp() ? "w0lkcmTZkKh" : (DEBUG_VERSION ? "O2P2z+/jBpJ" : "oLeq9AcOZkT"); 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"; public static String PLAYSTORE_APP_URL = "https://play.google.com/store/apps/details?id=org.telegram.messenger";

View file

@ -13,6 +13,8 @@ import android.os.SystemClock;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.SparseArray; import android.util.SparseArray;
import com.google.android.exoplayer2.util.Log;
import org.telegram.messenger.voip.Instance; import org.telegram.messenger.voip.Instance;
import org.telegram.messenger.voip.VoIPService; import org.telegram.messenger.voip.VoIPService;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
@ -24,6 +26,8 @@ import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import androidx.collection.LongSparseArray;
public class ChatObject { public class ChatObject {
public static final int CHAT_TYPE_CHAT = 0; public static final int CHAT_TYPE_CHAT = 0;
@ -55,16 +59,16 @@ public class ChatObject {
public static class Call { public static class Call {
public TLRPC.GroupCall call; public TLRPC.GroupCall call;
public int chatId; public long chatId;
public SparseArray<TLRPC.TL_groupCallParticipant> participants = new SparseArray<>(); public LongSparseArray<TLRPC.TL_groupCallParticipant> participants = new LongSparseArray<>();
public final ArrayList<TLRPC.TL_groupCallParticipant> sortedParticipants = new ArrayList<>(); public final ArrayList<TLRPC.TL_groupCallParticipant> sortedParticipants = new ArrayList<>();
public final ArrayList<ChatObject.VideoParticipant> visibleVideoParticipants = new ArrayList<>(); public final ArrayList<VideoParticipant> visibleVideoParticipants = new ArrayList<>();
public final ArrayList<TLRPC.TL_groupCallParticipant> visibleParticipants = new ArrayList<>(); public final ArrayList<TLRPC.TL_groupCallParticipant> visibleParticipants = new ArrayList<>();
public final HashMap<String, Bitmap> thumbs = new HashMap<>(); public final HashMap<String, Bitmap> thumbs = new HashMap<>();
private final HashMap<String, VideoParticipant> videoParticipantsCache = new HashMap<>(); private final HashMap<String, VideoParticipant> videoParticipantsCache = new HashMap<>();
public ArrayList<Integer> invitedUsers = new ArrayList<>(); public ArrayList<Long> invitedUsers = new ArrayList<>();
public HashSet<Integer> invitedUsersMap = new HashSet<>(); public HashSet<Long> invitedUsersMap = new HashSet<>();
public SparseArray<TLRPC.TL_groupCallParticipant> participantsBySources = new SparseArray<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsBySources = new SparseArray<>();
public SparseArray<TLRPC.TL_groupCallParticipant> participantsByVideoSources = new SparseArray<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsByVideoSources = new SparseArray<>();
public SparseArray<TLRPC.TL_groupCallParticipant> participantsByPresentationSources = new SparseArray<>(); public SparseArray<TLRPC.TL_groupCallParticipant> participantsByPresentationSources = new SparseArray<>();
@ -91,8 +95,8 @@ public class ChatObject {
public TLRPC.Peer selfPeer; public TLRPC.Peer selfPeer;
private HashSet<Integer> loadingUids = new HashSet<>(); private HashSet<Long> loadingUids = new HashSet<>();
private HashSet<Integer> loadingSsrcs = new HashSet<>(); private HashSet<Long> loadingSsrcs = new HashSet<>();
private Runnable checkQueueRunnable; private Runnable checkQueueRunnable;
@ -100,7 +104,7 @@ public class ChatObject {
private boolean loadingGroupCall; private boolean loadingGroupCall;
private static int videoPointer; private static int videoPointer;
public final SparseArray<TLRPC.TL_groupCallParticipant> currentSpeakingPeers = new SparseArray<>(); public final LongSparseArray<TLRPC.TL_groupCallParticipant> currentSpeakingPeers = new LongSparseArray<>();
private final Runnable updateCurrentSpeakingRunnable = new Runnable() { private final Runnable updateCurrentSpeakingRunnable = new Runnable() {
@Override @Override
@ -108,11 +112,19 @@ public class ChatObject {
long uptime = SystemClock.uptimeMillis(); long uptime = SystemClock.uptimeMillis();
boolean update = false; boolean update = false;
for(int i = 0; i < currentSpeakingPeers.size(); i++) { 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); TLRPC.TL_groupCallParticipant participant = currentSpeakingPeers.get(key);
if (uptime - participant.lastSpeakTime >= 500) { if (uptime - participant.lastSpeakTime >= 500) {
update = true; update = true;
currentSpeakingPeers.remove(key); 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--; 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; this.chatId = chatId;
currentAccount = account; currentAccount = account;
call = groupCall.call; call = groupCall.call;
@ -162,7 +174,7 @@ public class ChatObject {
} }
public void addSelfDummyParticipant(boolean notify) { public void addSelfDummyParticipant(boolean notify) {
int selfId = getSelfId(); long selfId = getSelfId();
if (participants.indexOfKey(selfId) >= 0) { if (participants.indexOfKey(selfId) >= 0) {
return; return;
} }
@ -212,8 +224,8 @@ public class ChatObject {
return (call.flags & 128) != 0; return (call.flags & 128) != 0;
} }
private int getSelfId() { private long getSelfId() {
int selfId; long selfId;
if (selfPeer != null) { if (selfPeer != null) {
return MessageObject.getPeerId(selfPeer); return MessageObject.getPeerId(selfPeer);
} else { } else {
@ -222,13 +234,13 @@ public class ChatObject {
} }
private void onParticipantsLoad(ArrayList<TLRPC.TL_groupCallParticipant> loadedParticipants, boolean fromBegin, String reqOffset, String nextOffset, int version, int participantCount) { private void onParticipantsLoad(ArrayList<TLRPC.TL_groupCallParticipant> loadedParticipants, boolean fromBegin, String reqOffset, String nextOffset, int version, int participantCount) {
SparseArray<TLRPC.TL_groupCallParticipant> old = null; LongSparseArray<TLRPC.TL_groupCallParticipant> old = null;
int selfId = getSelfId(); long selfId = getSelfId();
TLRPC.TL_groupCallParticipant oldSelf = participants.get(selfId); TLRPC.TL_groupCallParticipant oldSelf = participants.get(selfId);
if (TextUtils.isEmpty(reqOffset)) { if (TextUtils.isEmpty(reqOffset)) {
if (participants.size() != 0) { if (participants.size() != 0) {
old = participants; old = participants;
participants = new SparseArray<>(); participants = new LongSparseArray<>();
} else { } else {
participants.clear(); 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)) { if (participants.get(uid) != null || invitedUsersMap.contains(uid)) {
return; return;
} }
@ -365,13 +377,13 @@ public class ChatObject {
invitedUsers.add(uid); invitedUsers.add(uid);
} }
public void processTypingsUpdate(AccountInstance accountInstance, ArrayList<Integer> uids, int date) { public void processTypingsUpdate(AccountInstance accountInstance, ArrayList<Long> uids, int date) {
boolean updated = false; boolean updated = false;
ArrayList<Integer> participantsToLoad = null; ArrayList<Long> participantsToLoad = null;
long time = SystemClock.elapsedRealtime(); long time = SystemClock.elapsedRealtime();
currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time);
for (int a = 0, N = uids.size(); a < N; a++) { 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); TLRPC.TL_groupCallParticipant participant = participants.get(id);
if (participant != null) { if (participant != null) {
if (date - participant.lastTypingDate > 10) { if (date - participant.lastTypingDate > 10) {
@ -397,8 +409,8 @@ public class ChatObject {
} }
} }
private void loadUnknownParticipants(ArrayList<Integer> participantsToLoad, boolean isIds, OnParticipantsLoad onLoad) { private void loadUnknownParticipants(ArrayList<Long> participantsToLoad, boolean isIds, OnParticipantsLoad onLoad) {
HashSet<Integer> set = isIds ? loadingUids : loadingSsrcs; HashSet<Long> set = isIds ? loadingUids : loadingSsrcs;
for (int a = 0, N = participantsToLoad.size(); a < N; a++) { for (int a = 0, N = participantsToLoad.size(); a < N; a++) {
if (set.contains(participantsToLoad.get(a))) { if (set.contains(participantsToLoad.get(a))) {
participantsToLoad.remove(a); participantsToLoad.remove(a);
@ -414,9 +426,9 @@ public class ChatObject {
set.addAll(participantsToLoad); set.addAll(participantsToLoad);
TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants(); TLRPC.TL_phone_getGroupParticipants req = new TLRPC.TL_phone_getGroupParticipants();
req.call = getInputGroupCall(); req.call = getInputGroupCall();
if (isIds) { for (int a = 0, N = participantsToLoad.size(); a < N; a++) {
for (int a = 0, N = participantsToLoad.size(); a < N; a++) { long uid = participantsToLoad.get(a);
Integer uid = participantsToLoad.get(a); if (isIds) {
if (uid > 0) { if (uid > 0) {
TLRPC.TL_inputPeerUser peerUser = new TLRPC.TL_inputPeerUser(); TLRPC.TL_inputPeerUser peerUser = new TLRPC.TL_inputPeerUser();
peerUser.user_id = uid; peerUser.user_id = uid;
@ -433,9 +445,9 @@ public class ChatObject {
} }
req.ids.add(inputPeer); req.ids.add(inputPeer);
} }
} else {
req.sources.add((int) uid);
} }
} else {
req.sources = participantsToLoad;
} }
req.offset = ""; req.offset = "";
req.limit = 100; req.limit = 100;
@ -449,7 +461,7 @@ public class ChatObject {
currentAccount.getMessagesController().putChats(groupParticipants.chats, false); currentAccount.getMessagesController().putChats(groupParticipants.chats, false);
for (int a = 0, N = groupParticipants.participants.size(); a < N; a++) { for (int a = 0, N = groupParticipants.participants.size(); a < N; a++) {
TLRPC.TL_groupCallParticipant participant = groupParticipants.participants.get(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); TLRPC.TL_groupCallParticipant oldParticipant = participants.get(pid);
if (oldParticipant != null) { if (oldParticipant != null) {
sortedParticipants.remove(oldParticipant); sortedParticipants.remove(oldParticipant);
@ -459,7 +471,7 @@ public class ChatObject {
sortedParticipants.add(participant); sortedParticipants.add(participant);
processAllSources(participant, true); processAllSources(participant, true);
if (invitedUsersMap.contains(pid)) { if (invitedUsersMap.contains(pid)) {
Integer id = pid; Long id = pid;
invitedUsersMap.remove(id); invitedUsersMap.remove(id);
invitedUsers.remove(id); invitedUsers.remove(id);
} }
@ -530,7 +542,7 @@ public class ChatObject {
boolean updated = false; boolean updated = false;
boolean updateCurrentSpeakingList = false; boolean updateCurrentSpeakingList = false;
int currentTime = currentAccount.getConnectionsManager().getCurrentTime(); int currentTime = currentAccount.getConnectionsManager().getCurrentTime();
ArrayList<Integer> participantsToLoad = null; ArrayList<Long> participantsToLoad = null;
long time = SystemClock.elapsedRealtime(); long time = SystemClock.elapsedRealtime();
long uptime = SystemClock.uptimeMillis(); long uptime = SystemClock.uptimeMillis();
currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time);
@ -547,7 +559,7 @@ public class ChatObject {
participant.hasVoiceDelayed = voice[a]; participant.hasVoiceDelayed = voice[a];
participant.lastVoiceUpdateTime = time; participant.lastVoiceUpdateTime = time;
} }
int peerId = MessageObject.getPeerId(participant.peer); long peerId = MessageObject.getPeerId(participant.peer);
if (levels[a] > 0.1f) { if (levels[a] > 0.1f) {
if (voice[a] && participant.lastTypingDate + 1 < currentTime) { if (voice[a] && participant.lastTypingDate + 1 < currentTime) {
if (time != participant.lastVisibleDate) { if (time != participant.lastVisibleDate) {
@ -560,6 +572,13 @@ public class ChatObject {
participant.amplitude = levels[a]; participant.amplitude = levels[a];
if (currentSpeakingPeers.get(peerId, null) == null) { 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); currentSpeakingPeers.put(peerId, participant);
updateCurrentSpeakingList = true; updateCurrentSpeakingList = true;
} }
@ -567,6 +586,15 @@ public class ChatObject {
if (uptime - participant.lastSpeakTime >= 500) { if (uptime - participant.lastSpeakTime >= 500) {
if (currentSpeakingPeers.get(peerId, null) != null) { if (currentSpeakingPeers.get(peerId, null) != null) {
currentSpeakingPeers.remove(peerId); 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; updateCurrentSpeakingList = true;
} }
} }
@ -576,7 +604,7 @@ public class ChatObject {
if (participantsToLoad == null) { if (participantsToLoad == null) {
participantsToLoad = new ArrayList<>(); participantsToLoad = new ArrayList<>();
} }
participantsToLoad.add(ssrc[a]); participantsToLoad.add((long) ssrc[a]);
} }
} }
if (participantsToLoad != null) { if (participantsToLoad != null) {
@ -610,11 +638,11 @@ public class ChatObject {
} }
public interface OnParticipantsLoad { public interface OnParticipantsLoad {
void onLoad(ArrayList<Integer> ssrcs); void onLoad(ArrayList<Long> ssrcs);
} }
public void processUnknownVideoParticipants(int[] ssrc, OnParticipantsLoad onLoad) { public void processUnknownVideoParticipants(int[] ssrc, OnParticipantsLoad onLoad) {
ArrayList<Integer> participantsToLoad = null; ArrayList<Long> participantsToLoad = null;
for (int a = 0; a < ssrc.length; a++) { for (int a = 0; a < ssrc.length; a++) {
if (participantsBySources.get(ssrc[a]) != null || participantsByVideoSources.get(ssrc[a]) != null || participantsByPresentationSources.get(ssrc[a]) != null) { if (participantsBySources.get(ssrc[a]) != null || participantsByVideoSources.get(ssrc[a]) != null || participantsByPresentationSources.get(ssrc[a]) != null) {
continue; continue;
@ -622,7 +650,7 @@ public class ChatObject {
if (participantsToLoad == null) { if (participantsToLoad == null) {
participantsToLoad = new ArrayList<>(); participantsToLoad = new ArrayList<>();
} }
participantsToLoad.add(ssrc[a]); participantsToLoad.add((long) ssrc[a]);
} }
if (participantsToLoad != null) { if (participantsToLoad != null) {
loadUnknownParticipants(participantsToLoad, false, onLoad); loadUnknownParticipants(participantsToLoad, false, onLoad);
@ -797,7 +825,7 @@ public class ChatObject {
boolean changedOrAdded = false; boolean changedOrAdded = false;
boolean speakingUpdated = false; boolean speakingUpdated = false;
int selfId = getSelfId(); long selfId = getSelfId();
long time = SystemClock.elapsedRealtime(); long time = SystemClock.elapsedRealtime();
long justJoinedId = 0; long justJoinedId = 0;
int lastParticipantDate; int lastParticipantDate;
@ -809,7 +837,7 @@ public class ChatObject {
currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time); currentAccount.getNotificationCenter().postNotificationName(NotificationCenter.applyGroupCallVisibleParticipants, time);
for (int a = 0, N = update.participants.size(); a < N; a++) { for (int a = 0, N = update.participants.size(); a < N; a++) {
TLRPC.TL_groupCallParticipant participant = update.participants.get(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) { if (BuildVars.LOGS_ENABLED) {
FileLog.d("process participant " + pid + " left = " + participant.left + " versioned " + participant.versioned + " flags = " + participant.flags + " self = " + selfId + " volume = " + participant.volume); 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); sortedParticipants.remove(oldParticipant);
visibleParticipants.remove(oldParticipant); visibleParticipants.remove(oldParticipant);
if (currentSpeakingPeers.get(pid, null) != null) { 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); currentSpeakingPeers.remove(pid);
speakingUpdated = true; speakingUpdated = true;
} }
@ -845,7 +880,7 @@ public class ChatObject {
updated = true; updated = true;
} else { } else {
if (invitedUsersMap.contains(pid)) { if (invitedUsersMap.contains(pid)) {
Integer id = pid; Long id = pid;
invitedUsersMap.remove(id); invitedUsersMap.remove(id);
invitedUsers.remove(id); invitedUsers.remove(id);
} }
@ -856,6 +891,13 @@ public class ChatObject {
oldParticipant.muted = participant.muted; oldParticipant.muted = participant.muted;
if (participant.muted && currentSpeakingPeers.get(pid, null) != null) { if (participant.muted && currentSpeakingPeers.get(pid, null) != null) {
currentSpeakingPeers.remove(pid); 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; speakingUpdated = true;
} }
if (!participant.min) { if (!participant.min) {
@ -1032,7 +1074,8 @@ public class ChatObject {
visibleParticipants.clear(); visibleParticipants.clear();
TLRPC.Chat chat = currentAccount.getMessagesController().getChat(chatId); TLRPC.Chat chat = currentAccount.getMessagesController().getChat(chatId);
boolean isAdmin = ChatObject.canManageCalls(chat); boolean isAdmin = ChatObject.canManageCalls(chat);
int selfId = getSelfId();
long selfId = getSelfId();
VoIPService service = VoIPService.getSharedInstance(); VoIPService service = VoIPService.getSharedInstance();
TLRPC.TL_groupCallParticipant selfParticipant = participants.get(selfId); TLRPC.TL_groupCallParticipant selfParticipant = participants.get(selfId);
canStreamVideo = true;//selfParticipant != null && selfParticipant.video_joined || BuildVars.DEBUG_PRIVATE_VERSION; 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; 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); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId);
return ChatObject.isChannel(chat) && chat.megagroup; 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; 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); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId);
return chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden; 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); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(chatId);
return ChatObject.canSendMessages(chat) || chat.megagroup; return ChatObject.canSendMessages(chat) || chat.megagroup;
} }
@ -1553,15 +1596,6 @@ public class ChatObject {
return currentBannedRights; 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) { public static boolean hasPhoto(TLRPC.Chat chat) {
return chat != null && chat.photo != null && !(chat.photo instanceof TLRPC.TL_chatPhotoEmpty); return chat != null && chat.photo != null && !(chat.photo instanceof TLRPC.TL_chatPhotoEmpty);
} }

View file

@ -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<Long, Bitmap> themeIdWallpaperMap = new HashMap<>();
private static final HashMap<Long, Bitmap> themeIdWallpaperThumbMap = new HashMap<>();
private static List<ChatTheme> 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<List<ChatTheme>> 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<ChatTheme> 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<ChatTheme> 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<ChatTheme> getAllChatThemesFromPrefs() {
SharedPreferences preferences = getSharedPreferences();
int count = preferences.getInt("count", 0);
List<ChatTheme> 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<ChatTheme> callback) {
if (TextUtils.isEmpty(emoticon)) {
callback.onComplete(null);
return;
}
requestAllChatThemes(new ResultCallback<List<ChatTheme>>() {
@Override
public void onComplete(List<ChatTheme> 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<String> 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();
}
}

View file

@ -17,8 +17,6 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.Spanned; import android.text.Spanned;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.view.View; import android.view.View;
import android.widget.RemoteViews; import android.widget.RemoteViews;
import android.widget.RemoteViewsService; import android.widget.RemoteViewsService;
@ -32,6 +30,8 @@ import org.telegram.ui.EditWidgetActivity;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import androidx.collection.LongSparseArray;
public class ChatsWidgetService extends RemoteViewsService { public class ChatsWidgetService extends RemoteViewsService {
@Override @Override
public RemoteViewsFactory onGetViewFactory(Intent intent) { public RemoteViewsFactory onGetViewFactory(Intent intent) {
@ -101,8 +101,8 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
TLRPC.FileLocation photoPath = null; TLRPC.FileLocation photoPath = null;
TLRPC.User user = null; TLRPC.User user = null;
TLRPC.Chat chat = null; TLRPC.Chat chat = null;
if (id > 0) { if (DialogObject.isUserDialog(id)) {
user = accountInstance.getMessagesController().getUser((int) (long) id); user = accountInstance.getMessagesController().getUser(id);
if (user != null) { if (user != null) {
if (UserObject.isUserSelf(user)) { if (UserObject.isUserSelf(user)) {
name = LocaleController.getString("SavedMessages", R.string.SavedMessages); name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
@ -113,12 +113,12 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
} else { } else {
name = ContactsController.formatName(user.first_name, user.last_name); 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; photoPath = user.photo.photo_small;
} }
} }
} else { } else {
chat = accountInstance.getMessagesController().getChat(-(int) (long) id); chat = accountInstance.getMessagesController().getChat(-id);
if (chat != null) { if (chat != null) {
name = chat.title; 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) { 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) { if (message != null) {
TLRPC.User fromUser = null; TLRPC.User fromUser = null;
TLRPC.Chat fromChat = null; TLRPC.Chat fromChat = null;
int fromId = message.getFromChatId(); long fromId = message.getFromChatId();
if (fromId > 0) { if (DialogObject.isUserDialog(fromId)) {
fromUser = accountInstance.getMessagesController().getUser(fromId); fromUser = accountInstance.getMessagesController().getUser(fromId);
} else { } else {
fromChat = accountInstance.getMessagesController().getChat(-fromId); fromChat = accountInstance.getMessagesController().getChat(-fromId);
@ -198,7 +198,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
textColor = mContext.getResources().getColor(R.color.widget_action_text); textColor = mContext.getResources().getColor(R.color.widget_action_text);
} else { } else {
boolean needEmoji = true; 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()) { if (message.isOutOwner()) {
messageNameString = LocaleController.getString("FromYou", R.string.FromYou); messageNameString = LocaleController.getString("FromYou", R.string.FromYou);
} else if (fromUser != null) { } else if (fromUser != null) {
@ -303,7 +303,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle()); messageString = String.format("\uD83C\uDFA7 %s - %s", message.getMusicAuthor(), message.getMusicTitle());
} else { } else {
messageString = message.messageText; messageString = message.messageText;
AndroidUtilities.highlightText(messageString, message.highlightedWords); AndroidUtilities.highlightText(messageString, message.highlightedWords, null);
} }
if (message.messageOwner.media != null && !message.isMediaEmpty()) { if (message.messageOwner.media != null && !message.isMediaEmpty()) {
textColor = mContext.getResources().getColor(R.color.widget_action_text); textColor = mContext.getResources().getColor(R.color.widget_action_text);
@ -339,10 +339,10 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
Bundle extras = new Bundle(); Bundle extras = new Bundle();
if (id > 0) { if (DialogObject.isUserDialog(id)) {
extras.putInt("userId", (int) (long) id); extras.putLong("userId", id);
} else { } else {
extras.putInt("chatId", -(int) (long) id); extras.putLong("chatId", -id);
} }
extras.putInt("currentAccount", accountInstance.getCurrentAccount()); extras.putInt("currentAccount", accountInstance.getCurrentAccount());
@ -385,7 +385,7 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
accountInstance.getMessagesController().putChats(chats, true); accountInstance.getMessagesController().putChats(chats, true);
messageObjects.clear(); messageObjects.clear();
for (int a = 0, N = messages.size(); a < N; a++) { for (int a = 0, N = messages.size(); a < N; a++) {
MessageObject messageObject = new MessageObject(accountInstance.getCurrentAccount(), messages.valueAt(a), (SparseArray<TLRPC.User>) null, null, false, true); MessageObject messageObject = new MessageObject(accountInstance.getCurrentAccount(), messages.valueAt(a), (LongSparseArray<TLRPC.User>) null, null, false, true);
messageObjects.put(messages.keyAt(a), messageObject); messageObjects.put(messages.keyAt(a), messageObject);
} }
} }

View file

@ -27,7 +27,6 @@ import android.text.TextUtils;
import android.util.SparseArray; import android.util.SparseArray;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.support.SparseLongArray;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.Bulletin; import org.telegram.ui.Components.Bulletin;
@ -38,6 +37,8 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import androidx.collection.LongSparseArray;
public class ContactsController extends BaseController { public class ContactsController extends BaseController {
private Account systemAccount; private Account systemAccount;
@ -51,7 +52,7 @@ public class ContactsController extends BaseController {
private boolean contactsBookLoaded; private boolean contactsBookLoaded;
private boolean migratingContacts; private boolean migratingContacts;
private String lastContactsVersions = ""; private String lastContactsVersions = "";
private ArrayList<Integer> delayedContactsUpdate = new ArrayList<>(); private ArrayList<Long> delayedContactsUpdate = new ArrayList<>();
private String inviteLink; private String inviteLink;
private boolean updatingInviteLink; private boolean updatingInviteLink;
private HashMap<String, String> sectionsToReplace = new HashMap<>(); private HashMap<String, String> sectionsToReplace = new HashMap<>();
@ -167,7 +168,7 @@ public class ContactsController extends BaseController {
public ArrayList<String> phoneBookSectionsArray = new ArrayList<>(); public ArrayList<String> phoneBookSectionsArray = new ArrayList<>();
public ArrayList<TLRPC.TL_contact> contacts = new ArrayList<>(); public ArrayList<TLRPC.TL_contact> contacts = new ArrayList<>();
public ConcurrentHashMap<Integer, TLRPC.TL_contact> contactsDict = new ConcurrentHashMap<>(20, 1.0f, 2); public ConcurrentHashMap<Long, TLRPC.TL_contact> contactsDict = new ConcurrentHashMap<>(20, 1.0f, 2);
public HashMap<String, ArrayList<TLRPC.TL_contact>> usersSectionsDict = new HashMap<>(); public HashMap<String, ArrayList<TLRPC.TL_contact>> usersSectionsDict = new HashMap<>();
public ArrayList<String> sortedUsersSectionsArray = new ArrayList<>(); public ArrayList<String> sortedUsersSectionsArray = new ArrayList<>();
@ -581,9 +582,7 @@ public class ContactsController extends BaseController {
if (pCur != null) { if (pCur != null) {
int count = pCur.getCount(); int count = pCur.getCount();
if (count > 0) { if (count > 0) {
if (contactsMap == null) { contactsMap = new HashMap<>(count);
contactsMap = new HashMap<>(count);
}
while (pCur.moveToNext()) { while (pCur.moveToNext()) {
String number = pCur.getString(1); String number = pCur.getString(1);
String accountType = pCur.getString(5); String accountType = pCur.getString(5);
@ -695,7 +694,7 @@ public class ContactsController extends BaseController {
String fname = pCur.getString(1); String fname = pCur.getString(1);
String sname = pCur.getString(2); String sname = pCur.getString(2);
String mname = pCur.getString(3); 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 != null && !contact.namesFilled) {
if (contact.isGoodProvider) { if (contact.isGoodProvider) {
if (fname != null) { if (fname != null) {
@ -1297,7 +1296,7 @@ public class ContactsController extends BaseController {
if (first) { if (first) {
contactsLoaded = true; contactsLoaded = true;
} }
if (!delayedContactsUpdate.isEmpty() && contactsLoaded && contactsBookLoaded) { if (!delayedContactsUpdate.isEmpty() && contactsLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null); applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear(); delayedContactsUpdate.clear();
} }
@ -1316,7 +1315,7 @@ public class ContactsController extends BaseController {
} }
} }
private int getContactsHash(ArrayList<TLRPC.TL_contact> contacts) { private long getContactsHash(ArrayList<TLRPC.TL_contact> contacts) {
long acc = 0; long acc = 0;
contacts = new ArrayList<>(contacts); contacts = new ArrayList<>(contacts);
Collections.sort(contacts, (tl_contact, tl_contact2) -> { Collections.sort(contacts, (tl_contact, tl_contact2) -> {
@ -1330,16 +1329,16 @@ public class ContactsController extends BaseController {
int count = contacts.size(); int count = contacts.size();
for (int a = -1; a < count; a++) { for (int a = -1; a < count; a++) {
if (a == -1) { if (a == -1) {
acc = ((acc * 20261) + 0x80000000L + getUserConfig().contactsSavedCount) % 0x80000000L; acc = MediaDataController.calcHash(acc, getUserConfig().contactsSavedCount);
} else { } else {
TLRPC.TL_contact set = contacts.get(a); 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) { synchronized (loadContactsSync) {
loadingContacts = true; loadingContacts = true;
} }
@ -1391,7 +1390,7 @@ public class ContactsController extends BaseController {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
getMessagesController().putUsers(usersArr, from == 1); getMessagesController().putUsers(usersArr, from == 1);
final SparseArray<TLRPC.User> usersDict = new SparseArray<>(); final LongSparseArray<TLRPC.User> usersDict = new LongSparseArray<>();
final boolean isEmpty = contactsArr.isEmpty(); final boolean isEmpty = contactsArr.isEmpty();
@ -1463,7 +1462,7 @@ public class ContactsController extends BaseController {
return name1.compareTo(name2); return name1.compareTo(name2);
}); });
final ConcurrentHashMap<Integer, TLRPC.TL_contact> contactsDictionary = new ConcurrentHashMap<>(20, 1.0f, 2); final ConcurrentHashMap<Long, TLRPC.TL_contact> contactsDictionary = new ConcurrentHashMap<>(20, 1.0f, 2);
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>(); final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDictMutual = new HashMap<>(); final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDictMutual = new HashMap<>();
final ArrayList<String> sortedSectionsArray = new ArrayList<>(); final ArrayList<String> sortedSectionsArray = new ArrayList<>();
@ -1593,8 +1592,8 @@ public class ContactsController extends BaseController {
}); });
} }
public boolean isContact(int uid) { public boolean isContact(long userId) {
return contactsDict.get(uid) != null; return contactsDict.get(userId) != null;
} }
public void reloadContactsStatusesMaybe() { public void reloadContactsStatusesMaybe() {
@ -1838,10 +1837,10 @@ public class ContactsController extends BaseController {
final ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver(); 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(); 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); cursor = contentResolver.query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
SparseLongArray bookContacts = new SparseLongArray(); LongSparseArray<Long> bookContacts = new LongSparseArray<>();
if (cursor != null) { if (cursor != null) {
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
bookContacts.put(cursor.getInt(1), cursor.getLong(0)); bookContacts.put(cursor.getLong(1), cursor.getLong(0));
} }
cursor.close(); cursor.close();
cursor = null; cursor = null;
@ -1867,12 +1866,12 @@ public class ContactsController extends BaseController {
Utilities.phoneBookQueue.postRunnable(() -> performWriteContactsToPhoneBookInternal(contactsArray)); Utilities.phoneBookQueue.postRunnable(() -> performWriteContactsToPhoneBookInternal(contactsArray));
} }
private void applyContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict, ArrayList<TLRPC.TL_contact> newC, ArrayList<Integer> contactsTD) { private void applyContactsUpdates(ArrayList<Long> ids, ConcurrentHashMap<Long, TLRPC.User> userDict, ArrayList<TLRPC.TL_contact> newC, ArrayList<Long> contactsTD) {
if (newC == null || contactsTD == null) { if (newC == null || contactsTD == null) {
newC = new ArrayList<>(); newC = new ArrayList<>();
contactsTD = new ArrayList<>(); contactsTD = new ArrayList<>();
for (int a = 0; a < ids.size(); a++) { for (int a = 0; a < ids.size(); a++) {
Integer uid = ids.get(a); Long uid = ids.get(a);
if (uid > 0) { if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact(); TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = uid; contact.user_id = uid;
@ -1920,7 +1919,7 @@ public class ContactsController extends BaseController {
} }
for (int a = 0; a < contactsTD.size(); a++) { 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)); Utilities.phoneBookQueue.postRunnable(() -> deleteContactFromPhoneBook(uid));
TLRPC.User user = null; TLRPC.User user = null;
@ -1960,7 +1959,7 @@ public class ContactsController extends BaseController {
Utilities.stageQueue.postRunnable(() -> loadContacts(false, 0)); Utilities.stageQueue.postRunnable(() -> loadContacts(false, 0));
} else { } else {
final ArrayList<TLRPC.TL_contact> newContacts = newC; final ArrayList<TLRPC.TL_contact> newContacts = newC;
final ArrayList<Integer> contactsToDelete = contactsTD; final ArrayList<Long> contactsToDelete = contactsTD;
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
for (int a = 0; a < newContacts.size(); a++) { for (int a = 0; a < newContacts.size(); a++) {
TLRPC.TL_contact contact = newContacts.get(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++) { 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); TLRPC.TL_contact contact = contactsDict.get(uid);
if (contact != null) { if (contact != null) {
contacts.remove(contact); contacts.remove(contact);
@ -1988,10 +1987,10 @@ public class ContactsController extends BaseController {
} }
} }
public void processContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict) { public void processContactsUpdates(ArrayList<Long> ids, ConcurrentHashMap<Long, TLRPC.User> userDict) {
final ArrayList<TLRPC.TL_contact> newContacts = new ArrayList<>(); final ArrayList<TLRPC.TL_contact> newContacts = new ArrayList<>();
final ArrayList<Integer> contactsToDelete = new ArrayList<>(); final ArrayList<Long> contactsToDelete = new ArrayList<>();
for (Integer uid : ids) { for (Long uid : ids) {
if (uid > 0) { if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact(); TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = uid; contact.user_id = uid;
@ -2115,7 +2114,7 @@ public class ContactsController extends BaseController {
return res; return res;
} }
private void deleteContactFromPhoneBook(int uid) { private void deleteContactFromPhoneBook(long uid) {
if (!hasContactsPermission()) { if (!hasContactsPermission()) {
return; return;
} }
@ -2223,8 +2222,9 @@ public class ContactsController extends BaseController {
return; return;
} }
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts(); TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
final ArrayList<Integer> uids = new ArrayList<>(); final ArrayList<Long> uids = new ArrayList<>();
for (TLRPC.User user : users) { for (int a = 0, N = users.size(); a < N; a++) {
TLRPC.User user = users.get(a);
TLRPC.InputUser inputUser = getMessagesController().getInputUser(user); TLRPC.InputUser inputUser = getMessagesController().getInputUser(user);
if (inputUser == null) { if (inputUser == null) {
continue; continue;
@ -2512,7 +2512,7 @@ public class ContactsController extends BaseController {
reloadContactsStatuses(); reloadContactsStatuses();
} }
public void createOrUpdateConnectionServiceContact(int id, String firstName, String lastName) { public void createOrUpdateConnectionServiceContact(long id, String firstName, String lastName) {
if (!hasContactsPermission()) { if (!hasContactsPermission()) {
return; return;
} }

View file

@ -13,12 +13,9 @@ public final class ContactsLoadingObserver {
void onResult(boolean contactsLoaded); void onResult(boolean contactsLoaded);
} }
private final NotificationCenter.NotificationCenterDelegate observer = new NotificationCenter.NotificationCenterDelegate() { private final NotificationCenter.NotificationCenterDelegate observer = (id, account, args) -> {
@Override if (id == NotificationCenter.contactsDidLoad) {
public void didReceivedNotification(int id, int account, Object... args) { onContactsLoadingStateUpdated(account, false);
if (id == NotificationCenter.contactsDidLoad) {
onContactsLoadingStateUpdated(account, false);
}
} }
}; };

View file

@ -14,7 +14,6 @@ import android.graphics.Paint;
import android.graphics.RectF; import android.graphics.RectF;
import android.graphics.Shader; import android.graphics.Shader;
import android.os.Bundle; import android.os.Bundle;
import android.util.LongSparseArray;
import android.view.View; import android.view.View;
import android.widget.RemoteViews; import android.widget.RemoteViews;
import android.widget.RemoteViewsService; import android.widget.RemoteViewsService;
@ -27,6 +26,8 @@ import org.telegram.ui.EditWidgetActivity;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import androidx.collection.LongSparseArray;
public class ContactsWidgetService extends RemoteViewsService { public class ContactsWidgetService extends RemoteViewsService {
@Override @Override
public RemoteViewsFactory onGetViewFactory(Intent intent) { public RemoteViewsFactory onGetViewFactory(Intent intent) {
@ -104,8 +105,8 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor
TLRPC.FileLocation photoPath = null; TLRPC.FileLocation photoPath = null;
TLRPC.User user = null; TLRPC.User user = null;
TLRPC.Chat chat = null; TLRPC.Chat chat = null;
if (id > 0) { if (DialogObject.isUserDialog(id)) {
user = accountInstance.getMessagesController().getUser((int) (long) id); user = accountInstance.getMessagesController().getUser(id);
if (UserObject.isUserSelf(user)) { if (UserObject.isUserSelf(user)) {
name = LocaleController.getString("SavedMessages", R.string.SavedMessages); name = LocaleController.getString("SavedMessages", R.string.SavedMessages);
} else if (UserObject.isReplyUser(user)) { } else if (UserObject.isReplyUser(user)) {
@ -119,7 +120,7 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor
photoPath = user.photo.photo_small; photoPath = user.photo.photo_small;
} }
} else { } else {
chat = accountInstance.getMessagesController().getChat(-(int) (long) id); chat = accountInstance.getMessagesController().getChat(-id);
if (chat != null) { if (chat != null) {
name = chat.title; 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) { 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(); Bundle extras = new Bundle();
if (id > 0) { if (DialogObject.isUserDialog(id)) {
extras.putInt("userId", (int) (long) id); extras.putLong("userId", id);
} else { } else {
extras.putInt("chatId", -(int) (long) id); extras.putLong("chatId", -id);
} }
extras.putInt("currentAccount", accountInstance.getCurrentAccount()); extras.putInt("currentAccount", accountInstance.getCurrentAccount());

View file

@ -16,28 +16,12 @@ public class DialogObject {
return dialog != null && (dialog.flags & 1) != 0; return dialog != null && (dialog.flags & 1) != 0;
} }
public static long makeSecretDialogId(int chatId) {
return ((long) chatId) << 32;
}
public static long makeFolderDialogId(int folderId) { public static long makeFolderDialogId(int folderId) {
return (((long) 2) << 32) | folderId; return 0x2000000000000000L | (long) folderId;
} }
public static boolean isFolderDialogId(long dialogId) { public static boolean isFolderDialogId(long dialogId) {
int lowerId = (int) dialogId; return (dialogId & 0x2000000000000000L) != 0 && (dialogId & 0x8000000000000000L) == 0;
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;
} }
public static void initDialog(TLRPC.Dialog dialog) { public static void initDialog(TLRPC.Dialog dialog) {
@ -90,4 +74,28 @@ public class DialogObject {
public static long getLastMessageOrDraftDate(TLRPC.Dialog dialog, TLRPC.DraftMessage draftMessage) { 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; 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;
}
} }

View file

@ -12,12 +12,12 @@ public class DocumentObject {
public static class ThemeDocument extends TLRPC.TL_document { public static class ThemeDocument extends TLRPC.TL_document {
public TLRPC.TL_themeSettings themeSettings; public TLRPC.ThemeSettings themeSettings;
public TLRPC.Document wallpaper; public TLRPC.Document wallpaper;
public Theme.ThemeInfo baseTheme; public Theme.ThemeInfo baseTheme;
public Theme.ThemeAccent accent; public Theme.ThemeAccent accent;
public ThemeDocument(TLRPC.TL_themeSettings settings) { public ThemeDocument(TLRPC.ThemeSettings settings) {
themeSettings = settings; themeSettings = settings;
baseTheme = Theme.getTheme(Theme.getBaseThemeKey(settings)); baseTheme = Theme.getTheme(Theme.getBaseThemeKey(settings));
accent = baseTheme.createNewAccent(settings); accent = baseTheme.createNewAccent(settings);

View file

@ -14,7 +14,6 @@ import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.util.LongSparseArray;
import android.util.Pair; import android.util.Pair;
import android.util.SparseArray; import android.util.SparseArray;
@ -24,6 +23,8 @@ import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import androidx.collection.LongSparseArray;
public class DownloadController extends BaseController implements NotificationCenter.NotificationCenterDelegate { public class DownloadController extends BaseController implements NotificationCenter.NotificationCenterDelegate {
public interface FileDownloadProgressListener { public interface FileDownloadProgressListener {
@ -629,7 +630,7 @@ public class DownloadController extends BaseController implements NotificationCe
index = 2; index = 2;
} }
} else { } 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 (ChatObject.isChannel(chat) && chat.megagroup) {
if (message.from_id instanceof TLRPC.TL_peerUser && getContactsController().contactsDict.containsKey(message.from_id.user_id)) { if (message.from_id instanceof TLRPC.TL_peerUser && getContactsController().contactsDict.containsKey(message.from_id.user_id)) {
index = 0; index = 0;

View file

@ -50,6 +50,7 @@ public class Emoji {
public static HashMap<String, String> emojiColor = new HashMap<>(); public static HashMap<String, String> emojiColor = new HashMap<>();
private static boolean recentEmojiLoaded; private static boolean recentEmojiLoaded;
private static Runnable invalidateUiRunnable = () -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.emojiLoaded); private static Runnable invalidateUiRunnable = () -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.emojiLoaded);
public static float emojiDrawingYOffset;
private final static int MAX_RECENT_EMOJI_COUNT = 48; private final static int MAX_RECENT_EMOJI_COUNT = 48;
@ -544,7 +545,16 @@ public class Emoji {
restoreAlpha = true; restoreAlpha = true;
getDrawable().setAlpha(paint.getAlpha()); 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); super.draw(canvas, text, start, end, x, top, y, bottom, paint);
if (needRestore) {
canvas.restore();
}
if (restoreAlpha) { if (restoreAlpha) {
getDrawable().setAlpha(255); getDrawable().setAlpha(255);
} }

View file

@ -529,6 +529,10 @@ public class EmojiData {
return "".equals(emoji); return "".equals(emoji);
} }
public static boolean hasEmojiSupportVibration(String emoji) {
return isHeartEmoji(emoji) || isPeachEmoji(emoji) || isCofinEmoji(emoji);
}
static { static {
for (int a = 0; a < emojiToFE0F.length; a++) { for (int a = 0; a < emojiToFE0F.length; a++) {
emojiToFE0FMap.put(emojiToFE0F[a], true); emojiToFE0FMap.put(emojiToFE0F[a], true);

View file

@ -10,7 +10,6 @@ import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.widget.RemoteViews; import android.widget.RemoteViews;
import org.telegram.ui.FeedWidgetConfigActivity;
import org.telegram.ui.LaunchActivity; import org.telegram.ui.LaunchActivity;
public class FeedWidgetProvider extends AppWidgetProvider { public class FeedWidgetProvider extends AppWidgetProvider {

View file

@ -35,7 +35,6 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N
private ArrayList<MessageObject> messages = new ArrayList<>(); private ArrayList<MessageObject> messages = new ArrayList<>();
private Context mContext; private Context mContext;
private int appWidgetId;
private long dialogId; private long dialogId;
private int classGuid; private int classGuid;
private AccountInstance accountInstance; private AccountInstance accountInstance;
@ -43,7 +42,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N
public FeedRemoteViewsFactory(Context context, Intent intent) { public FeedRemoteViewsFactory(Context context, Intent intent) {
mContext = context; 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); SharedPreferences preferences = context.getSharedPreferences("shortcut_widget", Activity.MODE_PRIVATE);
int accountId = preferences.getInt("account" + appWidgetId, -1); int accountId = preferences.getInt("account" + appWidgetId, -1);
if (accountId >= 0) { if (accountId >= 0) {
@ -107,7 +106,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N
} }
Bundle extras = new Bundle(); Bundle extras = new Bundle();
extras.putInt("chatId", (int) -messageObject.getDialogId()); extras.putLong("chatId", -messageObject.getDialogId());
extras.putInt("message_id", messageObject.getId()); extras.putInt("message_id", messageObject.getId());
extras.putInt("currentAccount", accountInstance.getCurrentAccount()); extras.putInt("currentAccount", accountInstance.getCurrentAccount());
@ -144,7 +143,7 @@ class FeedRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory, N
if (classGuid == 0) { if (classGuid == 0) {
classGuid = ConnectionsManager.generateClassGuid(); 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 { try {
countDownLatch.await(); countDownLatch.await();

View file

@ -71,11 +71,11 @@ public class FileRefController extends BaseController {
public static String getKeyForParentObject(Object parentObject) { public static String getKeyForParentObject(Object parentObject) {
if (parentObject instanceof MessageObject) { if (parentObject instanceof MessageObject) {
MessageObject messageObject = (MessageObject) parentObject; MessageObject messageObject = (MessageObject) parentObject;
int channelId = messageObject.getChannelId(); long channelId = messageObject.getChannelId();
return "message" + messageObject.getRealId() + "_" + channelId + "_" + messageObject.scheduled; return "message" + messageObject.getRealId() + "_" + channelId + "_" + messageObject.scheduled;
} else if (parentObject instanceof TLRPC.Message) { } else if (parentObject instanceof TLRPC.Message) {
TLRPC.Message message = (TLRPC.Message) parentObject; 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; return "message" + message.id + "_" + channelId + "_" + message.from_scheduled;
} else if (parentObject instanceof TLRPC.WebPage) { } else if (parentObject instanceof TLRPC.WebPage) {
TLRPC.WebPage webPage = (TLRPC.WebPage) parentObject; 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) { private void requestReferenceFromServer(Object parentObject, String locationKey, String parentKey, Object[] args) {
if (parentObject instanceof MessageObject) { if (parentObject instanceof MessageObject) {
MessageObject messageObject = (MessageObject) parentObject; MessageObject messageObject = (MessageObject) parentObject;
int channelId = messageObject.getChannelId(); long channelId = messageObject.getChannelId();
if (messageObject.scheduled) { if (messageObject.scheduled) {
TLRPC.TL_messages_getScheduledMessages req = new TLRPC.TL_messages_getScheduledMessages(); 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()); req.id.add(messageObject.getRealId());
getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false)); getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false));
} else if (channelId != 0) { } else if (channelId != 0) {
@ -403,7 +403,7 @@ public class FileRefController extends BaseController {
} }
getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false)); getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false));
} else if (string.startsWith("avatar_")) { } else if (string.startsWith("avatar_")) {
int id = Utilities.parseInt(string); long id = Utilities.parseLong(string);
if (id > 0) { if (id > 0) {
TLRPC.TL_photos_getUserPhotos req = new TLRPC.TL_photos_getUserPhotos(); TLRPC.TL_photos_getUserPhotos req = new TLRPC.TL_photos_getUserPhotos();
req.limit = 80; req.limit = 80;
@ -423,7 +423,7 @@ public class FileRefController extends BaseController {
} else if (string.startsWith("sent_")) { } else if (string.startsWith("sent_")) {
String[] params = string.split("_"); String[] params = string.split("_");
if (params.length == 3) { if (params.length == 3) {
int channelId = Utilities.parseInt(params[1]); long channelId = Utilities.parseLong(params[1]);
if (channelId != 0) { if (channelId != 0) {
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.channel = getMessagesController().getInputChannel(channelId);

View file

@ -22,13 +22,13 @@ public class ForwardingMessagesParams {
public boolean willSeeSenders; public boolean willSeeSenders;
public boolean multiplyUsers; public boolean multiplyUsers;
public ArrayList<TLRPC.TL_pollAnswerVoters> pollChoosenAnswers = new ArrayList(); public ArrayList<TLRPC.TL_pollAnswerVoters> pollChoosenAnswers = new ArrayList<>();
public ForwardingMessagesParams(ArrayList<MessageObject> messages, long newDialogId) { public ForwardingMessagesParams(ArrayList<MessageObject> messages, long newDialogId) {
this.messages = messages; this.messages = messages;
hasCaption = false; hasCaption = false;
hasSenders = false; hasSenders = false;
isSecret = DialogObject.isSecretDialogId(newDialogId); isSecret = DialogObject.isEncryptedDialog(newDialogId);
ArrayList<String> hiddenSendersName = new ArrayList<>(); ArrayList<String> hiddenSendersName = new ArrayList<>();
for (int i = 0; i < messages.size(); i++) { for (int i = 0; i < messages.size(); i++) {
MessageObject messageObject = messages.get(i); MessageObject messageObject = messages.get(i);
@ -53,10 +53,11 @@ public class ForwardingMessagesParams {
message.reply_markup = messageObject.messageOwner.reply_markup; message.reply_markup = messageObject.messageOwner.reply_markup;
message.post = messageObject.messageOwner.post; message.post = messageObject.messageOwner.post;
message.legacy = messageObject.messageOwner.legacy; message.legacy = messageObject.messageOwner.legacy;
message.restriction_reason = messageObject.messageOwner.restriction_reason;
TLRPC.MessageFwdHeader header = null; TLRPC.MessageFwdHeader header = null;
int clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId; long clientUserId = UserConfig.getInstance(messageObject.currentAccount).clientUserId;
if (!isSecret) { if (!isSecret) {
if (messageObject.messageOwner.fwd_from != null) { if (messageObject.messageOwner.fwd_from != null) {
header = messageObject.messageOwner.fwd_from; header = messageObject.messageOwner.fwd_from;
@ -135,10 +136,10 @@ public class ForwardingMessagesParams {
} }
} }
ArrayList<Integer> uids = new ArrayList<>(); ArrayList<Long> uids = new ArrayList<>();
for (int a = 1; a < messages.size(); a++) { for (int a = 0; a < messages.size(); a++) {
MessageObject object = messages.get(a); MessageObject object = messages.get(a);
int uid; long uid;
if (object.isFromUser()) { if (object.isFromUser()) {
uid = object.messageOwner.from_id.user_id; uid = object.messageOwner.from_id.user_id;
} else { } else {

View file

@ -56,7 +56,7 @@ public abstract class FourierTransform {
} }
if (whichAverage == LINAVG) { if (whichAverage == LINAVG) {
int avgWidth = (int) spectrum.length / averages.length; int avgWidth = spectrum.length / averages.length;
for (int i = 0; i < averages.length; i++) { for (int i = 0; i < averages.length; i++) {
float avg = 0; float avg = 0;
int j; int j;
@ -140,15 +140,6 @@ public abstract class FourierTransform {
whichAverage = LOGAVG; 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. * 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; if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1;
// all other cases // all other cases
float fraction = freq / (float) sampleRate; float fraction = freq / (float) sampleRate;
int i = Math.round(timeSize * fraction); return Math.round(timeSize * fraction);
return i;
} }
/** /**

View file

@ -11,7 +11,6 @@ package org.telegram.messenger;
import android.os.SystemClock; import android.os.SystemClock;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Base64; import android.util.Base64;
import android.util.SparseArray;
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage; import com.google.firebase.messaging.RemoteMessage;
@ -28,6 +27,8 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import androidx.collection.LongSparseArray;
public class GcmPushListenerService extends FirebaseMessagingService { public class GcmPushListenerService extends FirebaseMessagingService {
public static final int NOTIFICATION_ID = 1; public static final int NOTIFICATION_ID = 1;
@ -121,11 +122,13 @@ public class GcmPushListenerService extends FirebaseMessagingService {
} else { } else {
userIdObject = null; userIdObject = null;
} }
int accountUserId; long accountUserId;
if (userIdObject == null) { if (userIdObject == null) {
accountUserId = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId(); accountUserId = UserConfig.getInstance(UserConfig.selectedAccount).getClientUserId();
} else { } else {
if (userIdObject instanceof Integer) { if (userIdObject instanceof Long) {
accountUserId = (Long) userIdObject;
} else if (userIdObject instanceof Integer) {
accountUserId = (Integer) userIdObject; accountUserId = (Integer) userIdObject;
} else if (userIdObject instanceof String) { } else if (userIdObject instanceof String) {
accountUserId = Utilities.parseInt((String) userIdObject); accountUserId = Utilities.parseInt((String) userIdObject);
@ -206,31 +209,31 @@ public class GcmPushListenerService extends FirebaseMessagingService {
} }
} }
int channel_id; long channel_id;
int chat_id; long chat_id;
int user_id; long user_id;
long dialogId = 0; long dialogId = 0;
boolean scheduled; boolean scheduled;
if (custom.has("channel_id")) { if (custom.has("channel_id")) {
channel_id = custom.getInt("channel_id"); channel_id = custom.getLong("channel_id");
dialogId = -channel_id; dialogId = -channel_id;
} else { } else {
channel_id = 0; channel_id = 0;
} }
if (custom.has("from_id")) { if (custom.has("from_id")) {
user_id = custom.getInt("from_id"); user_id = custom.getLong("from_id");
dialogId = user_id; dialogId = user_id;
} else { } else {
user_id = 0; user_id = 0;
} }
if (custom.has("chat_id")) { if (custom.has("chat_id")) {
chat_id = custom.getInt("chat_id"); chat_id = custom.getLong("chat_id");
dialogId = -chat_id; dialogId = -chat_id;
} else { } else {
chat_id = 0; chat_id = 0;
} }
if (custom.has("encryption_id")) { if (custom.has("encryption_id")) {
dialogId = ((long) custom.getInt("encryption_id")) << 32; dialogId = DialogObject.makeEncryptedDialogId(custom.getInt("encryption_id"));
} }
if (custom.has("schedule")) { if (custom.has("schedule")) {
scheduled = custom.getInt("schedule") == 1; scheduled = custom.getInt("schedule") == 1;
@ -238,7 +241,7 @@ public class GcmPushListenerService extends FirebaseMessagingService {
scheduled = false; scheduled = false;
} }
if (dialogId == 0 && "ENCRYPTED_MESSAGE".equals(loc_key)) { if (dialogId == 0 && "ENCRYPTED_MESSAGE".equals(loc_key)) {
dialogId = -(1L << 32); dialogId = NotificationsController.globalSecretChatId;
} }
boolean canRelease = true; boolean canRelease = true;
if (dialogId != 0) { if (dialogId != 0) {
@ -269,12 +272,12 @@ public class GcmPushListenerService extends FirebaseMessagingService {
} else if ("MESSAGE_DELETED".equals(loc_key)) { } else if ("MESSAGE_DELETED".equals(loc_key)) {
String messages = custom.getString("messages"); String messages = custom.getString("messages");
String[] messagesArgs = messages.split(","); String[] messagesArgs = messages.split(",");
SparseArray<ArrayList<Integer>> deletedMessages = new SparseArray<>(); LongSparseArray<ArrayList<Integer>> deletedMessages = new LongSparseArray<>();
ArrayList<Integer> ids = new ArrayList<>(); ArrayList<Integer> ids = new ArrayList<>();
for (int a = 0; a < messagesArgs.length; a++) { for (int a = 0; a < messagesArgs.length; a++) {
ids.add(Utilities.parseInt(messagesArgs[a])); ids.add(Utilities.parseInt(messagesArgs[a]));
} }
deletedMessages.put(channel_id, ids); deletedMessages.put(-channel_id, ids);
NotificationsController.getInstance(currentAccount).removeDeletedMessagesFromNotifications(deletedMessages); NotificationsController.getInstance(currentAccount).removeDeletedMessagesFromNotifications(deletedMessages);
MessagesController.getInstance(currentAccount).deleteMessagesByPush(dialogId, ids, channel_id); MessagesController.getInstance(currentAccount).deleteMessagesByPush(dialogId, ids, channel_id);
@ -312,9 +315,9 @@ public class GcmPushListenerService extends FirebaseMessagingService {
} }
} }
if (processNotification) { if (processNotification) {
int chat_from_id = custom.optInt("chat_from_id", 0); long chat_from_id = custom.optLong("chat_from_id", 0);
int chat_from_broadcast_id = custom.optInt("chat_from_broadcast_id", 0); long chat_from_broadcast_id = custom.optLong("chat_from_broadcast_id", 0);
int chat_from_group_id = custom.optInt("chat_from_group_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 isGroup = chat_from_id != 0 || chat_from_group_id != 0;
boolean mention = custom.has("mention") && custom.getInt("mention") != 0; boolean mention = custom.has("mention") && custom.getInt("mention") != 0;

View file

@ -34,7 +34,7 @@ public class GoogleVoiceClientService extends SearchActionVerificationClientServ
if (!TextUtils.isEmpty(text)) { if (!TextUtils.isEmpty(text)) {
String contactUri = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_URI"); 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"); 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); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid);
if (user == null) { if (user == null) {
user = MessagesStorage.getInstance(currentAccount).getUserSync(uid); user = MessagesStorage.getInstance(currentAccount).getUserSync(uid);

View file

@ -77,6 +77,7 @@ public class ImageLoader {
private HashMap<String, Integer> bitmapUseCounts = new HashMap<>(); private HashMap<String, Integer> bitmapUseCounts = new HashMap<>();
private LruCache<BitmapDrawable> memCache; private LruCache<BitmapDrawable> memCache;
private LruCache<BitmapDrawable> wallpaperMemCache;
private LruCache<RLottieDrawable> lottieMemCache; private LruCache<RLottieDrawable> lottieMemCache;
private HashMap<String, CacheImage> imageLoadingByUrl = new HashMap<>(); private HashMap<String, CacheImage> imageLoadingByUrl = new HashMap<>();
private HashMap<String, CacheImage> imageLoadingByKeys = new HashMap<>(); private HashMap<String, CacheImage> imageLoadingByKeys = new HashMap<>();
@ -824,7 +825,11 @@ public class ImageLoader {
h = Math.min(h, 160); h = Math.min(h, 160);
limitFps = true; 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) { if (args.length >= 3) {
@ -1422,15 +1427,21 @@ public class ImageLoader {
toSet = drawable; toSet = drawable;
} else if (drawable instanceof BitmapDrawable) { } else if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
toSet = memCache.get(cacheImage.key); toSet = getFromMemCache(cacheImage.key);
boolean incrementUseCount = true;
if (toSet == null) { 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; toSet = bitmapDrawable;
} else { } else {
Bitmap image = bitmapDrawable.getBitmap(); Bitmap image = bitmapDrawable.getBitmap();
image.recycle(); image.recycle();
} }
if (toSet != null) { if (toSet != null && incrementUseCount) {
incrementUseCount(cacheImage.key); incrementUseCount(cacheImage.key);
decrementKey = 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) { public static Bitmap getStrippedPhotoBitmap(byte[] photoBytes, String filter) {
int len = photoBytes.length - 3 + Bitmaps.header.length + Bitmaps.footer.length; int len = photoBytes.length - 3 + Bitmaps.header.length + Bitmaps.footer.length;
byte[] bytes = bytesLocal.get(); byte[] bytes = bytesLocal.get();
@ -1699,6 +1718,12 @@ public class ImageLoader {
} }
} }
}; };
wallpaperMemCache = new LruCache<BitmapDrawable>(cacheSize / 4) {
@Override
protected int sizeOf(String key, BitmapDrawable value) {
return value.getBitmap().getByteCount();
}
};
lottieMemCache = new LruCache<RLottieDrawable>(512 * 512 * 2 * 4 * 5) { lottieMemCache = new LruCache<RLottieDrawable>(512 * 512 * 2 * 4 * 5) {
@Override @Override
@ -1894,11 +1919,13 @@ public class ImageLoader {
File path = Environment.getExternalStorageDirectory(); File path = Environment.getExternalStorageDirectory();
if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(SharedConfig.storageCacheDir)) { if (Build.VERSION.SDK_INT >= 19 && !TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
ArrayList<File> dirs = AndroidUtilities.getRootDirs(); ArrayList<File> dirs = AndroidUtilities.getRootDirs();
for (int a = 0, N = dirs.size(); a < N; a++) { if (dirs != null) {
File dir = dirs.get(a); for (int a = 0, N = dirs.size(); a < N; a++) {
if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { File dir = dirs.get(a);
path = dir; if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
break; path = dir;
break;
}
} }
} }
} }
@ -1925,15 +1952,13 @@ public class ImageLoader {
}*/ }*/
if (Build.VERSION.SDK_INT >= 19 && !telegramPath.isDirectory()) { if (Build.VERSION.SDK_INT >= 19 && !telegramPath.isDirectory()) {
ArrayList<File> dirs = AndroidUtilities.getDataDirs(); ArrayList<File> dirs = AndroidUtilities.getDataDirs();
if (dirs != null) { for (int a = 0, N = dirs.size(); a < N; a++) {
for (int a = 0, N = dirs.size(); a < N; a++) { File dir = dirs.get(a);
File dir = dirs.get(a); if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
if (dir.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) { path = dir;
path = dir; telegramPath = new File(path, "Telegram");
telegramPath = new File(path, "Telegram"); telegramPath.mkdirs();
telegramPath.mkdirs(); break;
break;
}
} }
} }
} }
@ -2139,7 +2164,7 @@ public class ImageLoader {
if (animated) { if (animated) {
return lottieMemCache.get(key) != null; return lottieMemCache.get(key) != null;
} else { } else {
return memCache.get(key) != null; return getFromMemCache(key) != null;
} }
} }
@ -2233,7 +2258,7 @@ public class ImageLoader {
if (filter != null) { if (filter != null) {
key += "@" + filter; key += "@" + filter;
} }
return memCache.get(key); return getFromMemCache(key);
} }
private void replaceImageInCacheInternal(final String oldKey, final String newKey, final ImageLocation newLocation) { private void replaceImageInCacheInternal(final String oldKey, final String newKey, final ImageLocation newLocation) {
@ -2659,6 +2684,11 @@ public class ImageLoader {
drawable = memCache.get(mediaKey); drawable = memCache.get(mediaKey);
if (drawable != null) { if (drawable != null) {
memCache.moveToFront(mediaKey); memCache.moveToFront(mediaKey);
} else {
drawable = wallpaperMemCache.get(mediaKey);
if (drawable != null) {
wallpaperMemCache.moveToFront(mediaKey);
}
} }
} }
if (drawable != null) { if (drawable != null) {
@ -2680,6 +2710,11 @@ public class ImageLoader {
drawable = memCache.get(imageKey); drawable = memCache.get(imageKey);
if (drawable != null) { if (drawable != null) {
memCache.moveToFront(imageKey); memCache.moveToFront(imageKey);
} else {
drawable = wallpaperMemCache.get(imageKey);
if (drawable != null) {
wallpaperMemCache.moveToFront(imageKey);
}
} }
} }
if (drawable != null) { if (drawable != null) {
@ -2702,6 +2737,11 @@ public class ImageLoader {
drawable = memCache.get(thumbKey); drawable = memCache.get(thumbKey);
if (drawable != null) { if (drawable != null) {
memCache.moveToFront(thumbKey); memCache.moveToFront(thumbKey);
} else {
drawable = wallpaperMemCache.get(thumbKey);
if (drawable != null) {
wallpaperMemCache.moveToFront(thumbKey);
}
} }
} }
if (drawable != null) { if (drawable != null) {
@ -2803,7 +2843,7 @@ public class ImageLoader {
} }
String docExt = FileLoader.getDocumentFileName(object.document); String docExt = FileLoader.getDocumentFileName(object.document);
int idx; int idx;
if (docExt == null || (idx = docExt.lastIndexOf('.')) == -1) { if ((idx = docExt.lastIndexOf('.')) == -1) {
docExt = ""; docExt = "";
} else { } else {
docExt = docExt.substring(idx); docExt = docExt.substring(idx);
@ -2866,6 +2906,10 @@ public class ImageLoader {
thumbKey += "@" + thumbFilter; thumbKey += "@" + thumbFilter;
} }
if (imageReceiver.getUniqKeyPrefix() != null) {
imageKey = imageReceiver.getUniqKeyPrefix() + imageKey;
}
if (imageLocation != null && imageLocation.path != null) { if (imageLocation != null && imageLocation.path != null) {
createLoadOperationForImageReceiver(imageReceiver, thumbKey, thumbUrl, thumbExt, thumbLocation, thumbFilter, 0, 1, ImageReceiver.TYPE_THUMB, thumbSet ? 2 : 1, guid); 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); 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; int thumbCacheType = mediaCacheType == 0 ? 1 : mediaCacheType;
if (!thumbSet) { 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) { if (!imageSet) {
createLoadOperationForImageReceiver(imageReceiver, imageKey, imageUrl, imageExt, imageLocation, imageFilter, 0, imageCacheType, ImageReceiver.TYPE_IMAGE, 0, guid); createLoadOperationForImageReceiver(imageReceiver, imageKey, imageUrl, imageExt, imageLocation, imageFilter, 0, imageCacheType, ImageReceiver.TYPE_IMAGE, 0, guid);

View file

@ -272,6 +272,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private int crossfadeDuration = DEFAULT_CROSSFADE_DURATION; private int crossfadeDuration = DEFAULT_CROSSFADE_DURATION;
private float pressedProgress; private float pressedProgress;
private int animateFromIsPressed; private int animateFromIsPressed;
private String uniqKeyPrefix;
public ImageReceiver() { public ImageReceiver() {
this(null); this(null);
@ -449,6 +450,10 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
imageKey += "@" + imageFilter; imageKey += "@" + imageFilter;
} }
if (uniqKeyPrefix != null) {
imageKey = uniqKeyPrefix + imageKey;
}
String mediaKey = mediaLocation != null ? mediaLocation.getKey(parentObject, null, false) : null; String mediaKey = mediaLocation != null ? mediaLocation.getKey(parentObject, null, false) : null;
if (mediaKey == null && mediaLocation != null) { if (mediaKey == null && mediaLocation != null) {
mediaLocation = null; mediaLocation = null;
@ -1424,12 +1429,15 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
} }
if (thumbDrawable != null) { if (thumbDrawable != null) {
int alpha; int alpha;
if (thumbDrawable instanceof SvgHelper.SvgDrawable) { if (thumbDrawable instanceof SvgHelper.SvgDrawable || thumbDrawable instanceof Emoji.EmojiDrawable) {
alpha = (int) (overrideAlpha * 255 * (1.0f - currentAlpha)); alpha = (int) (overrideAlpha * 255 * (1.0f - currentAlpha));
} else { } else {
alpha = (int) (overrideAlpha * 255); alpha = (int) (overrideAlpha * 255);
} }
drawDrawable(canvas, thumbDrawable, alpha, thumbShaderToUse, thumbOrientation); 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); 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()) { if (currentMediaDrawable instanceof AnimatedFileDrawable && ((AnimatedFileDrawable) currentMediaDrawable).hasBitmap()) {
allowCorssfade = false; allowCorssfade = false;
} else if (currentImageDrawable instanceof RLottieDrawable) { } 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)) { if (allowCorssfade && (currentThumbDrawable == null && staticThumbDrawable == null || currentAlpha == 1.0f || forceCrossfade)) {
currentAlpha = 0.0f; currentAlpha = 0.0f;
@ -2303,4 +2311,12 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
currentAlpha = 0f; currentAlpha = 0f;
updateDrawableRadius(staticThumbDrawable); updateDrawableRadius(staticThumbDrawable);
} }
public void setUniqKeyPrefix(String prefix) {
uniqKeyPrefix = prefix;
}
public String getUniqKeyPrefix() {
return uniqKeyPrefix;
}
} }

View file

@ -21,23 +21,20 @@ public class KeepAliveJob extends JobIntentService {
private static final Object sync = new Object(); private static final Object sync = new Object();
public static void startJob() { public static void startJob() {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.globalQueue.postRunnable(() -> {
@Override if (startingJob || countDownLatch != null) {
public void run() { return;
if (startingJob || countDownLatch != null) { }
return; try {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("starting keep-alive job");
} }
try { synchronized (sync) {
if (BuildVars.LOGS_ENABLED) { startingJob = true;
FileLog.d("starting keep-alive job"); }
} enqueueWork(ApplicationLoader.applicationContext, KeepAliveJob.class, 1000, new Intent());
synchronized (sync) { } catch (Exception ignore) {
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() { public static void finishJob() {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.globalQueue.postRunnable(KeepAliveJob::finishJobInternal);
@Override
public void run() {
finishJobInternal();
}
});
} }
private static Runnable finishJobByTimeoutRunnable = new Runnable() { private static Runnable finishJobByTimeoutRunnable = KeepAliveJob::finishJobInternal;
@Override
public void run() {
finishJobInternal();
}
};
@Override @Override
protected void onHandleWork(Intent intent) { protected void onHandleWork(Intent intent) {

View file

@ -454,7 +454,7 @@ public class LocaleController {
} }
public void checkUpdateForCurrentRemoteLocale(int currentAccount, int version, int baseVersion) { 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; return;
} }
if (currentLocaleInfo.hasBaseLang()) { if (currentLocaleInfo.hasBaseLang()) {
@ -722,10 +722,8 @@ public class LocaleController {
if (remoteLanguagesDict.containsKey(localeInfo.getKey())) { if (remoteLanguagesDict.containsKey(localeInfo.getKey())) {
continue; continue;
} }
if (localeInfo != null) { remoteLanguages.add(localeInfo);
remoteLanguages.add(localeInfo); remoteLanguagesDict.put(localeInfo.getKey(), localeInfo);
remoteLanguagesDict.put(localeInfo.getKey(), localeInfo);
}
} }
} }
locales = preferences.getString("unofficial", null); locales = preferences.getString("unofficial", null);
@ -737,9 +735,7 @@ public class LocaleController {
continue; continue;
} }
localeInfo.shortName = localeInfo.shortName.replace("-", "_"); localeInfo.shortName = localeInfo.shortName.replace("-", "_");
if (localeInfo != null) { unofficialLanguages.add(localeInfo);
unofficialLanguages.add(localeInfo);
}
} }
} }
} }

View file

@ -19,7 +19,6 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock; import android.os.SystemClock;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseIntArray; import android.util.SparseIntArray;
import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.ConnectionResult;
@ -44,6 +43,8 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import androidx.collection.LongSparseArray;
public class LocationController extends BaseController implements NotificationCenter.NotificationCenterDelegate, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public class LocationController extends BaseController implements NotificationCenter.NotificationCenterDelegate, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private LongSparseArray<SharingLocationInfo> sharingLocationsMap = new LongSparseArray<>(); private LongSparseArray<SharingLocationInfo> sharingLocationsMap = new LongSparseArray<>();
@ -214,9 +215,9 @@ public class LocationController extends BaseController implements NotificationCe
messages.add(messageObject.messageOwner); messages.add(messageObject.messageOwner);
} }
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) {
int lowerId = (int) messageObject.getDialogId(); long dialogId = messageObject.getDialogId();
if (lowerId > 0) { if (DialogObject.isUserDialog(dialogId)) {
setProximityLocation(messageObject.getDialogId(), 0, false); setProximityLocation(dialogId, 0, false);
} }
} }
} }
@ -230,11 +231,11 @@ public class LocationController extends BaseController implements NotificationCe
} }
if (!sharingLocationsUI.isEmpty()) { if (!sharingLocationsUI.isEmpty()) {
ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0]; ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
int channelId = (Integer) args[1]; long channelId = (Long) args[1];
ArrayList<Long> toRemove = null; ArrayList<Long> toRemove = null;
for (int a = 0; a < sharingLocationsUI.size(); a++) { for (int a = 0; a < sharingLocationsUI.size(); a++) {
SharingLocationInfo info = sharingLocationsUI.get(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) { if (channelId != messageChannelId) {
continue; continue;
} }
@ -397,7 +398,7 @@ public class LocationController extends BaseController implements NotificationCe
} }
} }
TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); 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.id = info.mid;
req.flags |= 16384; req.flags |= 16384;
req.media = new TLRPC.TL_inputMediaGeoLive(); req.media = new TLRPC.TL_inputMediaGeoLive();
@ -663,8 +664,8 @@ public class LocationController extends BaseController implements NotificationCe
final ArrayList<TLRPC.User> users = new ArrayList<>(); final ArrayList<TLRPC.User> users = new ArrayList<>();
final ArrayList<TLRPC.Chat> chats = new ArrayList<>(); final ArrayList<TLRPC.Chat> chats = new ArrayList<>();
try { try {
ArrayList<Integer> usersToLoad = new ArrayList<>(); ArrayList<Long> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Long> chatsToLoad = new ArrayList<>();
SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT uid, mid, date, period, message, proximity FROM sharing_locations WHERE 1"); SQLiteCursor cursor = getMessagesStorage().getDatabase().queryFinalized("SELECT uid, mid, date, period, message, proximity FROM sharing_locations WHERE 1");
while (cursor.next()) { while (cursor.next()) {
SharingLocationInfo info = new SharingLocationInfo(); SharingLocationInfo info = new SharingLocationInfo();
@ -681,22 +682,14 @@ public class LocationController extends BaseController implements NotificationCe
data.reuse(); data.reuse();
} }
result.add(info); result.add(info);
int lower_id = (int) info.did; if (DialogObject.isChatDialog(info.did)) {
int high_id = (int) (info.did >> 32); if (!chatsToLoad.contains(-info.did)) {
if (lower_id != 0) { chatsToLoad.add(-info.did);
if (lower_id < 0) { }
if (!chatsToLoad.contains(-lower_id)) { } else if (DialogObject.isUserDialog(info.did)) {
chatsToLoad.add(-lower_id); if (!usersToLoad.contains(info.did)) {
} usersToLoad.add(info.did);
} else {
if (!usersToLoad.contains(lower_id)) {
usersToLoad.add(lower_id);
}
} }
} else {
/*if (!encryptedChatIds.contains(high_id)) {
encryptedChatIds.add(high_id);
}*/
} }
} }
cursor.dispose(); cursor.dispose();
@ -777,7 +770,7 @@ public class LocationController extends BaseController implements NotificationCe
sharingLocationsMap.remove(did); sharingLocationsMap.remove(did);
if (info != null) { if (info != null) {
TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); 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.id = info.mid;
req.flags |= 16384; req.flags |= 16384;
req.media = new TLRPC.TL_inputMediaGeoLive(); 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++) { for (int a = 0; a < sharingLocations.size(); a++) {
SharingLocationInfo info = sharingLocations.get(a); SharingLocationInfo info = sharingLocations.get(a);
TLRPC.TL_messages_editMessage req = new TLRPC.TL_messages_editMessage(); 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.id = info.mid;
req.flags |= 16384; req.flags |= 16384;
req.media = new TLRPC.TL_inputMediaGeoLive(); req.media = new TLRPC.TL_inputMediaGeoLive();
@ -947,13 +940,13 @@ public class LocationController extends BaseController implements NotificationCe
return lastKnownLocation; return lastKnownLocation;
} }
public void loadLiveLocations(final long did) { public void loadLiveLocations(long did) {
if (cacheRequests.indexOfKey(did) >= 0) { if (cacheRequests.indexOfKey(did) >= 0) {
return; return;
} }
cacheRequests.put(did, true); cacheRequests.put(did, true);
TLRPC.TL_messages_getRecentLocations req = new TLRPC.TL_messages_getRecentLocations(); TLRPC.TL_messages_getRecentLocations req = new TLRPC.TL_messages_getRecentLocations();
req.peer = getMessagesController().getInputPeer((int) did); req.peer = getMessagesController().getInputPeer(did);
req.limit = 100; req.limit = 100;
getConnectionsManager().sendRequest(req, (response, error) -> { getConnectionsManager().sendRequest(req, (response, error) -> {
if (error != null) { if (error != null) {
@ -978,8 +971,7 @@ public class LocationController extends BaseController implements NotificationCe
} }
public void markLiveLoactionsAsRead(long dialogId) { public void markLiveLoactionsAsRead(long dialogId) {
int lowerId = (int) dialogId; if (DialogObject.isEncryptedDialog(dialogId)) {
if (lowerId == 0) {
return; return;
} }
ArrayList<TLRPC.Message> messages = locationsCache.get(dialogId); ArrayList<TLRPC.Message> messages = locationsCache.get(dialogId);
@ -993,12 +985,12 @@ public class LocationController extends BaseController implements NotificationCe
} }
lastReadLocationTime.put(dialogId, currentDate); lastReadLocationTime.put(dialogId, currentDate);
TLObject request; 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(); TLRPC.TL_channels_readMessageContents req = new TLRPC.TL_channels_readMessageContents();
for (int a = 0, N = messages.size(); a < N; a++) { for (int a = 0, N = messages.size(); a < N; a++) {
req.id.add(messages.get(a).id); req.id.add(messages.get(a).id);
} }
req.channel = getMessagesController().getInputChannel(-lowerId); req.channel = getMessagesController().getInputChannel(-dialogId);
request = req; request = req;
} else { } else {
TLRPC.TL_messages_readMessageContents req = new TLRPC.TL_messages_readMessageContents(); TLRPC.TL_messages_readMessageContents req = new TLRPC.TL_messages_readMessageContents();

View file

@ -97,14 +97,14 @@ public class LocationSharingService extends Service implements NotificationCente
String str; String str;
if (infos.size() == 1) { if (infos.size() == 1) {
LocationController.SharingLocationInfo info = infos.get(0); LocationController.SharingLocationInfo info = infos.get(0);
int lower_id = (int) info.messageObject.getDialogId(); long dialogId = info.messageObject.getDialogId();
int currentAccount = info.messageObject.currentAccount; int currentAccount = info.messageObject.currentAccount;
if (lower_id > 0) { if (DialogObject.isUserDialog(dialogId)) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(lower_id); TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(dialogId);
param = UserObject.getFirstName(user); param = UserObject.getFirstName(user);
str = LocaleController.getString("AttachLiveLocationIsSharing", R.string.AttachLiveLocationIsSharing); str = LocaleController.getString("AttachLiveLocationIsSharing", R.string.AttachLiveLocationIsSharing);
} else { } else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-lower_id); TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
if (chat != null) { if (chat != null) {
param = chat.title; param = chat.title;
} else { } else {

View file

@ -624,28 +624,26 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
final double amplitude = Math.sqrt(sum / len / 2); final double amplitude = Math.sqrt(sum / len / 2);
final ByteBuffer finalBuffer = buffer; final ByteBuffer finalBuffer = buffer;
final boolean flush = len != buffer.capacity(); final boolean flush = len != buffer.capacity();
if (len != 0) { fileEncodingQueue.postRunnable(() -> {
fileEncodingQueue.postRunnable(() -> { while (finalBuffer.hasRemaining()) {
while (finalBuffer.hasRemaining()) { int oldLimit = -1;
int oldLimit = -1; if (finalBuffer.remaining() > fileBuffer.remaining()) {
if (finalBuffer.remaining() > fileBuffer.remaining()) { oldLimit = finalBuffer.limit();
oldLimit = finalBuffer.limit(); finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position());
finalBuffer.limit(fileBuffer.remaining() + finalBuffer.position()); }
} fileBuffer.put(finalBuffer);
fileBuffer.put(finalBuffer); if (fileBuffer.position() == fileBuffer.limit() || flush) {
if (fileBuffer.position() == fileBuffer.limit() || flush) { if (writeFrame(fileBuffer, !flush ? fileBuffer.limit() : finalBuffer.position()) != 0) {
if (writeFrame(fileBuffer, !flush ? fileBuffer.limit() : finalBuffer.position()) != 0) { fileBuffer.rewind();
fileBuffer.rewind(); recordTimeCount += fileBuffer.limit() / 2 / (sampleRate / 1000);
recordTimeCount += fileBuffer.limit() / 2 / (sampleRate / 1000);
}
}
if (oldLimit != -1) {
finalBuffer.limit(oldLimit);
} }
} }
recordQueue.postRunnable(() -> recordBuffers.add(finalBuffer)); if (oldLimit != -1) {
}); finalBuffer.limit(oldLimit);
} }
}
recordQueue.postRunnable(() -> recordBuffers.add(finalBuffer));
});
recordQueue.postRunnable(recordRunnable); recordQueue.postRunnable(recordRunnable);
AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordProgressChanged, recordingGuid, amplitude)); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getInstance(recordingCurrentAccount).postNotificationName(NotificationCenter.recordProgressChanged, recordingGuid, amplitude));
} else { } else {
@ -1046,7 +1044,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public void run() { public void run() {
synchronized (sync) { synchronized (sync) {
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
if (currentPlayingMessageObject != null && (audioPlayer != null || videoPlayer != null) && !isPaused) { if ((audioPlayer != null || videoPlayer != null) && !isPaused) {
try { try {
long duration; long duration;
long progress; long progress;
@ -1059,7 +1057,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
return; return;
} }
bufferedValue = videoPlayer.getBufferedPosition() / (float) duration; bufferedValue = videoPlayer.getBufferedPosition() / (float) duration;
value = duration >= 0 ? progress / (float) duration : 0.0f; value = progress / (float) duration;
if (value >= 1) { if (value >= 1) {
return; return;
} }
@ -1286,7 +1284,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
if (scheduled) { if (scheduled) {
return; return;
} }
int channelId = (Integer) args[1]; long channelId = (Long) args[1];
ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0]; ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
if (playingMessageObject != null) { if (playingMessageObject != null) {
if (channelId == playingMessageObject.messageOwner.peer_id.channel_id) { if (channelId == playingMessageObject.messageOwner.peer_id.channel_id) {
@ -1343,7 +1341,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
int type = (Integer) args[4]; int type = (Integer) args[4];
ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[2]; ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[2];
boolean enc = ((int) did) == 0; boolean enc = DialogObject.isEncryptedDialog(did);
int loadIndex = did == playlistMergeDialogId ? 1 : 0; int loadIndex = did == playlistMergeDialogId ? 1 : 0;
if (!arr.isEmpty()) { if (!arr.isEmpty()) {
playlistEndReached[loadIndex] = (Boolean) args[5]; playlistEndReached[loadIndex] = (Boolean) args[5];
@ -1360,11 +1358,9 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
playlistMaxId[loadIndex] = Math.min(playlistMaxId[loadIndex], message.getId()); playlistMaxId[loadIndex] = Math.min(playlistMaxId[loadIndex], message.getId());
} }
sortPlaylist(); sortPlaylist();
if (playingMessageObject != null) { int newIndex = playlist.indexOf(playingMessageObject);
int newIndex = playlist.indexOf(playingMessageObject); if (newIndex >= 0) {
if (newIndex >= 0) { currentPlaylistNum = newIndex;
currentPlaylistNum = newIndex;
}
} }
loadingPlaylist = false; loadingPlaylist = false;
if (SharedConfig.shuffleMusic) { if (SharedConfig.shuffleMusic) {
@ -1848,7 +1844,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, true); NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, true);
} else { } else {
long position = videoPlayer.getCurrentPosition(); 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; playingMessageObject.audioProgressMs = (int) position;
NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, false); NotificationCenter.getInstance(playingMessageObject.currentAccount).postNotificationName(NotificationCenter.messagePlayingGoingToStop, playingMessageObject, false);
} }
@ -2004,7 +2000,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
} }
public void loadMoreMusic() { 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; return;
} }
if (playlistGlobalSearchParams != null) { if (playlistGlobalSearchParams != null) {
@ -2037,7 +2033,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
req.offset_rate = playlistGlobalSearchParams.nextSearchRate; req.offset_rate = playlistGlobalSearchParams.nextSearchRate;
req.flags |= 1; req.flags |= 1;
req.folder_id = playlistGlobalSearchParams.folderId; req.folder_id = playlistGlobalSearchParams.folderId;
int id; long id;
if (lastMessage.messageOwner.peer_id.channel_id != 0) { if (lastMessage.messageOwner.peer_id.channel_id != 0) {
id = -lastMessage.messageOwner.peer_id.channel_id; id = -lastMessage.messageOwner.peer_id.channel_id;
} else if (lastMessage.messageOwner.peer_id.chat_id != 0) { } else if (lastMessage.messageOwner.peer_id.chat_id != 0) {
@ -2123,19 +2119,19 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
playMusicAgain = !playlist.isEmpty(); playMusicAgain = !playlist.isEmpty();
clearPlaylist(); clearPlaylist();
playlistGlobalSearchParams = params; playlistGlobalSearchParams = params;
boolean isSecretChat = !messageObjects.isEmpty() && (int) messageObjects.get(0).getDialogId() == 0; boolean isSecretChat = !messageObjects.isEmpty() && DialogObject.isEncryptedDialog(messageObjects.get(0).getDialogId());
long minId = Long.MAX_VALUE; int minId = Integer.MAX_VALUE;
long maxId = Long.MIN_VALUE; int maxId = Integer.MIN_VALUE;
for (int a = messageObjects.size() - 1; a >= 0; a--) { for (int a = messageObjects.size() - 1; a >= 0; a--) {
MessageObject messageObject = messageObjects.get(a); MessageObject messageObject = messageObjects.get(a);
if (messageObject.isMusic()) { if (messageObject.isMusic()) {
long id = messageObject.getIdWithChannel(); int id = messageObject.getId();
if (id > 0 || isSecretChat) { if (id > 0 || isSecretChat) {
minId = Math.min(minId, id); minId = Math.min(minId, id);
maxId = Math.max(maxId, id); maxId = Math.max(maxId, id);
} }
playlist.add(messageObject); playlist.add(messageObject);
playlistMap.put(messageObject.getId(), messageObject); playlistMap.put(id, messageObject);
} }
} }
sortPlaylist(); sortPlaylist();
@ -2244,7 +2240,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
} }
audioPlayer = null; audioPlayer = null;
Theme.unrefAudioVisualizeDrawable(playingMessageObject); Theme.unrefAudioVisualizeDrawable(playingMessageObject);
} else if (videoPlayer != null) { } else {
currentAspectRatioFrameLayout = null; currentAspectRatioFrameLayout = null;
currentTextureViewContainer = null; currentTextureViewContainer = null;
currentAspectRatioFrameLayoutReady = false; currentAspectRatioFrameLayoutReady = false;
@ -2301,7 +2297,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
currentPlaylistNum = 0; currentPlaylistNum = 0;
} }
} }
if (currentPlaylistNum < 0 || currentPlaylistNum >= currentPlayList.size()) { if (currentPlaylistNum >= currentPlayList.size()) {
return; return;
} }
playMusicAgain = true; playMusicAgain = true;
@ -2328,8 +2324,8 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
} }
} }
final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner); final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner);
boolean exist = cacheFile != null && cacheFile.exists(); boolean exist = cacheFile.exists();
if (cacheFile != null && cacheFile != file && !cacheFile.exists()) { if (cacheFile != file && !cacheFile.exists()) {
FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, 0, 0); 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); final File cacheFile = file != null ? file : FileLoader.getPathToMessage(nextAudio.messageOwner);
boolean exist = cacheFile != null && cacheFile.exists(); boolean exist = cacheFile.exists();
if (cacheFile != null && cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) { if (cacheFile != file && !cacheFile.exists() && nextAudio.isMusic()) {
FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, 0, 0); FileLoader.getInstance(currentAccount).loadFile(nextAudio.getDocument(), nextAudio, 0, 0);
} }
} }
@ -2419,7 +2415,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
pipSwitchingState = 2; pipSwitchingState = 2;
pipRoundVideoView.close(true); pipRoundVideoView.close(true);
pipRoundVideoView = null; pipRoundVideoView = null;
} else if (currentAspectRatioFrameLayout != null) { } else {
if (currentAspectRatioFrameLayout.getParent() == null) { if (currentAspectRatioFrameLayout.getParent() == null) {
currentTextureViewContainer.addView(currentAspectRatioFrameLayout); currentTextureViewContainer.addView(currentAspectRatioFrameLayout);
} }
@ -2469,9 +2465,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
currentAspectRatioFrameLayout = aspectRatioFrameLayout; currentAspectRatioFrameLayout = aspectRatioFrameLayout;
currentTextureViewContainer = container; currentTextureViewContainer = container;
if (currentAspectRatioFrameLayoutReady && currentAspectRatioFrameLayout != null) { if (currentAspectRatioFrameLayoutReady && currentAspectRatioFrameLayout != null) {
if (currentAspectRatioFrameLayout != null) { currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation);
currentAspectRatioFrameLayout.setAspectRatio(currentAspectRatioFrameLayoutRatio, currentAspectRatioFrameLayoutRotation);
}
//if (currentTextureViewContainer.getVisibility() != View.VISIBLE) { //if (currentTextureViewContainer.getVisibility() != View.VISIBLE) {
// currentTextureViewContainer.setVisibility(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); 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; boolean canStream = SharedConfig.streamMedia && (messageObject.isMusic() || messageObject.isRoundVideo() || messageObject.isVideo() && messageObject.canStreamVideo()) && !DialogObject.isEncryptedDialog(messageObject.getDialogId());
if (cacheFile != null && cacheFile != file && !(exists = cacheFile.exists()) && !canStream) { if (cacheFile != file && !(exists = cacheFile.exists()) && !canStream) {
FileLoader.getInstance(messageObject.currentAccount).loadFile(messageObject.getDocument(), messageObject, 0, 0); FileLoader.getInstance(messageObject.currentAccount).loadFile(messageObject.getDocument(), messageObject, 0, 0);
downloadingCurrentMessage = true; downloadingCurrentMessage = true;
isPaused = false; isPaused = false;
@ -3057,7 +3051,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
if (!playlist.isEmpty() && (playlist.size() > 1 || !messageObject.isVoice())) { if (!playlist.isEmpty() && (playlist.size() > 1 || !messageObject.isVoice())) {
playNextMessageWithoutOrder(true); playNextMessageWithoutOrder(true);
} else { } 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)) { } else if (audioPlayer != null && seekToProgressPending != 0 && (playbackState == ExoPlayer.STATE_READY || playbackState == ExoPlayer.STATE_IDLE)) {
int seekTo = (int) (audioPlayer.getDuration() * seekToProgressPending); int seekTo = (int) (audioPlayer.getDuration() * seekToProgressPending);
@ -4074,11 +4068,9 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
byte[] header = new byte[12]; byte[] header = new byte[12];
if (inputStream.read(header, 0, 12) == 12) { if (inputStream.read(header, 0, 12) == 12) {
String str = new String(header); String str = new String(header);
if (str != null) { str = str.toLowerCase();
str = str.toLowerCase(); if (str.startsWith("riff") && str.endsWith("webp")) {
if (str.startsWith("riff") && str.endsWith("webp")) { return true;
return true;
}
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -4102,7 +4094,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
byte[] header = new byte[3]; byte[] header = new byte[3];
if (inputStream.read(header, 0, 3) == 3) { if (inputStream.read(header, 0, 3) == 3) {
String str = new String(header); String str = new String(header);
if (str != null && str.equalsIgnoreCase("gif")) { if (str.equalsIgnoreCase("gif")) {
return true; return true;
} }
} }
@ -4322,7 +4314,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
} }
try { 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"); 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) { if (cursor != null) {
int imageIdColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID); int imageIdColumn = cursor.getColumnIndex(MediaStore.Video.Media._ID);
@ -4672,7 +4664,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
int framerate = info.framerate; int framerate = info.framerate;
int bitrate = info.bitrate; int bitrate = info.bitrate;
int originalBitrate = info.originalBitrate; int originalBitrate = info.originalBitrate;
boolean isSecret = ((int) messageObject.getDialogId()) == 0; boolean isSecret = DialogObject.isEncryptedDialog(messageObject.getDialogId());
final File cacheFile = new File(messageObject.messageOwner.attachPath); final File cacheFile = new File(messageObject.messageOwner.attachPath);
if (cacheFile.exists()) { if (cacheFile.exists()) {
cacheFile.delete(); cacheFile.delete();
@ -4800,7 +4792,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
compressFactor = 1f; compressFactor = 1f;
minCompressFactor = 1f; minCompressFactor = 1f;
} else if (Math.min(height, width) >= 720) { } else if (Math.min(height, width) >= 720) {
maxBitrate = 2621_440; maxBitrate = 3200_000;
compressFactor = 1f; compressFactor = 1f;
minCompressFactor = 1f; minCompressFactor = 1f;
} else if (Math.min(height, width) >= 480) { } else if (Math.min(height, width) >= 480) {
@ -4836,7 +4828,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public static class PlaylistGlobalSearchParams { public static class PlaylistGlobalSearchParams {
final String query; final String query;
final FiltersView.MediaFilterData filter; final FiltersView.MediaFilterData filter;
final int dialogId; final long dialogId;
final long minDate; final long minDate;
final long maxDate; final long maxDate;
public int totalCount; public int totalCount;
@ -4844,7 +4836,7 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
public int nextSearchRate; public int nextSearchRate;
public int folderId; 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.filter = filter;
this.query = query; this.query = query;
this.dialogId = dialogId; this.dialogId = dialogId;

View file

@ -24,7 +24,6 @@ import android.text.style.ClickableSpan;
import android.text.style.URLSpan; import android.text.style.URLSpan;
import android.text.util.Linkify; import android.text.util.Linkify;
import android.util.Base64; import android.util.Base64;
import android.util.SparseArray;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.browser.Browser; import org.telegram.messenger.browser.Browser;
@ -58,6 +57,8 @@ import java.util.HashMap;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import androidx.collection.LongSparseArray;
public class MessageObject { public class MessageObject {
public static final int MESSAGE_SEND_STATE_SENT = 0; public static final int MESSAGE_SEND_STATE_SENT = 0;
@ -875,11 +876,11 @@ public class MessageObject {
localEdit = edit; localEdit = edit;
} }
public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users, boolean generateLayout, boolean checkMediaExists) { public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Long, TLRPC.User> users, boolean generateLayout, boolean checkMediaExists) {
this(accountNum, message, users, null, generateLayout, checkMediaExists); this(accountNum, message, users, null, generateLayout, checkMediaExists);
} }
public MessageObject(int accountNum, TLRPC.Message message, SparseArray<TLRPC.User> users, boolean generateLayout, boolean checkMediaExists) { public MessageObject(int accountNum, TLRPC.Message message, LongSparseArray<TLRPC.User> users, boolean generateLayout, boolean checkMediaExists) {
this(accountNum, message, users, null, generateLayout, 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); this(accountNum, message, replyToMessage, null, null, null, null, generateLayout, checkMediaExists, 0);
} }
public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users, AbstractMap<Integer, TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists) { public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Long, TLRPC.User> users, AbstractMap<Long, TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists) {
this(accountNum, message, users, chats, generateLayout, checkMediaExists, 0); this(accountNum, message, users, chats, generateLayout, checkMediaExists, 0);
} }
public MessageObject(int accountNum, TLRPC.Message message, SparseArray<TLRPC.User> users, SparseArray<TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists) { public MessageObject(int accountNum, TLRPC.Message message, LongSparseArray<TLRPC.User> users, LongSparseArray<TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists) {
this(accountNum, message, null, null, null, users, chats, generateLayout, checkMediaExists, 0); this(accountNum, message, null, null, null, users, chats, generateLayout, checkMediaExists, 0);
} }
public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users, AbstractMap<Integer, TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists, long eid) { public MessageObject(int accountNum, TLRPC.Message message, AbstractMap<Long, TLRPC.User> users, AbstractMap<Long, TLRPC.Chat> chats, boolean generateLayout, boolean checkMediaExists, long eid) {
this(accountNum, message, null, users, chats, null, null, generateLayout, checkMediaExists, eid); this(accountNum, message, null, users, chats, null, null, generateLayout, checkMediaExists, eid);
} }
public MessageObject(int accountNum, TLRPC.Message message, MessageObject replyToMessage, AbstractMap<Integer, TLRPC.User> users, AbstractMap<Integer, TLRPC.Chat> chats, SparseArray<TLRPC.User> sUsers, SparseArray<TLRPC.Chat> sChats, boolean generateLayout, boolean checkMediaExists, long eid) { public MessageObject(int accountNum, TLRPC.Message message, MessageObject replyToMessage, AbstractMap<Long, TLRPC.User> users, AbstractMap<Long, TLRPC.Chat> chats, LongSparseArray<TLRPC.User> sUsers, LongSparseArray<TLRPC.Chat> sChats, boolean generateLayout, boolean checkMediaExists, long eid) {
Theme.createCommonMessageResources(); Theme.createCommonMessageResources();
currentAccount = accountNum; currentAccount = accountNum;
@ -1149,7 +1150,7 @@ public class MessageObject {
TLRPC.TL_channelAdminLogEventActionParticipantInvite action = (TLRPC.TL_channelAdminLogEventActionParticipantInvite) event.action; TLRPC.TL_channelAdminLogEventActionParticipantInvite action = (TLRPC.TL_channelAdminLogEventActionParticipantInvite) event.action;
messageOwner = new TLRPC.TL_messageService(); messageOwner = new TLRPC.TL_messageService();
messageOwner.action = new TLRPC.TL_messageActionChatAddUser(); messageOwner.action = new TLRPC.TL_messageActionChatAddUser();
int peerId = getPeerId(action.participant.peer); long peerId = getPeerId(action.participant.peer);
TLObject whoUser; TLObject whoUser;
if (peerId > 0) { if (peerId > 0) {
whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); whoUser = MessagesController.getInstance(currentAccount).getUser(peerId);
@ -1180,7 +1181,7 @@ public class MessageObject {
new_participant = action.new_participant; new_participant = action.new_participant;
} }
messageOwner = new TLRPC.TL_message(); messageOwner = new TLRPC.TL_message();
int peerId = MessageObject.getPeerId(prev_participant.peer); long peerId = MessageObject.getPeerId(prev_participant.peer);
TLObject whoUser; TLObject whoUser;
if (peerId > 0) { if (peerId > 0) {
whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); whoUser = MessagesController.getInstance(currentAccount).getUser(peerId);
@ -1347,7 +1348,7 @@ public class MessageObject {
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) {
TLRPC.TL_channelAdminLogEventActionParticipantToggleBan action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) event.action; TLRPC.TL_channelAdminLogEventActionParticipantToggleBan action = (TLRPC.TL_channelAdminLogEventActionParticipantToggleBan) event.action;
messageOwner = new TLRPC.TL_message(); messageOwner = new TLRPC.TL_message();
int peerId = getPeerId(action.prev_participant.peer); long peerId = getPeerId(action.prev_participant.peer);
TLObject whoUser; TLObject whoUser;
if (peerId > 0) { if (peerId > 0) {
whoUser = MessagesController.getInstance(currentAccount).getUser(peerId); whoUser = MessagesController.getInstance(currentAccount).getUser(peerId);
@ -1534,8 +1535,8 @@ public class MessageObject {
message = ((TLRPC.TL_channelAdminLogEventActionDeleteMessage) event.action).message; message = ((TLRPC.TL_channelAdminLogEventActionDeleteMessage) event.action).message;
messageText = replaceWithLink(LocaleController.getString("EventLogDeletedMessages", R.string.EventLogDeletedMessages), "un1", fromUser); messageText = replaceWithLink(LocaleController.getString("EventLogDeletedMessages", R.string.EventLogDeletedMessages), "un1", fromUser);
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) {
int newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value; long newChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).new_value;
int oldChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).prev_value; long oldChatId = ((TLRPC.TL_channelAdminLogEventActionChangeLinkedChat) event.action).prev_value;
if (chat.megagroup) { if (chat.megagroup) {
if (newChatId == 0) { if (newChatId == 0) {
TLRPC.Chat oldChat = MessagesController.getInstance(currentAccount).getChat(oldChatId); TLRPC.Chat oldChat = MessagesController.getInstance(currentAccount).getChat(oldChatId);
@ -1749,7 +1750,7 @@ public class MessageObject {
} }
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantMute) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantMute) {
TLRPC.TL_channelAdminLogEventActionParticipantMute action = (TLRPC.TL_channelAdminLogEventActionParticipantMute) event.action; TLRPC.TL_channelAdminLogEventActionParticipantMute action = (TLRPC.TL_channelAdminLogEventActionParticipantMute) event.action;
int id = getPeerId(action.participant.peer); long id = getPeerId(action.participant.peer);
TLObject object; TLObject object;
if (id > 0) { if (id > 0) {
object = MessagesController.getInstance(currentAccount).getUser(id); object = MessagesController.getInstance(currentAccount).getUser(id);
@ -1760,7 +1761,7 @@ public class MessageObject {
messageText = replaceWithLink(messageText, "un2", object); messageText = replaceWithLink(messageText, "un2", object);
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantUnmute) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantUnmute) {
TLRPC.TL_channelAdminLogEventActionParticipantUnmute action = (TLRPC.TL_channelAdminLogEventActionParticipantUnmute) event.action; TLRPC.TL_channelAdminLogEventActionParticipantUnmute action = (TLRPC.TL_channelAdminLogEventActionParticipantUnmute) event.action;
int id = getPeerId(action.participant.peer); long id = getPeerId(action.participant.peer);
TLObject object; TLObject object;
if (id > 0) { if (id > 0) {
object = MessagesController.getInstance(currentAccount).getUser(id); object = MessagesController.getInstance(currentAccount).getUser(id);
@ -1798,7 +1799,7 @@ public class MessageObject {
messageText = replaceWithLink(messageText, "un3", action.new_invite); messageText = replaceWithLink(messageText, "un3", action.new_invite);
} else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantVolume) { } else if (event.action instanceof TLRPC.TL_channelAdminLogEventActionParticipantVolume) {
TLRPC.TL_channelAdminLogEventActionParticipantVolume action = (TLRPC.TL_channelAdminLogEventActionParticipantVolume) event.action; TLRPC.TL_channelAdminLogEventActionParticipantVolume action = (TLRPC.TL_channelAdminLogEventActionParticipantVolume) event.action;
int id = getPeerId(action.participant.peer); long id = getPeerId(action.participant.peer);
TLObject object; TLObject object;
if (id > 0) { if (id > 0) {
object = MessagesController.getInstance(currentAccount).getUser(id); object = MessagesController.getInstance(currentAccount).getUser(id);
@ -1919,7 +1920,7 @@ public class MessageObject {
private String getUserName(TLObject object, ArrayList<TLRPC.MessageEntity> entities, int offset) { private String getUserName(TLObject object, ArrayList<TLRPC.MessageEntity> entities, int offset) {
String name; String name;
String username; String username;
int id; long id;
if (object == null) { if (object == null) {
name = ""; name = "";
username = null; username = null;
@ -2021,7 +2022,7 @@ public class MessageObject {
public void generatePaymentSentMessageText(TLRPC.User fromUser) { public void generatePaymentSentMessageText(TLRPC.User fromUser) {
if (fromUser == null) { if (fromUser == null) {
fromUser = MessagesController.getInstance(currentAccount).getUser((int) getDialogId()); fromUser = MessagesController.getInstance(currentAccount).getUser(getDialogId());
} }
String name; String name;
if (fromUser != null) { if (fromUser != null) {
@ -2062,7 +2063,7 @@ public class MessageObject {
messageText = replaceWithLink(LocaleController.getString("ActionPinnedVoice", R.string.ActionPinnedVoice), "un1", fromUser != null ? fromUser : chat); messageText = replaceWithLink(LocaleController.getString("ActionPinnedVoice", R.string.ActionPinnedVoice), "un1", fromUser != null ? fromUser : chat);
} else if (replyMessageObject.isRoundVideo()) { } else if (replyMessageObject.isRoundVideo()) {
messageText = replaceWithLink(LocaleController.getString("ActionPinnedRound", R.string.ActionPinnedRound), "un1", fromUser != null ? fromUser : chat); 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); messageText = replaceWithLink(LocaleController.getString("ActionPinnedSticker", R.string.ActionPinnedSticker), "un1", fromUser != null ? fromUser : chat);
} else if (replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { } else if (replyMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
messageText = replaceWithLink(LocaleController.getString("ActionPinnedFile", R.string.ActionPinnedFile), "un1", fromUser != null ? fromUser : chat); messageText = replaceWithLink(LocaleController.getString("ActionPinnedFile", R.string.ActionPinnedFile), "un1", fromUser != null ? fromUser : chat);
@ -2464,33 +2465,33 @@ public class MessageObject {
return localType != 0; return localType != 0;
} }
private TLRPC.User getUser(AbstractMap<Integer, TLRPC.User> users, SparseArray<TLRPC.User> sUsers, int uid) { private TLRPC.User getUser(AbstractMap<Long, TLRPC.User> users, LongSparseArray<TLRPC.User> sUsers, long userId) {
TLRPC.User user = null; TLRPC.User user = null;
if (users != null) { if (users != null) {
user = users.get(uid); user = users.get(userId);
} else if (sUsers != null) { } else if (sUsers != null) {
user = sUsers.get(uid); user = sUsers.get(userId);
} }
if (user == null) { if (user == null) {
user = MessagesController.getInstance(currentAccount).getUser(uid); user = MessagesController.getInstance(currentAccount).getUser(userId);
} }
return user; return user;
} }
private TLRPC.Chat getChat(AbstractMap<Integer, TLRPC.Chat> chats, SparseArray<TLRPC.Chat> sChats, int cid) { private TLRPC.Chat getChat(AbstractMap<Long, TLRPC.Chat> chats, LongSparseArray<TLRPC.Chat> sChats, long chatId) {
TLRPC.Chat chat = null; TLRPC.Chat chat = null;
if (chats != null) { if (chats != null) {
chat = chats.get(cid); chat = chats.get(chatId);
} else if (sChats != null) { } else if (sChats != null) {
chat = sChats.get(cid); chat = sChats.get(chatId);
} }
if (chat == null) { if (chat == null) {
chat = MessagesController.getInstance(currentAccount).getChat(cid); chat = MessagesController.getInstance(currentAccount).getChat(chatId);
} }
return chat; return chat;
} }
private void updateMessageText(AbstractMap<Integer, TLRPC.User> users, AbstractMap<Integer, TLRPC.Chat> chats, SparseArray<TLRPC.User> sUsers, SparseArray<TLRPC.Chat> sChats) { private void updateMessageText(AbstractMap<Long, TLRPC.User> users, AbstractMap<Long, TLRPC.Chat> chats, LongSparseArray<TLRPC.User> sUsers, LongSparseArray<TLRPC.Chat> sChats) {
TLRPC.User fromUser = null; TLRPC.User fromUser = null;
TLRPC.Chat fromChat = null; TLRPC.Chat fromChat = null;
if (messageOwner.from_id instanceof TLRPC.TL_peerUser) { if (messageOwner.from_id instanceof TLRPC.TL_peerUser) {
@ -2550,7 +2551,7 @@ public class MessageObject {
} }
} }
} else if (messageOwner.action instanceof TLRPC.TL_messageActionInviteToGroupCall) { } 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) { if (singleUserId == 0 && messageOwner.action.users.size() == 1) {
singleUserId = messageOwner.action.users.get(0); singleUserId = messageOwner.action.users.get(0);
} }
@ -2575,15 +2576,15 @@ public class MessageObject {
} }
} else if (messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) { } else if (messageOwner.action instanceof TLRPC.TL_messageActionGeoProximityReached) {
TLRPC.TL_messageActionGeoProximityReached action = (TLRPC.TL_messageActionGeoProximityReached) messageOwner.action; TLRPC.TL_messageActionGeoProximityReached action = (TLRPC.TL_messageActionGeoProximityReached) messageOwner.action;
int fromId = getPeerId(action.from_id); long fromId = getPeerId(action.from_id);
TLObject from; TLObject from;
if (fromId > 0) { if (fromId > 0) {
from = getUser(users, sUsers, fromId); from = getUser(users, sUsers, fromId);
} else { } else {
from = getChat(chats, sChats, -fromId); from = getChat(chats, sChats, -fromId);
} }
int toId = getPeerId(action.to_id); long toId = getPeerId(action.to_id);
int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId();
if (toId == selfUserId) { if (toId == selfUserId) {
messageText = replaceWithLink(LocaleController.formatString("ActionUserWithinRadius", R.string.ActionUserWithinRadius, LocaleController.formatDistance(action.distance, 2)), "un1", from); messageText = replaceWithLink(LocaleController.formatString("ActionUserWithinRadius", R.string.ActionUserWithinRadius, LocaleController.formatDistance(action.distance, 2)), "un1", from);
} else { } else {
@ -2627,7 +2628,7 @@ public class MessageObject {
} }
} }
} else if (messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) { } 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) { if (singleUserId == 0 && messageOwner.action.users.size() == 1) {
singleUserId = messageOwner.action.users.get(0); singleUserId = messageOwner.action.users.get(0);
} }
@ -2895,7 +2896,7 @@ public class MessageObject {
} }
} }
} else if (messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent) { } 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); generatePaymentSentMessageText(user);
} else if (messageOwner.action instanceof TLRPC.TL_messageActionBotAllowed) { } else if (messageOwner.action instanceof TLRPC.TL_messageActionBotAllowed) {
String domain = ((TLRPC.TL_messageActionBotAllowed) messageOwner.action).domain; String domain = ((TLRPC.TL_messageActionBotAllowed) messageOwner.action).domain;
@ -2947,6 +2948,19 @@ public class MessageObject {
user = getUser(users, sUsers, messageOwner.peer_id.user_id); user = getUser(users, sUsers, messageOwner.peer_id.user_id);
} }
messageText = LocaleController.formatString("ActionBotDocuments", R.string.ActionBotDocuments, UserObject.getFirstName(user), str.toString()); 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 { } else {
@ -3466,7 +3480,7 @@ public class MessageObject {
} }
} }
public CharSequence replaceWithLink(CharSequence source, String param, ArrayList<Integer> uids, AbstractMap<Integer, TLRPC.User> usersDict, SparseArray<TLRPC.User> sUsersDict) { public CharSequence replaceWithLink(CharSequence source, String param, ArrayList<Long> uids, AbstractMap<Long, TLRPC.User> usersDict, LongSparseArray<TLRPC.User> sUsersDict) {
int start = TextUtils.indexOf(source, param); int start = TextUtils.indexOf(source, param);
if (start >= 0) { if (start >= 0) {
SpannableStringBuilder names = new SpannableStringBuilder(""); SpannableStringBuilder names = new SpannableStringBuilder("");
@ -4518,7 +4532,7 @@ public class MessageObject {
if (messageOwner.fwd_from == null) { if (messageOwner.fwd_from == null) {
return true; return true;
} }
int selfUserId = UserConfig.getInstance(currentAccount).getClientUserId(); long selfUserId = UserConfig.getInstance(currentAccount).getClientUserId();
if (getDialogId() == selfUserId) { 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) 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); || 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; return false;
} }
public static int getFromChatId(TLRPC.Message message) { public static long getFromChatId(TLRPC.Message message) {
return getPeerId(message.from_id); return getPeerId(message.from_id);
} }
public static int getPeerId(TLRPC.Peer peer) { public static long getPeerId(TLRPC.Peer peer) {
if (peer == null) { if (peer == null) {
return 0; return 0;
} }
@ -4565,11 +4579,11 @@ public class MessageObject {
} }
} }
public int getFromChatId() { public long getFromChatId() {
return getFromChatId(messageOwner); return getFromChatId(messageOwner);
} }
public int getChatId() { public long getChatId() {
if (messageOwner.peer_id instanceof TLRPC.TL_peerChat) { if (messageOwner.peer_id instanceof TLRPC.TL_peerChat) {
return messageOwner.peer_id.chat_id; return messageOwner.peer_id.chat_id;
} else if (messageOwner.peer_id instanceof TLRPC.TL_peerChannel) { } else if (messageOwner.peer_id instanceof TLRPC.TL_peerChannel) {
@ -4649,11 +4663,7 @@ public class MessageObject {
return getMessageSize(messageOwner); return getMessageSize(messageOwner);
} }
public long getIdWithChannel() { public static void fixMessagePeer(ArrayList<TLRPC.Message> messages, long channelId) {
return getIdWithChannel(messageOwner);
}
public static void fixMessagePeer(ArrayList<TLRPC.Message> messages, int channelId) {
if (messages == null || messages.isEmpty() || channelId == 0) { if (messages == null || messages.isEmpty() || channelId == 0) {
return; return;
} }
@ -4666,17 +4676,13 @@ public class MessageObject {
} }
} }
public static long getIdWithChannel(TLRPC.Message message) { public long getChannelId() {
long id = message.id; return getChannelId(messageOwner);
if (message.peer_id != null && message.peer_id.channel_id != 0) {
id |= ((long) message.peer_id.channel_id) << 32;
}
return id;
} }
public int getChannelId() { public static long getChannelId(TLRPC.Message message) {
if (messageOwner.peer_id != null) { if (message.peer_id != null) {
return messageOwner.peer_id.channel_id; return message.peer_id.channel_id;
} }
return 0; return 0;
} }
@ -5009,7 +5015,7 @@ public class MessageObject {
} }
public static boolean isAnimatedStickerMessage(TLRPC.Message message) { 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) { if (isSecretChat && message.stickerVerified != 1) {
return false; return false;
} }
@ -5201,7 +5207,7 @@ public class MessageObject {
} }
if (photoHeight > maxHeight) { if (photoHeight > maxHeight) {
photoWidth *= maxHeight / photoHeight; photoWidth *= maxHeight / photoHeight;
photoHeight = (int)maxHeight; photoHeight = (int) maxHeight;
} }
if (photoWidth > maxWidth) { if (photoWidth > maxWidth) {
photoHeight *= maxWidth / photoWidth; photoHeight *= maxWidth / photoWidth;
@ -5308,7 +5314,7 @@ public class MessageObject {
if (type != 1000) { if (type != 1000) {
return type == TYPE_ANIMATED_STICKER; return type == TYPE_ANIMATED_STICKER;
} }
boolean isSecretChat = DialogObject.isSecretDialogId(getDialogId()); boolean isSecretChat = DialogObject.isEncryptedDialog(getDialogId());
if (isSecretChat && messageOwner.stickerVerified != 1) { if (isSecretChat && messageOwner.stickerVerified != 1) {
return false; return false;
} }
@ -5638,7 +5644,7 @@ public class MessageObject {
return messageOwner.replies != null && messageOwner.replies.comments; 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); 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; 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() { public int getReplyAnyMsgId() {
if (messageOwner.reply_to != null) { if (messageOwner.reply_to != null) {
if (messageOwner.reply_to.reply_to_top_id != 0) { 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; 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 != null && messageOwner.fwd_from.saved_from_peer != null) {
if (messageOwner.fwd_from.saved_from_peer.user_id != 0) { if (messageOwner.fwd_from.saved_from_peer.user_id != 0) {
if (messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerUser) { if (messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerUser) {

View file

@ -34,7 +34,6 @@ import android.os.Process;
import android.os.SystemClock; import android.os.SystemClock;
import android.service.media.MediaBrowserService; import android.service.media.MediaBrowserService;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.SparseArray;
import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteCursor;
import org.telegram.messenger.audioinfo.AudioInfo; import org.telegram.messenger.audioinfo.AudioInfo;
@ -48,6 +47,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import androidx.collection.LongSparseArray;
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class MusicBrowserService extends MediaBrowserService implements NotificationCenter.NotificationCenterDelegate { 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 int currentAccount = UserConfig.selectedAccount;
private boolean chatsLoaded; private boolean chatsLoaded;
private boolean loadingChats; private boolean loadingChats;
private ArrayList<Integer> dialogs = new ArrayList<>(); private ArrayList<Long> dialogs = new ArrayList<>();
private SparseArray<TLRPC.User> users = new SparseArray<>(); private LongSparseArray<TLRPC.User> users = new LongSparseArray<>();
private SparseArray<TLRPC.Chat> chats = new SparseArray<>(); private LongSparseArray<TLRPC.Chat> chats = new LongSparseArray<>();
private SparseArray<ArrayList<MessageObject>> musicObjects = new SparseArray<>(); private LongSparseArray<ArrayList<MessageObject>> musicObjects = new LongSparseArray<>();
private SparseArray<ArrayList<MediaSession.QueueItem>> musicQueues = new SparseArray<>(); private LongSparseArray<ArrayList<MediaSession.QueueItem>> musicQueues = new LongSparseArray<>();
public static final String ACTION_CMD = "com.example.android.mediabrowserservice.ACTION_CMD"; public static final String ACTION_CMD = "com.example.android.mediabrowserservice.ACTION_CMD";
public static final String CMD_NAME = "CMD_NAME"; public static final String CMD_NAME = "CMD_NAME";
@ -76,7 +77,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
private boolean serviceStarted; private boolean serviceStarted;
private int lastSelectedDialog; private long lastSelectedDialog;
private static final int STOP_DELAY = 30000; private static final int STOP_DELAY = 30000;
@ -87,7 +88,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
super.onCreate(); super.onCreate();
ApplicationLoader.postInitApplication(); ApplicationLoader.postInitApplication();
lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0); lastSelectedDialog = AndroidUtilities.getPrefIntOrLong(MessagesController.getNotificationsSettings(currentAccount), "auto_lastSelectedDialog", 0);
mediaSession = new MediaSession(this, "MusicService"); mediaSession = new MediaSession(this, "MusicService");
setSessionToken(mediaSession.getSessionToken()); setSessionToken(mediaSession.getSessionToken());
@ -145,35 +146,35 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
} }
@Override @Override
public void onLoadChildren(final String parentMediaId, final Result<List<MediaBrowser.MediaItem>> result) { public void onLoadChildren(String parentMediaId, Result<List<MediaBrowser.MediaItem>> result) {
if (!chatsLoaded) { if (!chatsLoaded) {
result.detach(); result.detach();
if (loadingChats) { if (loadingChats) {
return; return;
} }
loadingChats = true; loadingChats = true;
final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount); MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount);
messagesStorage.getStorageQueue().postRunnable(() -> { messagesStorage.getStorageQueue().postRunnable(() -> {
try { try {
ArrayList<Integer> usersToLoad = new ArrayList<>(); ArrayList<Long> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Long> 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)); 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()) { while (cursor.next()) {
int lower_part = (int) cursor.longValue(0); long dialogId = cursor.longValue(0);
if (lower_part == 0) { if (DialogObject.isEncryptedDialog(dialogId)) {
continue; continue;
} }
dialogs.add(lower_part); dialogs.add(dialogId);
if (lower_part > 0) { if (DialogObject.isUserDialog(dialogId)) {
usersToLoad.add(lower_part); usersToLoad.add(dialogId);
} else { } else {
chatsToLoad.add(-lower_part); chatsToLoad.add(-dialogId);
} }
} }
cursor.dispose(); cursor.dispose();
if (!dialogs.isEmpty()) { if (!dialogs.isEmpty()) {
String ids = TextUtils.join(",", dialogs); 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()) { while (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(1); NativeByteBuffer data = cursor.byteBufferValue(1);
if (data != null) { if (data != null) {
@ -181,7 +182,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId); message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId);
data.reuse(); data.reuse();
if (MessageObject.isMusicMessage(message)) { if (MessageObject.isMusicMessage(message)) {
int did = cursor.intValue(0); long did = cursor.longValue(0);
message.id = cursor.intValue(2); message.id = cursor.intValue(2);
message.dialog_id = did; message.dialog_id = did;
ArrayList<MessageObject> arrayList = musicObjects.get(did); ArrayList<MessageObject> arrayList = musicObjects.get(did);
@ -265,16 +266,16 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
} }
} }
private void loadChildrenImpl(final String parentMediaId, final Result<List<MediaBrowser.MediaItem>> result) { private void loadChildrenImpl(String parentMediaId, Result<List<MediaBrowser.MediaItem>> result) {
List<MediaBrowser.MediaItem> mediaItems = new ArrayList<>(); List<MediaBrowser.MediaItem> mediaItems = new ArrayList<>();
if (MEDIA_ID_ROOT.equals(parentMediaId)) { if (MEDIA_ID_ROOT.equals(parentMediaId)) {
for (int a = 0; a < dialogs.size(); a++) { for (int a = 0; a < dialogs.size(); a++) {
int did = dialogs.get(a); long dialogId = dialogs.get(a);
MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId("__CHAT_" + did); MediaDescription.Builder builder = new MediaDescription.Builder().setMediaId("__CHAT_" + dialogId);
TLRPC.FileLocation avatar = null; TLRPC.FileLocation avatar = null;
if (did > 0) { if (DialogObject.isUserDialog(dialogId)) {
TLRPC.User user = users.get(did); TLRPC.User user = users.get(dialogId);
if (user != null) { if (user != null) {
builder.setTitle(ContactsController.formatName(user.first_name, user.last_name)); builder.setTitle(ContactsController.formatName(user.first_name, user.last_name));
if (user.photo != null && !(user.photo.photo_small instanceof TLRPC.TL_fileLocationUnavailable)) { 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"); builder.setTitle("DELETED USER");
} }
} else { } else {
TLRPC.Chat chat = chats.get(-did); TLRPC.Chat chat = chats.get(-dialogId);
if (chat != null) { if (chat != null) {
builder.setTitle(chat.title); builder.setTitle(chat.title);
if (chat.photo != null && !(chat.photo.photo_small instanceof TLRPC.TL_fileLocationUnavailable)) { if (chat.photo != null && !(chat.photo.photo_small instanceof TLRPC.TL_fileLocationUnavailable)) {
@ -384,7 +385,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
return; return;
} }
try { try {
int did = Integer.parseInt(args[0]); long did = Long.parseLong(args[0]);
int id = Integer.parseInt(args[1]); int id = Integer.parseInt(args[1]);
ArrayList<MessageObject> arrayList = musicObjects.get(did); ArrayList<MessageObject> arrayList = musicObjects.get(did);
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did); ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
@ -392,7 +393,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
return; return;
} }
lastSelectedDialog = did; 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); MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), 0, false, null);
mediaSession.setQueue(arrayList1); mediaSession.setQueue(arrayList1);
if (did > 0) { if (did > 0) {
@ -443,8 +444,8 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
} }
query = query.toLowerCase(); query = query.toLowerCase();
for (int a = 0; a < dialogs.size(); a++) { for (int a = 0; a < dialogs.size(); a++) {
int did = dialogs.get(a); long did = dialogs.get(a);
if (did > 0) { if (DialogObject.isUserDialog(did)) {
TLRPC.User user = users.get(did); TLRPC.User user = users.get(did);
if (user == null) { if (user == null) {
continue; continue;

View file

@ -53,16 +53,23 @@ public class MusicPlayerReceiver extends BroadcastReceiver {
break; break;
} }
} else { } else {
if (intent.getAction().equals(MusicPlayerService.NOTIFY_PLAY)) { switch (intent.getAction()) {
MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject()); case MusicPlayerService.NOTIFY_PLAY:
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PAUSE) || intent.getAction().equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject());
MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject()); break;
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_NEXT)) { case MusicPlayerService.NOTIFY_PAUSE:
MediaController.getInstance().playNextMessage(); case android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY:
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_CLOSE)) { MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject());
MediaController.getInstance().cleanupPlayer(true, true); break;
} else if (intent.getAction().equals(MusicPlayerService.NOTIFY_PREVIOUS)) { case MusicPlayerService.NOTIFY_NEXT:
MediaController.getInstance().playPreviousMessage(); MediaController.getInstance().playNextMessage();
break;
case MusicPlayerService.NOTIFY_CLOSE:
MediaController.getInstance().cleanupPlayer(true, true);
break;
case MusicPlayerService.NOTIFY_PREVIOUS:
MediaController.getInstance().playPreviousMessage();
break;
} }
} }
} }

View file

@ -55,12 +55,7 @@ public class NotificationBadge {
intent.putExtra(CLASSNAME, componentName.getClassName()); intent.putExtra(CLASSNAME, componentName.getClassName());
intent.putExtra(COUNT, badgeCount); intent.putExtra(COUNT, badgeCount);
if (canResolveBroadcast(intent)) { if (canResolveBroadcast(intent)) {
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent));
@Override
public void run() {
ApplicationLoader.applicationContext.sendBroadcast(intent);
}
});
} }
} }
@ -88,12 +83,7 @@ public class NotificationBadge {
intent.putExtra(COUNT, badgeCount); intent.putExtra(COUNT, badgeCount);
intent.putExtra(CLASS, componentName.getClassName()); intent.putExtra(CLASS, componentName.getClassName());
if (canResolveBroadcast(intent)) { if (canResolveBroadcast(intent)) {
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent));
@Override
public void run() {
ApplicationLoader.applicationContext.sendBroadcast(intent);
}
});
} }
} }
@ -118,12 +108,7 @@ public class NotificationBadge {
intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName()); intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName());
intent.putExtra("badge_vip_count", 0); intent.putExtra("badge_vip_count", 0);
if (canResolveBroadcast(intent)) { if (canResolveBroadcast(intent)) {
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent));
@Override
public void run() {
ApplicationLoader.applicationContext.sendBroadcast(intent);
}
});
} }
} }
@ -145,14 +130,11 @@ public class NotificationBadge {
intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount); intent.putExtra(INTENT_EXTRA_BADGE_COUNT, badgeCount);
intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName()); intent.putExtra(INTENT_EXTRA_PACKAGENAME, componentName.getPackageName());
intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName()); intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName());
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> {
@Override try {
public void run() { ApplicationLoader.applicationContext.sendBroadcast(intent);
try { } catch (Exception ignore) {
ApplicationLoader.applicationContext.sendBroadcast(intent);
} catch (Exception ignore) {
}
} }
}); });
} }
@ -175,14 +157,11 @@ public class NotificationBadge {
localBundle.putString("package", ApplicationLoader.applicationContext.getPackageName()); localBundle.putString("package", ApplicationLoader.applicationContext.getPackageName());
localBundle.putString("class", componentName.getClassName()); localBundle.putString("class", componentName.getClassName());
localBundle.putInt("badgenumber", badgeCount); localBundle.putInt("badgenumber", badgeCount);
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> {
@Override try {
public void run() { ApplicationLoader.applicationContext.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle);
try { } catch (Exception e) {
ApplicationLoader.applicationContext.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, localBundle); FileLog.e(e);
} catch (Exception e) {
FileLog.e(e);
}
} }
}); });
} }
@ -216,12 +195,9 @@ public class NotificationBadge {
intent.putExtra(COUNT, badgeCount); intent.putExtra(COUNT, badgeCount);
if (canResolveBroadcast(intent1) || canResolveBroadcast(intent)) { if (canResolveBroadcast(intent1) || canResolveBroadcast(intent)) {
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> {
@Override ApplicationLoader.applicationContext.sendBroadcast(intent1);
public void run() { ApplicationLoader.applicationContext.sendBroadcast(intent);
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_ACTIVITY_NAME, componentName.getClassName());
intent.putExtra(INTENT_EXTRA_MESSAGE, String.valueOf(badgeCount)); intent.putExtra(INTENT_EXTRA_MESSAGE, String.valueOf(badgeCount));
intent.putExtra(INTENT_EXTRA_SHOW_MESSAGE, badgeCount > 0); intent.putExtra(INTENT_EXTRA_SHOW_MESSAGE, badgeCount > 0);
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> ApplicationLoader.applicationContext.sendBroadcast(intent));
@Override
public void run() {
ApplicationLoader.applicationContext.sendBroadcast(intent);
}
});
} }
private void executeBadgeByContentProvider(int badgeCount) { private void executeBadgeByContentProvider(int badgeCount) {
@ -488,14 +459,11 @@ public class NotificationBadge {
public void executeBadge(int badgeCount) { public void executeBadge(int badgeCount) {
final Bundle extra = new Bundle(); final Bundle extra = new Bundle();
extra.putInt("app_badge_count", badgeCount); extra.putInt("app_badge_count", badgeCount);
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(() -> {
@Override try {
public void run() { ApplicationLoader.applicationContext.getContentResolver().call(CONTENT_URI, "setAppBadgeCount", null, extra);
try { } catch (Exception e) {
ApplicationLoader.applicationContext.getContentResolver().call(CONTENT_URI, "setAppBadgeCount", null, extra); FileLog.e(e);
} catch (Exception e) {
FileLog.e(e);
}
} }
}); });
} }

View file

@ -221,6 +221,8 @@ public class NotificationCenter {
public static final int webRtcSpeakerAmplitudeEvent = totalEvents++; public static final int webRtcSpeakerAmplitudeEvent = totalEvents++;
public static final int showBulletin = totalEvents++; public static final int showBulletin = totalEvents++;
public static final int appUpdateAvailable = totalEvents++; public static final int appUpdateAvailable = totalEvents++;
public static final int onDatabaseMigration = totalEvents++;
public static final int onEmojiInteractionsReceived = totalEvents++;
private SparseArray<ArrayList<NotificationCenterDelegate>> observers = new SparseArray<>(); private SparseArray<ArrayList<NotificationCenterDelegate>> observers = new SparseArray<>();
private SparseArray<ArrayList<NotificationCenterDelegate>> removeAfterBroadcast = new SparseArray<>(); private SparseArray<ArrayList<NotificationCenterDelegate>> removeAfterBroadcast = new SparseArray<>();

View file

@ -22,14 +22,15 @@ public class OpenChatReceiver extends Activity {
Intent intent = getIntent(); Intent intent = getIntent();
if (intent == null) { if (intent == null) {
finish(); finish();
return;
} }
if (intent.getAction() == null || !intent.getAction().startsWith("com.tmessages.openchat")) { if (intent.getAction() == null || !intent.getAction().startsWith("com.tmessages.openchat")) {
finish(); finish();
return; return;
} }
try { try {
int chatId = intent.getIntExtra("chatId", 0); long chatId = intent.getLongExtra("chatId", 0);
int userId = intent.getIntExtra("userId", 0); long userId = intent.getLongExtra("userId", 0);
int encId = intent.getIntExtra("encId", 0); int encId = intent.getIntExtra("encId", 0);
if (chatId == 0 && userId == 0 && encId == 0) { if (chatId == 0 && userId == 0 && encId == 0) {
return; return;

View file

@ -12,11 +12,11 @@ import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray; import android.util.SparseArray;
import android.util.SparseIntArray; import android.util.SparseIntArray;
import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteCursor;
import org.telegram.messenger.support.LongSparseIntArray;
import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.AbstractSerializedData;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer; 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<Integer> sendingNotifyLayer = new ArrayList<>(); private ArrayList<Integer> sendingNotifyLayer = new ArrayList<>();
private SparseArray<ArrayList<TL_decryptedMessageHolder>> secretHolesQueue = new SparseArray<>(); private SparseArray<ArrayList<TL_decryptedMessageHolder>> secretHolesQueue = new SparseArray<>();
@ -110,7 +110,7 @@ public class SecretChatHelper extends BaseController {
protected void processPendingEncMessages() { protected void processPendingEncMessages() {
if (!pendingEncMessagesToDelete.isEmpty()) { if (!pendingEncMessagesToDelete.isEmpty()) {
final ArrayList<Long> pendingEncMessagesToDeleteCopy = new ArrayList<>(pendingEncMessagesToDelete); ArrayList<Long> pendingEncMessagesToDeleteCopy = new ArrayList<>(pendingEncMessagesToDelete);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
for (int a = 0; a < pendingEncMessagesToDeleteCopy.size(); a++) { for (int a = 0; a < pendingEncMessagesToDeleteCopy.size(); a++) {
MessageObject messageObject = getMessagesController().dialogMessagesByRandomIds.get(pendingEncMessagesToDeleteCopy.get(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(); TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService();
newMsg.action = new TLRPC.TL_messageEncryptedAction(); newMsg.action = new TLRPC.TL_messageEncryptedAction();
@ -136,7 +136,7 @@ public class SecretChatHelper extends BaseController {
newMsg.unread = true; newMsg.unread = true;
newMsg.out = true; newMsg.out = true;
newMsg.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; 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.peer_id = new TLRPC.TL_peerUser();
newMsg.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; newMsg.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
if (encryptedChat.participant_id == getUserConfig().getClientUserId()) { if (encryptedChat.participant_id == getUserConfig().getClientUserId()) {
@ -179,22 +179,22 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null);
} }
protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap<Integer, TLRPC.User> usersDict) { protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap<Long, TLRPC.User> usersDict) {
final TLRPC.EncryptedChat newChat = update.chat; TLRPC.EncryptedChat newChat = update.chat;
long dialog_id = ((long) newChat.id) << 32; long dialog_id = DialogObject.makeEncryptedDialogId(newChat.id);
TLRPC.EncryptedChat existingChat = getMessagesController().getEncryptedChatDB(newChat.id, false); TLRPC.EncryptedChat existingChat = getMessagesController().getEncryptedChatDB(newChat.id, false);
if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) { if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) {
int user_id = newChat.participant_id; long userId = newChat.participant_id;
if (user_id == getUserConfig().getClientUserId()) { if (userId == getUserConfig().getClientUserId()) {
user_id = newChat.admin_id; userId = newChat.admin_id;
} }
TLRPC.User user = getMessagesController().getUser(user_id); TLRPC.User user = getMessagesController().getUser(userId);
if (user == null) { if (user == null) {
user = usersDict.get(user_id); user = usersDict.get(userId);
} }
newChat.user_id = user_id; newChat.user_id = userId;
final TLRPC.Dialog dialog = new TLRPC.TL_dialog(); TLRPC.Dialog dialog = new TLRPC.TL_dialog();
dialog.id = dialog_id; dialog.id = dialog_id;
dialog.folder_id = newChat.folder_id; dialog.folder_id = newChat.folder_id;
dialog.unread_count = 0; dialog.unread_count = 0;
@ -223,7 +223,7 @@ public class SecretChatHelper extends BaseController {
delayedEncryptedChatUpdates.add(update); delayedEncryptedChatUpdates.add(update);
} }
} else { } else {
final TLRPC.EncryptedChat exist = existingChat; TLRPC.EncryptedChat exist = existingChat;
if (exist != null) { if (exist != null) {
newChat.user_id = exist.user_id; newChat.user_id = exist.user_id;
newChat.auth_key = exist.auth_key; newChat.auth_key = exist.auth_key;
@ -288,7 +288,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -312,7 +312,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -335,7 +335,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -359,7 +359,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -382,7 +382,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -404,7 +404,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; return;
} }
@ -424,7 +424,7 @@ public class SecretChatHelper extends BaseController {
performSendEncryptedRequest(reqSend, message, encryptedChat, null, null, null); 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)) { if (!(encryptedChat instanceof TLRPC.TL_encryptedChat)) {
return; 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); 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++) { 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)); 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) { if (req == null || chat.auth_key == null || chat instanceof TLRPC.TL_encryptedChatRequested || chat instanceof TLRPC.TL_encryptedChatWaiting) {
return; return;
} }
@ -627,11 +627,9 @@ public class SecretChatHelper extends BaseController {
} }
getMessagesStorage().updateEncryptedChatSeq(chat, false); getMessagesStorage().updateEncryptedChatSeq(chat, false);
if (newMsgObj != null) { newMsgObj.seq_in = layer.in_seq_no;
newMsgObj.seq_in = layer.in_seq_no; newMsgObj.seq_out = layer.out_seq_no;
newMsgObj.seq_out = layer.out_seq_no; getMessagesStorage().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out);
getMessagesStorage().setMessageSeq(newMsgObj.id, newMsgObj.seq_in, newMsgObj.seq_out);
}
} else { } else {
layer.in_seq_no = newMsgObj.seq_in; layer.in_seq_no = newMsgObj.seq_in;
layer.out_seq_no = newMsgObj.seq_out; layer.out_seq_no = newMsgObj.seq_out;
@ -741,47 +739,45 @@ public class SecretChatHelper extends BaseController {
getMessagesStorage().updateEncryptedChatLayer(currentChat); getMessagesStorage().updateEncryptedChatLayer(currentChat);
} }
} }
if (newMsgObj != null) { if (error == null) {
if (error == null) { String attachPath = newMsgObj.attachPath;
final String attachPath = newMsgObj.attachPath; TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response;
final TLRPC.messages_SentEncryptedMessage res = (TLRPC.messages_SentEncryptedMessage) response; if (isSecretVisibleMessage(newMsgObj)) {
if (isSecretVisibleMessage(newMsgObj)) { newMsgObj.date = res.date;
newMsgObj.date = res.date; }
} int existFlags;
int existFlags; if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) {
if (newMsg != null && res.file instanceof TLRPC.TL_encryptedFile) { updateMediaPaths(newMsg, res.file, req, originalPath);
updateMediaPaths(newMsg, res.file, req, originalPath); existFlags = newMsg.getMediaExistanceFlags();
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);
});
});
} else { } 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(() -> { AndroidUtilities.runOnUIThread(() -> {
newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR; newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
getNotificationCenter().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, false);
getSendMessagesHelper().processSentMessage(newMsgObj.id); getSendMessagesHelper().processSentMessage(newMsgObj.id);
if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) { if (MessageObject.isVideoMessage(newMsgObj) || MessageObject.isNewGifMessage(newMsgObj) || MessageObject.isRoundVideoMessage(newMsgObj)) {
getSendMessagesHelper().stopVideoService(newMsgObj.attachPath); getSendMessagesHelper().stopVideoService(attachPath);
} }
getSendMessagesHelper().removeFromSendingMessages(newMsgObj.id, false); 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); }, ConnectionsManager.RequestFlagInvokeAfter);
} catch (Exception e) { } 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); int currentPeerLayer = AndroidUtilities.getPeerLayerVersion(chat.layer);
if (newPeerLayer <= currentPeerLayer) { if (newPeerLayer <= currentPeerLayer) {
return; return;
@ -815,9 +811,9 @@ public class SecretChatHelper extends BaseController {
AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.encryptedChatUpdated, chat)); 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) { if (object != null) {
int from_id = chat.admin_id; long from_id = chat.admin_id;
if (from_id == getUserConfig().getClientUserId()) { if (from_id == getUserConfig().getClientUserId()) {
from_id = chat.participant_id; from_id = chat.participant_id;
} }
@ -869,7 +865,7 @@ public class SecretChatHelper extends BaseController {
newMessage.grouped_id = decryptedMessage.grouped_id; newMessage.grouped_id = decryptedMessage.grouped_id;
newMessage.flags |= 131072; newMessage.flags |= 131072;
} }
newMessage.dialog_id = ((long) chat.id) << 32; newMessage.dialog_id = DialogObject.makeEncryptedDialogId(chat.id);
if (decryptedMessage.reply_to_random_id != 0) { if (decryptedMessage.reply_to_random_id != 0) {
newMessage.reply_to = new TLRPC.TL_messageReplyHeader(); newMessage.reply_to = new TLRPC.TL_messageReplyHeader();
newMessage.reply_to.reply_to_random_id = decryptedMessage.reply_to_random_id; newMessage.reply_to.reply_to_random_id = decryptedMessage.reply_to_random_id;
@ -1117,7 +1113,7 @@ public class SecretChatHelper extends BaseController {
} }
return newMessage; return newMessage;
} else if (object instanceof TLRPC.TL_decryptedMessageService) { } 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) { if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL || serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) {
TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService(); TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) { if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
@ -1128,7 +1124,7 @@ public class SecretChatHelper extends BaseController {
chat.ttl = serviceMessage.action.ttl_seconds; chat.ttl = serviceMessage.action.ttl_seconds;
newMessage.action.encryptedAction = serviceMessage.action; newMessage.action.encryptedAction = serviceMessage.action;
getMessagesStorage().updateEncryptedChatTTL(chat); getMessagesStorage().updateEncryptedChatTTL(chat);
} else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) { } else {
newMessage.action = new TLRPC.TL_messageEncryptedAction(); newMessage.action = new TLRPC.TL_messageEncryptedAction();
newMessage.action.encryptedAction = serviceMessage.action; newMessage.action.encryptedAction = serviceMessage.action;
} }
@ -1141,10 +1137,10 @@ public class SecretChatHelper extends BaseController {
newMessage.from_id.user_id = from_id; newMessage.from_id.user_id = from_id;
newMessage.peer_id = new TLRPC.TL_peerUser(); newMessage.peer_id = new TLRPC.TL_peerUser();
newMessage.peer_id.user_id = getUserConfig().getClientUserId(); newMessage.peer_id.user_id = getUserConfig().getClientUserId();
newMessage.dialog_id = ((long) chat.id) << 32; newMessage.dialog_id = DialogObject.makeEncryptedDialogId(chat.id);
return newMessage; return newMessage;
} else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionFlushHistory) { } else if (serviceMessage.action instanceof TLRPC.TL_decryptedMessageActionFlushHistory) {
final long did = ((long) chat.id) << 32; long did = DialogObject.makeEncryptedDialogId(chat.id);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(did); TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(did);
if (dialog != null) { if (dialog != null) {
@ -1153,7 +1149,7 @@ public class SecretChatHelper extends BaseController {
} }
getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> { getMessagesStorage().getStorageQueue().postRunnable(() -> AndroidUtilities.runOnUIThread(() -> {
getNotificationsController().processReadMessages(null, did, 0, Integer.MAX_VALUE, false); getNotificationsController().processReadMessages(null, did, 0, Integer.MAX_VALUE, false);
LongSparseArray<Integer> dialogsToUpdate = new LongSparseArray<>(1); LongSparseIntArray dialogsToUpdate = new LongSparseIntArray(1);
dialogsToUpdate.put(did, 0); dialogsToUpdate.put(did, 0);
getNotificationsController().processDialogsUpdateRead(dialogsToUpdate); getNotificationsController().processDialogsUpdateRead(dialogsToUpdate);
})); }));
@ -1353,7 +1349,7 @@ public class SecretChatHelper extends BaseController {
newMsg.unread = true; newMsg.unread = true;
newMsg.out = true; newMsg.out = true;
newMsg.flags = TLRPC.MESSAGE_FLAG_HAS_FROM_ID; 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.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
newMsg.seq_in = seq_in; newMsg.seq_in = seq_in;
newMsg.seq_out = seq_out; newMsg.seq_out = seq_out;
@ -1368,7 +1364,7 @@ public class SecretChatHelper extends BaseController {
return newMsg; 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) { if (encryptedChat == null || endSeq - startSeq < 0) {
return; return;
} }
@ -1386,13 +1382,13 @@ public class SecretChatHelper extends BaseController {
return; return;
} }
long dialog_id = ((long) encryptedChat.id) << 32; long dialog_id = DialogObject.makeEncryptedDialogId(encryptedChat.id);
SparseArray<TLRPC.Message> messagesToResend = new SparseArray<>(); SparseArray<TLRPC.Message> messagesToResend = new SparseArray<>();
final ArrayList<TLRPC.Message> messages = new ArrayList<>(); ArrayList<TLRPC.Message> messages = new ArrayList<>();
for (int a = sSeq; a <= endSeq; a += 2) { for (int a = sSeq; a <= endSeq; a += 2) {
messagesToResend.put(a, null); 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()) { while (cursor.next()) {
TLRPC.Message message; TLRPC.Message message;
long random_id = cursor.longValue(1); long random_id = cursor.longValue(1);
@ -1551,7 +1547,7 @@ public class SecretChatHelper extends BaseController {
} }
protected ArrayList<TLRPC.Message> decryptMessage(TLRPC.EncryptedMessage message) { protected ArrayList<TLRPC.Message> 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) { if (chat == null || chat instanceof TLRPC.TL_encryptedChatDiscarded) {
return null; return null;
} }
@ -1600,7 +1596,7 @@ public class SecretChatHelper extends BaseController {
} }
} else { } else {
decryptedWithVersion = 2; decryptedWithVersion = 2;
if (!decryptWithMtProtoVersion(is, keyToDecrypt, messageKey, 2, incoming, tryAnotherDecrypt)) { if (!decryptWithMtProtoVersion(is, keyToDecrypt, messageKey, 2, incoming, true)) {
return null; return null;
} }
} }
@ -1613,7 +1609,7 @@ public class SecretChatHelper extends BaseController {
chat.key_use_count_in++; chat.key_use_count_in++;
} }
if (object instanceof TLRPC.TL_decryptedMessageLayer) { 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.seq_in == 0 && chat.seq_out == 0) {
if (chat.admin_id == getUserConfig().getClientUserId()) { if (chat.admin_id == getUserConfig().getClientUserId()) {
chat.seq_out = 1; chat.seq_out = 1;
@ -1650,7 +1646,7 @@ public class SecretChatHelper extends BaseController {
} }
if (arr.size() >= 4) { if (arr.size() >= 4) {
secretHolesQueue.remove(chat.id); 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.id = chat.id;
newChat.user_id = chat.user_id; newChat.user_id = chat.user_id;
newChat.auth_key = chat.auth_key; newChat.auth_key = chat.auth_key;
@ -1708,8 +1704,8 @@ public class SecretChatHelper extends BaseController {
return null; return null;
} }
public void requestNewSecretChatKey(final TLRPC.EncryptedChat encryptedChat) { public void requestNewSecretChatKey(TLRPC.EncryptedChat encryptedChat) {
final byte[] salt = new byte[256]; byte[] salt = new byte[256];
Utilities.random.nextBytes(salt); Utilities.random.nextBytes(salt);
BigInteger i_g_a = BigInteger.valueOf(getMessagesStorage().getSecretG()); BigInteger i_g_a = BigInteger.valueOf(getMessagesStorage().getSecretG());
@ -1730,7 +1726,7 @@ public class SecretChatHelper extends BaseController {
sendRequestKeyMessage(encryptedChat, null); sendRequestKeyMessage(encryptedChat, null);
} }
public void processAcceptedSecretChat(final TLRPC.EncryptedChat encryptedChat) { public void processAcceptedSecretChat(TLRPC.EncryptedChat encryptedChat) {
BigInteger p = new BigInteger(1, getMessagesStorage().getSecretPBytes()); BigInteger p = new BigInteger(1, getMessagesStorage().getSecretPBytes());
BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b); BigInteger i_authKey = new BigInteger(1, encryptedChat.g_a_or_b);
@ -1775,7 +1771,7 @@ public class SecretChatHelper extends BaseController {
sendNotifyLayerMessage(encryptedChat, null); sendNotifyLayerMessage(encryptedChat, null);
}); });
} else { } else {
final TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded(); TLRPC.TL_encryptedChatDiscarded newChat = new TLRPC.TL_encryptedChatDiscarded();
newChat.id = encryptedChat.id; newChat.id = encryptedChat.id;
newChat.user_id = encryptedChat.user_id; newChat.user_id = encryptedChat.user_id;
newChat.auth_key = encryptedChat.auth_key; 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) { if (acceptingChats.get(encryptedChat.id) != null) {
return; return;
} }
@ -1903,7 +1899,7 @@ public class SecretChatHelper extends BaseController {
getConnectionsManager().sendRequest(req2, (response1, error1) -> { getConnectionsManager().sendRequest(req2, (response1, error1) -> {
acceptingChats.remove(encryptedChat.id); acceptingChats.remove(encryptedChat.id);
if (error1 == null) { if (error1 == null) {
final TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response1; TLRPC.EncryptedChat newChat = (TLRPC.EncryptedChat) response1;
newChat.auth_key = encryptedChat.auth_key; newChat.auth_key = encryptedChat.auth_key;
newChat.user_id = encryptedChat.user_id; newChat.user_id = encryptedChat.user_id;
newChat.seq_in = encryptedChat.seq_in; 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) { if (user == null || context == null) {
return; return;
} }
startingSecretChat = true; 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(); TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
req.random_length = 256; req.random_length = 256;
req.version = getMessagesStorage().getLastSecretVersion(); req.version = getMessagesStorage().getLastSecretVersion();
final int reqId = getConnectionsManager().sendRequest(req, (response, error) -> { int reqId = getConnectionsManager().sendRequest(req, (response, error) -> {
if (error == null) { if (error == null) {
TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response; TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
if (response instanceof TLRPC.TL_messages_dhConfig) { if (response instanceof TLRPC.TL_messages_dhConfig) {
@ -1955,7 +1951,7 @@ public class SecretChatHelper extends BaseController {
getMessagesStorage().setLastSecretVersion(res.version); getMessagesStorage().setLastSecretVersion(res.version);
getMessagesStorage().saveSecretParams(getMessagesStorage().getLastSecretVersion(), getMessagesStorage().getSecretG(), getMessagesStorage().getSecretPBytes()); 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++) { for (int a = 0; a < 256; a++) {
salt[a] = (byte) ((byte) (Utilities.random.nextDouble() * 256) ^ res.random[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; chat.a_or_b = salt;
getMessagesController().putEncryptedChat(chat, false); getMessagesController().putEncryptedChat(chat, false);
TLRPC.Dialog dialog = new TLRPC.TL_dialog(); TLRPC.Dialog dialog = new TLRPC.TL_dialog();
dialog.id = DialogObject.makeSecretDialogId(chat.id); dialog.id = DialogObject.makeEncryptedDialogId(chat.id);
dialog.unread_count = 0; dialog.unread_count = 0;
dialog.top_message = 0; dialog.top_message = 0;
dialog.last_message_date = getConnectionsManager().getCurrentTime(); dialog.last_message_date = getConnectionsManager().getCurrentTime();

View file

@ -4,7 +4,6 @@ public class SegmentTree {
private Node[] heap; private Node[] heap;
private int[] array; private int[] array;
private int size;
public SegmentTree(int[] array) { public SegmentTree(int[] array) {
this.array = array; this.array = array;
@ -12,12 +11,11 @@ public class SegmentTree {
return; return;
} }
//The max size of this array is about 2 * 2 ^ log2(n) + 1 //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]; heap = new Node[size];
build(1, 0, array.length); build(1, 0, array.length);
} }
private void build(int v, int from, int size) { private void build(int v, int from, int size) {
heap[v] = new Node(); heap[v] = new Node();
heap[v].from = from; heap[v].from = from;

View file

@ -29,7 +29,6 @@ import android.os.SystemClock;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Base64; import android.util.Base64;
import android.util.LongSparseArray;
import android.util.SparseArray; import android.util.SparseArray;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
@ -40,6 +39,7 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.UiThread; import androidx.annotation.UiThread;
import androidx.collection.LongSparseArray;
import androidx.core.view.inputmethod.InputContentInfoCompat; import androidx.core.view.inputmethod.InputContentInfoCompat;
import org.json.JSONObject; import org.json.JSONObject;
@ -1018,7 +1018,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
String finalPath = (String) args[1]; String finalPath = (String) args[1];
long availableSize = (Long) args[2]; long availableSize = (Long) args[2];
long finalSize = (Long) args[3]; long finalSize = (Long) args[3];
boolean isEncrypted = ((int) messageObject.getDialogId()) == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(messageObject.getDialogId());
getFileLoader().checkUploadNewDataAvailable(finalPath, isEncrypted, availableSize, finalSize); getFileLoader().checkUploadNewDataAvailable(finalPath, isEncrypted, availableSize, finalSize);
if (finalSize != 0) { if (finalSize != 0) {
stopVideoService(messageObject.messageOwner.attachPath); stopVideoService(messageObject.messageOwner.attachPath);
@ -1249,17 +1249,15 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
ArrayList<DelayedMessage> checkReadyToSendGroups = new ArrayList<>(); ArrayList<DelayedMessage> checkReadyToSendGroups = new ArrayList<>();
ArrayList<Integer> messageIds = new ArrayList<>(); ArrayList<Integer> messageIds = new ArrayList<>();
boolean enc = false; boolean enc = false;
int channelId = 0;
boolean scheduled = false; boolean scheduled = false;
long scheduledDialogId = 0; long dialogId = 0;
for (int c = 0; c < objects.size(); c++) { for (int c = 0; c < objects.size(); c++) {
MessageObject object = objects.get(c); MessageObject object = objects.get(c);
if (object.scheduled) { if (object.scheduled) {
scheduled = true; scheduled = true;
scheduledDialogId = object.getDialogId();
} }
dialogId = object.getDialogId();
messageIds.add(object.getId()); messageIds.add(object.getId());
channelId = object.messageOwner.peer_id.channel_id;
TLRPC.Message sendingMessage = removeFromSendingMessages(object.getId(), object.scheduled); TLRPC.Message sendingMessage = removeFromSendingMessages(object.getId(), object.scheduled);
if (sendingMessage != null) { if (sendingMessage != null) {
getConnectionsManager().cancelRequest(sendingMessage.reqId, true); 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) { if (objects.size() == 1 && objects.get(0).isEditing() && objects.get(0).previousMedia != null) {
revertEditingMessageObject(objects.get(0)); revertEditingMessageObject(objects.get(0));
} else { } 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; return false;
} }
if (messageObject.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction) { 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); TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(enc_id);
if (encryptedChat == null) { if (encryptedChat == null) {
getMessagesStorage().markMessageAsSendError(messageObject.messageOwner, messageObject.scheduled); getMessagesStorage().markMessageAsSendError(messageObject.messageOwner, messageObject.scheduled);
@ -1404,7 +1402,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
return true; return true;
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionScreenshotTaken) { } 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); sendScreenshotMessage(user, messageObject.getReplyMsgId(), messageObject.messageOwner);
} }
if (unsent) { 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)) { 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<String, String> params = null; HashMap<String, String> 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 = new HashMap<>();
params.put("parentObject", "sent_" + messageObject.messageOwner.peer_id.channel_id + "_" + messageObject.getId()); 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.last_name = messageObject.messageOwner.media.last_name;
user.id = messageObject.messageOwner.media.user_id; user.id = messageObject.messageOwner.media.user_id;
sendMessage(user, did, messageObject.replyMessageObject, null, null, null, true, 0); sendMessage(user, did, messageObject.replyMessageObject, null, null, null, true, 0);
} else if ((int) did != 0) { } else if (!DialogObject.isEncryptedDialog(did)) {
ArrayList<MessageObject> arrayList = new ArrayList<>(); ArrayList<MessageObject> arrayList = new ArrayList<>();
arrayList.add(messageObject); arrayList.add(messageObject);
sendMessage(arrayList, did, true, false, true, 0); sendMessage(arrayList, did, true, false, true, 0);
@ -1472,7 +1470,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
entities = null; entities = null;
} }
sendMessage(messageObject.messageOwner.message, did, messageObject.replyMessageObject, null, webPage, true, entities, null, null, true, 0, 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<MessageObject> arrayList = new ArrayList<>(); ArrayList<MessageObject> arrayList = new ArrayList<>();
arrayList.add(messageObject); arrayList.add(messageObject);
sendMessage(arrayList, did, true, false, true, 0); sendMessage(arrayList, did, true, false, true, 0);
@ -1532,9 +1530,9 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
if (document == null) { if (document == null) {
return; return;
} }
if ((int) peer == 0) { if (DialogObject.isEncryptedDialog(peer)) {
int high_id = (int) (peer >> 32); int encryptedId = DialogObject.getEncryptedChatId(peer);
TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedId);
if (encryptedChat == null) { if (encryptedChat == null) {
return; return;
} }
@ -1637,28 +1635,27 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
if (messages == null || messages.isEmpty()) { if (messages == null || messages.isEmpty()) {
return 0; return 0;
} }
int lower_id = (int) peer;
int sendResult = 0; int sendResult = 0;
int myId = getUserConfig().getClientUserId(); long myId = getUserConfig().getClientUserId();
boolean isChannel = false; boolean isChannel = false;
if (lower_id != 0) { if (!DialogObject.isEncryptedDialog(peer)) {
final TLRPC.Peer peer_id = getMessagesController().getPeer((int) peer); final TLRPC.Peer peer_id = getMessagesController().getPeer(peer);
boolean isSignature = false; boolean isSignature = false;
boolean canSendStickers = true; boolean canSendStickers = true;
boolean canSendMedia = true; boolean canSendMedia = true;
boolean canSendPolls = true; boolean canSendPolls = true;
boolean canSendPreview = true; boolean canSendPreview = true;
String rank = null; String rank = null;
int linkedToGroup = 0; long linkedToGroup = 0;
TLRPC.Chat chat; TLRPC.Chat chat;
if (lower_id > 0) { if (DialogObject.isUserDialog(peer)) {
TLRPC.User sendToUser = getMessagesController().getUser(lower_id); TLRPC.User sendToUser = getMessagesController().getUser(peer);
if (sendToUser == null) { if (sendToUser == null) {
return 0; return 0;
} }
chat = null; chat = null;
} else { } else {
chat = getMessagesController().getChat(-lower_id); chat = getMessagesController().getChat(-peer);
if (ChatObject.isChannel(chat)) { if (ChatObject.isChannel(chat)) {
isSignature = chat.signatures; isSignature = chat.signatures;
isChannel = !chat.megagroup; isChannel = !chat.megagroup;
@ -1685,7 +1682,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
ArrayList<Long> randomIds = new ArrayList<>(); ArrayList<Long> randomIds = new ArrayList<>();
ArrayList<Integer> ids = new ArrayList<>(); ArrayList<Integer> ids = new ArrayList<>();
LongSparseArray<TLRPC.Message> messagesByRandomIds = new LongSparseArray<>(); LongSparseArray<TLRPC.Message> messagesByRandomIds = new LongSparseArray<>();
TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(lower_id); TLRPC.InputPeer inputPeer = getMessagesController().getInputPeer(peer);
long lastDialogId = 0; long lastDialogId = 0;
final boolean toMyself = peer == myId; final boolean toMyself = peer == myId;
long lastGroupedId; long lastGroupedId;
@ -1744,7 +1741,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
newMsg.fwd_from.date = msgObj.messageOwner.fwd_from.date; newMsg.fwd_from.date = msgObj.messageOwner.fwd_from.date;
newMsg.flags = TLRPC.MESSAGE_FLAG_FWD; newMsg.flags = TLRPC.MESSAGE_FLAG_FWD;
} else if (!forwardFromSaved) { //if (!toMyself || !msgObj.isOutOwner()) } 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 = new TLRPC.TL_messageFwdHeader();
newMsg.fwd_from.channel_post = msgObj.getId(); newMsg.fwd_from.channel_post = msgObj.getId();
newMsg.fwd_from.flags |= 4; 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_msg_id = msgObj.getId();
newMsg.fwd_from.saved_from_peer = msgObj.messageOwner.peer_id; newMsg.fwd_from.saved_from_peer = msgObj.messageOwner.peer_id;
if (newMsg.fwd_from.saved_from_peer.user_id == myId) { 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()) { if (!msgObj.messageOwner.restriction_reason.isEmpty()) {
newMsg.restriction_reason = msgObj.messageOwner.restriction_reason; newMsg.restriction_reason = msgObj.messageOwner.restriction_reason;
newMsg.flags |= 4194304; newMsg.flags |= 4194304;
@ -1926,9 +1922,6 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
newMsg.media_unread = true; 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); MessageObject newMsgObj = new MessageObject(currentAccount, newMsg, true, true);
newMsgObj.scheduled = scheduleDate != 0; newMsgObj.scheduled = scheduleDate != 0;
newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING; newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
@ -2059,7 +2052,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
ArrayList<Integer> messageIds = new ArrayList<>(); ArrayList<Integer> messageIds = new ArrayList<>();
messageIds.add(oldId); 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().getStorageQueue().postRunnable(() -> {
getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
@ -2074,7 +2067,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
}); });
} else { } else {
getMessagesStorage().getStorageQueue().postRunnable(() -> { 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); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduleDate != 0);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
newMsgObj1.send_state = MessageObject.MESSAGE_SEND_STATE_SENT; newMsgObj1.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
@ -2156,9 +2149,9 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
DelayedMessage delayedMessage = null; DelayedMessage delayedMessage = null;
long peer = messageObject.getDialogId(); long peer = messageObject.getDialogId();
boolean supportsSendingNewEntities = true; boolean supportsSendingNewEntities = true;
if ((int) peer == 0) { if (DialogObject.isEncryptedDialog(peer)) {
int high_id = (int) (peer >> 32); int encryptedId = DialogObject.getEncryptedChatId(peer);
TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(high_id); TLRPC.EncryptedChat encryptedChat = getMessagesController().getEncryptedChat(encryptedId);
if (encryptedChat == null || AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) < 101) { if (encryptedChat == null || AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) < 101) {
supportsSendingNewEntities = false; supportsSendingNewEntities = false;
} }
@ -2447,7 +2440,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
TLRPC.TL_messages_editMessage request = new TLRPC.TL_messages_editMessage(); TLRPC.TL_messages_editMessage request = new TLRPC.TL_messages_editMessage();
request.id = messageObject.getId(); request.id = messageObject.getId();
request.peer = getMessagesController().getInputPeer((int) peer); request.peer = getMessagesController().getInputPeer(peer);
if (inputMedia != null) { if (inputMedia != null) {
request.flags |= 16384; request.flags |= 16384;
request.media = inputMedia; 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(); 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) { if (message != null) {
req.message = message; req.message = message;
req.flags |= 2048; req.flags |= 2048;
@ -2574,24 +2567,23 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
return waitingForLocation.containsKey(key); 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(() -> { AndroidUtilities.runOnUIThread(() -> {
int lowerId = (int) dialogId;
final String key = dialogId + "_" + msgId + "_" + Utilities.bytesToHex(data) + "_" + 0; final String key = dialogId + "_" + msgId + "_" + Utilities.bytesToHex(data) + "_" + 0;
waitingForCallback.put(key, true); waitingForCallback.put(key, true);
if (lowerId > 0) { if (DialogObject.isUserDialog(dialogId)) {
TLRPC.User user = getMessagesController().getUser(lowerId); TLRPC.User user = getMessagesController().getUser(dialogId);
if (user == null) { if (user == null) {
user = getMessagesStorage().getUserSync(lowerId); user = getMessagesStorage().getUserSync(dialogId);
if (user != null) { if (user != null) {
getMessagesController().putUser(user, true); getMessagesController().putUser(user, true);
} }
} }
} else { } else {
TLRPC.Chat chat = getMessagesController().getChat(-lowerId); TLRPC.Chat chat = getMessagesController().getChat(-dialogId);
if (chat == null) { if (chat == null) {
chat = getMessagesStorage().getChatSync(-lowerId); chat = getMessagesStorage().getChatSync(-dialogId);
if (chat != null) { if (chat != null) {
getMessagesController().putChat(chat, true); 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(); 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.msg_id = msgId;
req.game = false; req.game = false;
if (data != null) { if (data != null) {
@ -2629,7 +2621,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
TLRPC.TL_messages_sendVote req = new TLRPC.TL_messages_sendVote(); TLRPC.TL_messages_sendVote req = new TLRPC.TL_messages_sendVote();
req.msg_id = messageObject.getId(); req.msg_id = messageObject.getId();
req.peer = getMessagesController().getInputPeer((int) messageObject.getDialogId()); req.peer = getMessagesController().getInputPeer(messageObject.getDialogId());
byte[] options; byte[] options;
if (answers != null) { if (answers != null) {
options = new byte[answers.size()]; options = new byte[answers.size()];
@ -2661,12 +2653,12 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
return voteSendTime.get(pollId, 0L); 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) { if (messageObject == null || parentFragment == null) {
return; return;
} }
TLRPC.TL_messages_sendReaction req = new TLRPC.TL_messages_sendReaction(); 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(); req.msg_id = messageObject.getId();
if (reaction != null) { if (reaction != null) {
req.reaction = reaction.toString(); req.reaction = reaction.toString();
@ -2771,7 +2763,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
getMessagesStorage().saveBotCache(key, res); getMessagesStorage().saveBotCache(key, res);
} }
if (res.message != null) { if (res.message != null) {
int uid = messageObject.getFromChatId(); long uid = messageObject.getFromChatId();
if (messageObject.messageOwner.via_bot_id != 0) { if (messageObject.messageOwner.via_bot_id != 0) {
uid = messageObject.messageOwner.via_bot_id; uid = messageObject.messageOwner.via_bot_id;
} }
@ -2806,7 +2798,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
if (parentFragment.getParentActivity() == null) { if (parentFragment.getParentActivity() == null) {
return; return;
} }
int uid = messageObject.getFromChatId(); long uid = messageObject.getFromChatId();
if (messageObject.messageOwner.via_bot_id != 0) { if (messageObject.messageOwner.via_bot_id != 0) {
uid = messageObject.messageOwner.via_bot_id; uid = messageObject.messageOwner.via_bot_id;
} }
@ -2940,7 +2932,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} else { } else {
if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) { if (button instanceof TLRPC.TL_keyboardButtonUrlAuth) {
TLRPC.TL_messages_requestUrlAuth req = new TLRPC.TL_messages_requestUrlAuth(); 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.msg_id = messageObject.getId();
req.button_id = button.button_id; req.button_id = button.button_id;
req.flags |= 2; req.flags |= 2;
@ -2974,7 +2966,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
} else { } else {
TLRPC.TL_messages_getBotCallbackAnswer req = new TLRPC.TL_messages_getBotCallbackAnswer(); 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.msg_id = messageObject.getId();
req.game = button instanceof TLRPC.TL_keyboardButtonGame; req.game = button instanceof TLRPC.TL_keyboardButtonGame;
if (button.requires_password) { if (button.requires_password) {
@ -3106,18 +3098,16 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
MessageObject newMsgObj = null; MessageObject newMsgObj = null;
DelayedMessage delayedMessage = null; DelayedMessage delayedMessage = null;
int type = -1; int type = -1;
int lower_id = (int) peer;
int high_id = (int) (peer >> 32);
boolean isChannel = false; boolean isChannel = false;
boolean forceNoSoundVideo = false; boolean forceNoSoundVideo = false;
boolean anonymously = false; boolean anonymously = false;
String rank = null; String rank = null;
int linkedToGroup = 0; long linkedToGroup = 0;
TLRPC.EncryptedChat encryptedChat = null; TLRPC.EncryptedChat encryptedChat = null;
TLRPC.InputPeer sendToPeer = lower_id != 0 ? getMessagesController().getInputPeer(lower_id) : null; TLRPC.InputPeer sendToPeer = !DialogObject.isEncryptedDialog(peer) ? getMessagesController().getInputPeer(peer) : null;
int myId = getUserConfig().getClientUserId(); long myId = getUserConfig().getClientUserId();
if (lower_id == 0) { if (DialogObject.isEncryptedDialog(peer)) {
encryptedChat = getMessagesController().getEncryptedChat(high_id); encryptedChat = getMessagesController().getEncryptedChat(DialogObject.getEncryptedChatId(peer));
if (encryptedChat == null) { if (encryptedChat == null) {
if (retryMessageObject != null) { if (retryMessageObject != null) {
getMessagesStorage().markMessageAsSendError(retryMessageObject.messageOwner, retryMessageObject.scheduled); getMessagesStorage().markMessageAsSendError(retryMessageObject.messageOwner, retryMessageObject.scheduled);
@ -3211,8 +3201,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
} else { } else {
boolean canSendStickers = true; boolean canSendStickers = true;
if (lower_id < 0) { if (DialogObject.isChatDialog(peer)) {
TLRPC.Chat chat = getMessagesController().getChat(-lower_id); TLRPC.Chat chat = getMessagesController().getChat(-peer);
canSendStickers = ChatObject.canSendStickers(chat); canSendStickers = ChatObject.canSendStickers(chat);
} }
if (message != null) { if (message != null) {
@ -3344,7 +3334,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} else { } else {
newMsg = new TLRPC.TL_message(); newMsg = new TLRPC.TL_message();
} }
if (lower_id < 0) { if (DialogObject.isChatDialog(peer)) {
if (!canSendStickers) { if (!canSendStickers) {
for (int a = 0, N = document.attributes.size(); a < N; a++) { for (int a = 0, N = document.attributes.size(); a < N; a++) {
if (document.attributes.get(a) instanceof TLRPC.TL_documentAttributeAnimated) { 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 = new TLRPC.TL_peerChannel();
newMsg.from_id.channel_id = sendToPeer.channel_id; newMsg.from_id.channel_id = sendToPeer.channel_id;
} else if (anonymously) { } else if (anonymously) {
newMsg.from_id = getMessagesController().getPeer(lower_id); newMsg.from_id = getMessagesController().getPeer(peer);
if (rank != null) { if (rank != null) {
newMsg.post_author = rank; newMsg.post_author = rank;
newMsg.flags |= 65536; newMsg.flags |= 65536;
@ -3516,10 +3506,10 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
newMsg.flags |= TLRPC.MESSAGE_FLAG_HAS_MARKUP; newMsg.flags |= TLRPC.MESSAGE_FLAG_HAS_MARKUP;
newMsg.reply_markup = replyMarkup; newMsg.reply_markup = replyMarkup;
} }
if (lower_id != 0) { if (!DialogObject.isEncryptedDialog(peer)) {
newMsg.peer_id = getMessagesController().getPeer(lower_id); newMsg.peer_id = getMessagesController().getPeer(peer);
if (lower_id > 0) { if (DialogObject.isUserDialog(peer)) {
TLRPC.User sendToUser = getMessagesController().getUser(lower_id); TLRPC.User sendToUser = getMessagesController().getUser(peer);
if (sendToUser == null) { if (sendToUser == null) {
processSentMessage(newMsg.id); processSentMessage(newMsg.id);
return; 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; newMsg.media_unread = true;
} }
@ -4346,7 +4336,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
reqSend.drop_author = true; reqSend.drop_author = true;
long peerId = Utilities.parseLong(params.get("fwd_peer")); long peerId = Utilities.parseLong(params.get("fwd_peer"));
if (peerId < 0) { if (peerId < 0) {
TLRPC.Chat chat = getMessagesController().getChat((int) -peerId); TLRPC.Chat chat = getMessagesController().getChat(-peerId);
if (ChatObject.isChannel(chat)) { if (ChatObject.isChannel(chat)) {
reqSend.from_peer = new TLRPC.TL_inputPeerChannel(); reqSend.from_peer = new TLRPC.TL_inputPeerChannel();
reqSend.from_peer.channel_id = chat.id; reqSend.from_peer.channel_id = chat.id;
@ -4359,16 +4349,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
reqSend.id.add(fwdId); reqSend.id.add(fwdId);
} else { } else {
if (retryMessageObject.messageOwner.ttl != 0) { reqSend.from_peer = new TLRPC.TL_inputPeerEmpty();
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.silent = newMsg.silent; reqSend.silent = newMsg.silent;
if (scheduleDate != 0) { if (scheduleDate != 0) {
@ -5059,7 +5040,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
LongSparseArray<Integer> newIds = new LongSparseArray<>(); LongSparseArray<Integer> newIds = new LongSparseArray<>();
final TLRPC.Updates updates = (TLRPC.Updates) response; final TLRPC.Updates updates = (TLRPC.Updates) response;
ArrayList<TLRPC.Update> updatesArr = ((TLRPC.Updates) response).updates; ArrayList<TLRPC.Update> updatesArr = ((TLRPC.Updates) response).updates;
SparseArray<SparseArray<TLRPC.TL_messageReplies>> channelReplies = null; LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelReplies = null;
for (int a = 0; a < updatesArr.size(); a++) { for (int a = 0; a < updatesArr.size(); a++) {
TLRPC.Update update = updatesArr.get(a); TLRPC.Update update = updatesArr.get(a);
if (update instanceof TLRPC.TL_updateMessageID) { if (update instanceof TLRPC.TL_updateMessageID) {
@ -5075,20 +5056,20 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
a--; a--;
} else if (update instanceof TLRPC.TL_updateNewChannelMessage) { } else if (update instanceof TLRPC.TL_updateNewChannelMessage) {
final TLRPC.TL_updateNewChannelMessage newMessage = (TLRPC.TL_updateNewChannelMessage) update; 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); 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 ((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) { if (channelReplies == null) {
channelReplies = new SparseArray<>(); channelReplies = new LongSparseArray<>();
} }
int did = (int) MessageObject.getDialogId(newMessage.message); long did = MessageObject.getDialogId(newMessage.message);
SparseArray<TLRPC.TL_messageReplies> replies = channelReplies.get(did); SparseArray<TLRPC.MessageReplies> replies = channelReplies.get(did);
if (replies == null) { if (replies == null) {
replies = new SparseArray<>(); replies = new SparseArray<>();
channelReplies.put(did, replies); 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; 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) { if (messageReplies == null) {
messageReplies = new TLRPC.TL_messageReplies(); messageReplies = new TLRPC.TL_messageReplies();
replies.put(id, messageReplies); replies.put(id, messageReplies);
@ -5111,7 +5092,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
} }
if (channelReplies != null) { if (channelReplies != null) {
getMessagesStorage().putChannelViews(null, null, channelReplies, true, true); getMessagesStorage().putChannelViews(null, null, channelReplies, true);
getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, 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; newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, grouped_id, existFlags, scheduled);
getMessagesStorage().getStorageQueue().postRunnable(() -> { 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); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduled);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id);
@ -5363,7 +5344,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
final TLRPC.Updates updates = (TLRPC.Updates) response; final TLRPC.Updates updates = (TLRPC.Updates) response;
ArrayList<TLRPC.Update> updatesArr = ((TLRPC.Updates) response).updates; ArrayList<TLRPC.Update> updatesArr = ((TLRPC.Updates) response).updates;
TLRPC.Message message = null; TLRPC.Message message = null;
SparseArray<SparseArray<TLRPC.TL_messageReplies>> channelReplies = null; LongSparseArray<SparseArray<TLRPC.MessageReplies>> channelReplies = null;
for (int a = 0; a < updatesArr.size(); a++) { for (int a = 0; a < updatesArr.size(); a++) {
TLRPC.Update update = updatesArr.get(a); TLRPC.Update update = updatesArr.get(a);
if (update instanceof TLRPC.TL_updateNewMessage) { if (update instanceof TLRPC.TL_updateNewMessage) {
@ -5374,20 +5355,20 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
break; break;
} else if (update instanceof TLRPC.TL_updateNewChannelMessage) { } else if (update instanceof TLRPC.TL_updateNewChannelMessage) {
final TLRPC.TL_updateNewChannelMessage newMessage = (TLRPC.TL_updateNewChannelMessage) update; 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); 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 ((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) { if (channelReplies == null) {
channelReplies = new SparseArray<>(); channelReplies = new LongSparseArray<>();
} }
int did = (int) MessageObject.getDialogId(newMessage.message); long did = MessageObject.getDialogId(newMessage.message);
SparseArray<TLRPC.TL_messageReplies> replies = channelReplies.get(did); SparseArray<TLRPC.MessageReplies> replies = channelReplies.get(did);
if (replies == null) { if (replies == null) {
replies = new SparseArray<>(); replies = new SparseArray<>();
channelReplies.put(did, replies); 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; 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) { if (messageReplies == null) {
messageReplies = new TLRPC.TL_messageReplies(); messageReplies = new TLRPC.TL_messageReplies();
replies.put(id, messageReplies); replies.put(id, messageReplies);
@ -5410,7 +5391,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
} }
if (channelReplies != null) { if (channelReplies != null) {
getMessagesStorage().putChannelViews(null, null, channelReplies, true, true); getMessagesStorage().putChannelViews(null, null, channelReplies, true);
getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, null, null, channelReplies, true); getNotificationCenter().postNotificationName(NotificationCenter.didUpdateMessagesViews, null, null, channelReplies, true);
} }
if (message != null) { if (message != null) {
@ -5455,7 +5436,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
if (scheduled && !currentSchedule) { if (scheduled && !currentSchedule) {
ArrayList<Integer> messageIds = new ArrayList<>(); ArrayList<Integer> messageIds = new ArrayList<>();
messageIds.add(oldId); 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().getStorageQueue().postRunnable(() -> {
getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, false);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
@ -5473,7 +5454,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} else { } else {
getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled); getNotificationCenter().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, newMsgObj.dialog_id, 0L, existFlags, scheduled);
getMessagesStorage().getStorageQueue().postRunnable(() -> { 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); getMessagesStorage().putMessages(sentMessages, true, false, false, 0, scheduled);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id); getMediaDataController().increasePeerRaiting(newMsgObj.dialog_id);
@ -5823,16 +5804,15 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
return importingHistoryMap.size() != 0; return importingHistoryMap.size() != 0;
} }
public void prepareImportHistory(long dialogId, Uri uri, ArrayList<Uri> mediaUris, MessagesStorage.IntCallback onStartImport) { public void prepareImportHistory(long dialogId, Uri uri, ArrayList<Uri> mediaUris, MessagesStorage.LongCallback onStartImport) {
if (importingHistoryMap.get(dialogId) != null) { if (importingHistoryMap.get(dialogId) != null) {
onStartImport.run(0); onStartImport.run(0);
return; return;
} }
int lowerId = (int) dialogId; if (DialogObject.isChatDialog(dialogId)) {
if (lowerId < 0) { TLRPC.Chat chat = getMessagesController().getChat(-dialogId);
TLRPC.Chat chat = getMessagesController().getChat(-lowerId);
if (chat != null && !chat.megagroup) { if (chat != null && !chat.megagroup) {
getMessagesController().convertToMegaGroup(null, -lowerId, null, (chatId) -> { getMessagesController().convertToMegaGroup(null, -dialogId, null, (chatId) -> {
if (chatId != 0) { if (chatId != 0) {
prepareImportHistory(-chatId, uri, mediaUris, onStartImport); prepareImportHistory(-chatId, uri, mediaUris, onStartImport);
} else { } else {
@ -5847,7 +5827,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
ImportingHistory importingHistory = new ImportingHistory(); ImportingHistory importingHistory = new ImportingHistory();
importingHistory.mediaPaths = uris; importingHistory.mediaPaths = uris;
importingHistory.dialogId = dialogId; importingHistory.dialogId = dialogId;
importingHistory.peer = getMessagesController().getInputPeer((int) dialogId); importingHistory.peer = getMessagesController().getInputPeer(dialogId);
HashMap<String, ImportingHistory> files = new HashMap<>(); HashMap<String, ImportingHistory> files = new HashMap<>();
for (int a = 0, N = uris.size(); a < N + 1; a++) { for (int a = 0, N = uris.size(); a < N + 1; a++) {
Uri mediaUri; Uri mediaUri;
@ -5903,7 +5883,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
importingHistoryMap.put(dialogId, importingHistory); importingHistoryMap.put(dialogId, importingHistory);
getFileLoader().uploadFile(importingHistory.historyPath, false, true, 0, ConnectionsManager.FileTypeFile, true); getFileLoader().uploadFile(importingHistory.historyPath, false, true, 0, ConnectionsManager.FileTypeFile, true);
getNotificationCenter().postNotificationName(NotificationCenter.historyImportProgressChanged, dialogId); getNotificationCenter().postNotificationName(NotificationCenter.historyImportProgressChanged, dialogId);
onStartImport.run((int) dialogId); onStartImport.run(dialogId);
Intent intent = new Intent(ApplicationLoader.applicationContext, ImportingService.class); Intent intent = new Intent(ApplicationLoader.applicationContext, ImportingService.class);
try { try {
@ -6036,7 +6016,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
return false; return false;
} }
boolean isEncrypted = (int) dialogId == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
String name = f.getName(); String name = f.getName();
String ext = ""; String ext = "";
@ -6302,7 +6282,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
String originalPath = messageObject.messageOwner.attachPath; String originalPath = messageObject.messageOwner.attachPath;
final File f = new File(originalPath); final File f = new File(originalPath);
boolean isEncrypted = (int) dialogId == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
if (!isEncrypted && count > 1 && mediaCount % 10 == 0) { if (!isEncrypted && count > 1 && mediaCount % 10 == 0) {
groupId = Utilities.random.nextLong(); groupId = Utilities.random.nextLong();
mediaCount = 0; mediaCount = 0;
@ -6327,8 +6307,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
if (isEncrypted) { if (isEncrypted) {
int high_id = (int) (dialogId >> 32); int encryptedChatId = DialogObject.getEncryptedChatId(dialogId);
TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(high_id); TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(encryptedChatId);
if (encryptedChat == null) { if (encryptedChat == null) {
return; return;
} }
@ -6391,7 +6371,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
int mediaCount = 0; int mediaCount = 0;
Integer[] docType = new Integer[1]; Integer[] docType = new Integer[1];
boolean isEncrypted = (int) dialogId == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
if (paths != null) { if (paths != null) {
int count = paths.size(); int count = paths.size();
@ -6484,13 +6464,13 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
} }
if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto) { if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto) {
new Thread(() -> { new Thread(() -> {
boolean isEncrypted = (int) dialogId == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
String finalPath = null; String finalPath = null;
TLRPC.TL_document document = null; TLRPC.TL_document document = null;
TLRPC.TL_photo photo = null; TLRPC.TL_photo photo = null;
TLRPC.TL_game game = null; TLRPC.TL_game game = null;
if ("game".equals(result.type)) { if ("game".equals(result.type)) {
if ((int) dialogId == 0) { if (isEncrypted) {
return; //doesn't work in secret chats for now return; //doesn't work in secret chats for now
} }
game = new TLRPC.TL_game(); game = new TLRPC.TL_game();
@ -6749,7 +6729,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
}).run(); }).run();
} else if (result.send_message instanceof TLRPC.TL_botInlineMessageText) { } else if (result.send_message instanceof TLRPC.TL_botInlineMessageText) {
TLRPC.WebPage webPage = null; TLRPC.WebPage webPage = null;
if ((int) dialogId == 0) { if (DialogObject.isEncryptedDialog(dialogId)) {
for (int a = 0; a < result.send_message.entities.size(); a++) { for (int a = 0; a < result.send_message.entities.size(); a++) {
TLRPC.MessageEntity entity = result.send_message.entities.get(a); TLRPC.MessageEntity entity = result.send_message.entities.get(a);
if (entity instanceof TLRPC.TL_messageEntityUrl) { if (entity instanceof TLRPC.TL_messageEntityUrl) {
@ -6798,7 +6778,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
user.restriction_reason.add(reason); user.restriction_reason.add(reason);
accountInstance.getSendMessagesHelper().sendMessage(user, dialogId, replyToMsg, replyToTopMsg, result.send_message.reply_markup, params, notify, scheduleDate); accountInstance.getSendMessagesHelper().sendMessage(user, dialogId, replyToMsg, replyToTopMsg, result.send_message.reply_markup, params, notify, scheduleDate);
} else if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaInvoice) { } 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 return; //doesn't work in secret chats for now
} }
TLRPC.TL_botInlineMessageMediaInvoice invoice = (TLRPC.TL_botInlineMessageMediaInvoice) result.send_message; 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(); long beginTime = System.currentTimeMillis();
HashMap<SendingMediaInfo, MediaSendPrepareWorker> workers; HashMap<SendingMediaInfo, MediaSendPrepareWorker> workers;
int count = media.size(); int count = media.size();
boolean isEncrypted = (int) dialogId == 0;
boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
if (!forceDocument && groupMediaFinal) { if (!forceDocument && groupMediaFinal) {
workers = new HashMap<>(); workers = new HashMap<>();
for (int a = 0; a < count; a++) { for (int a = 0; a < count; a++) {
@ -7862,12 +7843,14 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
compressionsCount = 1; 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) { if (selectedCompression > compressionsCount) {
selectedCompression = compressionsCount - 1; selectedCompression = compressionsCount;
} }
if (selectedCompression != compressionsCount - 1) { boolean needCompress = false;
if (selectedCompression != compressionsCount - 1 || Math.max(videoEditedInfo.originalWidth, videoEditedInfo.originalHeight) > 1280) {
needCompress = true;
switch (selectedCompression) { switch (selectedCompression) {
case 1: case 1:
maxSize = 432.0f; maxSize = 432.0f;
@ -7892,7 +7875,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
videoEditedInfo.resultHeight, videoEditedInfo.resultWidth videoEditedInfo.resultHeight, videoEditedInfo.resultWidth
); );
if (selectedCompression == compressionsCount - 1) { if (!needCompress) {
videoEditedInfo.resultWidth = videoEditedInfo.originalWidth; videoEditedInfo.resultWidth = videoEditedInfo.originalWidth;
videoEditedInfo.resultHeight = videoEditedInfo.originalHeight; videoEditedInfo.resultHeight = videoEditedInfo.originalHeight;
videoEditedInfo.bitrate = bitrate; videoEditedInfo.bitrate = bitrate;
@ -7917,7 +7900,7 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
new Thread(() -> { new Thread(() -> {
final VideoEditedInfo videoEditedInfo = info != null ? info : createCompressionSettings(videoPath); final VideoEditedInfo videoEditedInfo = info != null ? info : createCompressionSettings(videoPath);
boolean isEncrypted = (int) dialogId == 0; boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
boolean isRound = videoEditedInfo != null && videoEditedInfo.roundVideo; boolean isRound = videoEditedInfo != null && videoEditedInfo.roundVideo;
Bitmap thumb = null; Bitmap thumb = null;
@ -7982,8 +7965,8 @@ public class SendMessagesHelper extends BaseController implements NotificationCe
accountInstance.getUserConfig().saveConfig(false); accountInstance.getUserConfig().saveConfig(false);
TLRPC.TL_documentAttributeVideo attributeVideo; TLRPC.TL_documentAttributeVideo attributeVideo;
if (isEncrypted) { if (isEncrypted) {
int high_id = (int) (dialogId >> 32); int encryptedChatId = DialogObject.getEncryptedChatId(dialogId);
TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(high_id); TLRPC.EncryptedChat encryptedChat = accountInstance.getMessagesController().getEncryptedChat(encryptedChatId);
if (encryptedChat == null) { if (encryptedChat == null) {
return; return;
} }

View file

@ -23,8 +23,8 @@ import android.util.SparseArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.SerializedData;
import org.telegram.ui.Components.SwipeGestureSettingsView;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.SwipeGestureSettingsView;
import java.io.File; import java.io.File;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
@ -116,6 +116,9 @@ public class SharedConfig {
public static int fontSize = 16; public static int fontSize = 16;
public static int bubbleRadius = 10; public static int bubbleRadius = 10;
public static int ivFontSize = 16; 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 TLRPC.TL_help_appUpdate pendingAppUpdate;
public static int pendingAppUpdateBuildVersion; public static int pendingAppUpdateBuildVersion;
@ -364,6 +367,9 @@ public class SharedConfig {
disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false); disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false);
noiseSupression = preferences.getBoolean("noiseSupression", false); noiseSupression = preferences.getBoolean("noiseSupression", false);
chatSwipeAction = preferences.getInt("ChatSwipeAction", -1); 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); preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true); showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true);
@ -522,6 +528,9 @@ public class SharedConfig {
scheduledOrNoSoundHintShows = 0; scheduledOrNoSoundHintShows = 0;
lockRecordAudioVideoHint = 0; lockRecordAudioVideoHint = 0;
forwardingOptionsHintShown = false; forwardingOptionsHintShown = false;
messageSeenHintCount = 3;
emojiInteractionsHintCount = 3;
dayNightThemeSwitchHintCount = 3;
saveConfig(); saveConfig();
} }
@ -1033,8 +1042,6 @@ public class SharedConfig {
public static void checkSaveToGalleryFiles() { public static void checkSaveToGalleryFiles() {
Utilities.globalQueue.postRunnable(() -> { Utilities.globalQueue.postRunnable(() -> {
try { try {
File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram"); File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram");
File imagePath = new File(telegramPath, "Telegram Images"); File imagePath = new File(telegramPath, "Telegram Images");
imagePath.mkdir(); imagePath.mkdir();
@ -1081,6 +1088,25 @@ public class SharedConfig {
preferences.edit().putInt("ChatSwipeAction", chatSwipeAction).apply(); 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_LOW = 0;
public final static int PERFORMANCE_CLASS_AVERAGE = 1; public final static int PERFORMANCE_CLASS_AVERAGE = 1;
public final static int PERFORMANCE_CLASS_HIGH = 2; public final static int PERFORMANCE_CLASS_HIGH = 2;

View file

@ -47,7 +47,7 @@ public class SmsReceiver extends BroadcastReceiver {
if (matcher.find()) { if (matcher.find()) {
String code = matcher.group(0).replace("-", ""); String code = matcher.group(0).replace("-", "");
if (code.length() >= 3) { if (code.length() >= 3) {
if (preferences != null && hash != null) { if (hash != null) {
preferences.edit().putString("sms_hash_code", hash + "|" + code).commit(); preferences.edit().putString("sms_hash_code", hash + "|" + code).commit();
} }
AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReceiveSmsCode, code)); AndroidUtilities.runOnUIThread(() -> NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReceiveSmsCode, code));

View file

@ -106,7 +106,6 @@ public class SvgHelper {
protected int height; protected int height;
private static int[] parentPosition = new int[2]; private static int[] parentPosition = new int[2];
private Shader backgroundGradient;
private Bitmap backgroundBitmap; private Bitmap backgroundBitmap;
private Canvas backgroundCanvas; private Canvas backgroundCanvas;
private LinearGradient placeholderGradient; 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)); color = Color.argb((int) (Color.alpha(color) / 2 * colorAlpha), Color.red(color), Color.green(color), Color.blue(color));
float centerX = (1.0f - w) / 2; 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); 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) { if (Build.VERSION.SDK_INT >= 28) {
backgroundGradient = new LinearGradient(0, 0, gradientWidth, 0, new int[]{color, color}, null, Shader.TileMode.REPEAT); backgroundGradient = new LinearGradient(0, 0, gradientWidth, 0, new int[]{color, color}, null, Shader.TileMode.REPEAT);
} else { } else {

View file

@ -31,7 +31,7 @@ public class UserConfig extends BaseController {
public int lastSendMessageId = -210000; public int lastSendMessageId = -210000;
public int lastBroadcastId = -1; public int lastBroadcastId = -1;
public int contactsSavedCount; public int contactsSavedCount;
public int clientUserId; public long clientUserId;
public int lastContactsSyncTime; public int lastContactsSyncTime;
public int lastHintsSyncTime; public int lastHintsSyncTime;
public boolean draftsLoaded; public boolean draftsLoaded;
@ -43,9 +43,9 @@ public class UserConfig extends BaseController {
public boolean hasValidDialogLoadIds; public boolean hasValidDialogLoadIds;
public int migrateOffsetId = -1; public int migrateOffsetId = -1;
public int migrateOffsetDate = -1; public int migrateOffsetDate = -1;
public int migrateOffsetUserId = -1; public long migrateOffsetUserId = -1;
public int migrateOffsetChatId = -1; public long migrateOffsetChatId = -1;
public int migrateOffsetChannelId = -1; public long migrateOffsetChannelId = -1;
public long migrateOffsetAccess = -1; public long migrateOffsetAccess = -1;
public boolean filtersLoaded; public boolean filtersLoaded;
@ -136,9 +136,9 @@ public class UserConfig extends BaseController {
editor.putInt("6migrateOffsetId", migrateOffsetId); editor.putInt("6migrateOffsetId", migrateOffsetId);
if (migrateOffsetId != -1) { if (migrateOffsetId != -1) {
editor.putInt("6migrateOffsetDate", migrateOffsetDate); editor.putInt("6migrateOffsetDate", migrateOffsetDate);
editor.putInt("6migrateOffsetUserId", migrateOffsetUserId); editor.putLong("6migrateOffsetUserId", migrateOffsetUserId);
editor.putInt("6migrateOffsetChatId", migrateOffsetChatId); editor.putLong("6migrateOffsetChatId", migrateOffsetChatId);
editor.putInt("6migrateOffsetChannelId", migrateOffsetChannelId); editor.putLong("6migrateOffsetChannelId", migrateOffsetChannelId);
editor.putLong("6migrateOffsetAccess", migrateOffsetAccess); editor.putLong("6migrateOffsetAccess", migrateOffsetAccess);
} }
@ -197,7 +197,7 @@ public class UserConfig extends BaseController {
} }
} }
public int getClientUserId() { public long getClientUserId() {
synchronized (sync) { synchronized (sync) {
return currentUser != null ? currentUser.id : 0; return currentUser != null ? currentUser.id : 0;
} }
@ -271,9 +271,9 @@ public class UserConfig extends BaseController {
migrateOffsetId = preferences.getInt("6migrateOffsetId", 0); migrateOffsetId = preferences.getInt("6migrateOffsetId", 0);
if (migrateOffsetId != -1) { if (migrateOffsetId != -1) {
migrateOffsetDate = preferences.getInt("6migrateOffsetDate", 0); migrateOffsetDate = preferences.getInt("6migrateOffsetDate", 0);
migrateOffsetUserId = preferences.getInt("6migrateOffsetUserId", 0); migrateOffsetUserId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetUserId", 0);
migrateOffsetChatId = preferences.getInt("6migrateOffsetChatId", 0); migrateOffsetChatId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChatId", 0);
migrateOffsetChannelId = preferences.getInt("6migrateOffsetChannelId", 0); migrateOffsetChannelId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChannelId", 0);
migrateOffsetAccess = preferences.getLong("6migrateOffsetAccess", 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_dialogsLoadOffsetUserId = 2;
public static final int i_dialogsLoadOffsetChatId = 3; public static final int i_dialogsLoadOffsetChatId = 3;
public static final int i_dialogsLoadOffsetChannelId = 4; public static final int i_dialogsLoadOffsetChannelId = 4;
public static final int i_dialogsLoadOffsetAccess_1 = 5; public static final int i_dialogsLoadOffsetAccess = 5;
public static final int i_dialogsLoadOffsetAccess_2 = 6;
public int getTotalDialogsCount(int folderId) { public int getTotalDialogsCount(int folderId) {
return getPreferences().getInt("2totalDialogsLoadCount" + (folderId == 0 ? "" : folderId), 0); 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(); getPreferences().edit().putInt("2totalDialogsLoadCount" + (folderId == 0 ? "" : folderId), totalDialogsLoadCount).commit();
} }
public int[] getDialogLoadOffsets(int folderId) { public long[] getDialogLoadOffsets(int folderId) {
SharedPreferences preferences = getPreferences(); SharedPreferences preferences = getPreferences();
int dialogsLoadOffsetId = preferences.getInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); int dialogsLoadOffsetId = preferences.getInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1);
int dialogsLoadOffsetDate = preferences.getInt("2dialogsLoadOffsetDate" + (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); long dialogsLoadOffsetUserId = AndroidUtilities.getPrefIntOrLong(preferences, "2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1);
int dialogsLoadOffsetChatId = preferences.getInt("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1); long dialogsLoadOffsetChatId = AndroidUtilities.getPrefIntOrLong(preferences, "2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), hasValidDialogLoadIds ? 0 : -1);
int dialogsLoadOffsetChannelId = preferences.getInt("2dialogsLoadOffsetChannelId" + (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); 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(); SharedPreferences.Editor editor = getPreferences().edit();
editor.putInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetId); editor.putInt("2dialogsLoadOffsetId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetId);
editor.putInt("2dialogsLoadOffsetDate" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetDate); editor.putInt("2dialogsLoadOffsetDate" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetDate);
editor.putInt("2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetUserId); editor.putLong("2dialogsLoadOffsetUserId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetUserId);
editor.putInt("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChatId); editor.putLong("2dialogsLoadOffsetChatId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChatId);
editor.putInt("2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChannelId); editor.putLong("2dialogsLoadOffsetChannelId" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetChannelId);
editor.putLong("2dialogsLoadOffsetAccess" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetAccess); editor.putLong("2dialogsLoadOffsetAccess" + (folderId == 0 ? "" : folderId), dialogsLoadOffsetAccess);
editor.putBoolean("hasValidDialogLoadIds", true); editor.putBoolean("hasValidDialogLoadIds", true);
editor.commit(); editor.commit();

View file

@ -374,7 +374,7 @@ public class VideoEditedInfo {
} }
public boolean needConvert() { 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() { public boolean canAutoPlaySourceVideo() {

View file

@ -107,7 +107,7 @@ public class VideoEncodingService extends Service implements NotificationCenter.
} }
} }
currentProgress = 0; currentProgress = 0;
builder.setProgress(100, currentProgress, currentProgress == 0); builder.setProgress(100, currentProgress, true);
startForeground(4, builder.build()); startForeground(4, builder.build());
NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build()); NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build());
return Service.START_NOT_STICKY; return Service.START_NOT_STICKY;

View file

@ -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<MessageObject> arr = (ArrayList<MessageObject>) 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<Node> 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;
}
}

View file

@ -31,41 +31,39 @@ public class WearReplyReceiver extends BroadcastReceiver {
if (TextUtils.isEmpty(text)) { if (TextUtils.isEmpty(text)) {
return; return;
} }
long dialog_id = intent.getLongExtra("dialog_id", 0); long dialogId = intent.getLongExtra("dialog_id", 0);
int max_id = intent.getIntExtra("max_id", 0); int maxId = intent.getIntExtra("max_id", 0);
int currentAccount = intent.getIntExtra("currentAccount", 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; return;
} }
int lowerId = (int) dialog_id;
int highId = (int) (dialog_id >> 32);
AccountInstance accountInstance = AccountInstance.getInstance(currentAccount); AccountInstance accountInstance = AccountInstance.getInstance(currentAccount);
if (lowerId > 0) { if (DialogObject.isUserDialog(dialogId)) {
TLRPC.User user = accountInstance.getMessagesController().getUser(lowerId); TLRPC.User user = accountInstance.getMessagesController().getUser(dialogId);
if (user == null) { if (user == null) {
Utilities.globalQueue.postRunnable(() -> { Utilities.globalQueue.postRunnable(() -> {
TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(lowerId); TLRPC.User user1 = accountInstance.getMessagesStorage().getUserSync(dialogId);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
accountInstance.getMessagesController().putUser(user1, true); accountInstance.getMessagesController().putUser(user1, true);
sendMessage(accountInstance, text, dialog_id, max_id); sendMessage(accountInstance, text, dialogId, maxId);
}); });
}); });
return; return;
} }
} else if (lowerId < 0) { } else if (DialogObject.isChatDialog(dialogId)) {
TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-lowerId); TLRPC.Chat chat = accountInstance.getMessagesController().getChat(-dialogId);
if (chat == null) { if (chat == null) {
Utilities.globalQueue.postRunnable(() -> { Utilities.globalQueue.postRunnable(() -> {
TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-lowerId); TLRPC.Chat chat1 = accountInstance.getMessagesStorage().getChatSync(-dialogId);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
accountInstance.getMessagesController().putChat(chat1, true); accountInstance.getMessagesController().putChat(chat1, true);
sendMessage(accountInstance, text, dialog_id, max_id); sendMessage(accountInstance, text, dialogId, maxId);
}); });
}); });
return; 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) { private void sendMessage(AccountInstance accountInstance, CharSequence text, long dialog_id, int max_id) {

View file

@ -239,6 +239,7 @@ public class CameraController implements MediaRecorder.OnInfoListener {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.cameraInitied); NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.cameraInitied);
}); });
} catch (Exception e) { } catch (Exception e) {
FileLog.e(e);
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
onFinishCameraInitRunnables.clear(); onFinishCameraInitRunnables.clear();
loadingCameras = false; loadingCameras = false;
@ -247,7 +248,6 @@ public class CameraController implements MediaRecorder.OnInfoListener {
AndroidUtilities.runOnUIThread(() -> initCamera(onInitRunnable, true), 1000); AndroidUtilities.runOnUIThread(() -> initCamera(onInitRunnable, true), 1000);
} }
}); });
} }
}); });
} }

View file

@ -264,8 +264,6 @@ public class CameraSession {
if (params.getMaxNumMeteringAreas() > 0) { if (params.getMaxNumMeteringAreas() > 0) {
meteringAreaSupported = true; meteringAreaSupported = true;
} }
} }
} }
} catch (Throwable e) { } catch (Throwable e) {

View file

@ -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.
*
* <p>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%.</p>
*
* <p>It is possible to iterate over the items in this container using
* {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
* <code>keyAt(int)</code> 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 <code>valueAt(int)</code>.</p>
*/
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 <code>0</code>
* 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 <code>0...size()-1</code>, returns
* the key from the <code>index</code>th key-value mapping that this
* SparseLongArray stores.
*/
public long keyAt(int index) {
return mKeys[index];
}
/**
* Given an index in the range <code>0...size()-1</code>, returns
* the value from the <code>index</code>th 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;
}
}

View file

@ -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.
*
* <p>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%.</p>
*
* <p>It is possible to iterate over the items in this container using
* {@link #keyAt(int)} and {@link #valueAt(int)}. Iterating over the keys using
* <code>keyAt(int)</code> 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 <code>valueAt(int)</code>.</p>
*/
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 <code>0</code>
* 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 <code>0...size()-1</code>, returns
* the key from the <code>index</code>th key-value mapping that this
* SparseLongArray stores.
*/
public long keyAt(int index) {
return mKeys[index];
}
/**
* Given an index in the range <code>0...size()-1</code>, returns
* the value from the <code>index</code>th 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;
}
}

View file

@ -7,10 +7,21 @@ import android.media.MediaExtractor;
import android.media.MediaFormat; import android.media.MediaFormat;
import android.os.Build; 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.BuildVars;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController; 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.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.io.File;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -70,6 +81,7 @@ public class MediaCodecVideoConvertor {
boolean isPhoto, boolean isPhoto,
MediaController.CropState cropState) { MediaController.CropState cropState) {
long time = System.currentTimeMillis();
boolean error = false; boolean error = false;
boolean repeatWithIncreasedTimeout = false; boolean repeatWithIncreasedTimeout = false;
int videoTrackIndex = -5; int videoTrackIndex = -5;
@ -784,6 +796,11 @@ public class MediaCodecVideoConvertor {
isPhoto, cropState); 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; return error;
} }

View file

@ -15,7 +15,7 @@ import org.telegram.ui.Components.voip.VoIPHelper;
public final class VoIPPendingCall { 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); return new VoIPPendingCall(activity, userId, video, 1000, accountInstance);
} }
@ -27,7 +27,7 @@ public final class VoIPPendingCall {
private final Runnable releaseRunnable = () -> onConnectionStateUpdated(true); private final Runnable releaseRunnable = () -> onConnectionStateUpdated(true);
private final int userId; private final long userId;
private final boolean video; private final boolean video;
private final Activity activity; private final Activity activity;
@ -36,7 +36,7 @@ public final class VoIPPendingCall {
private boolean released; private boolean released;
private AccountInstance accountInstance; 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.activity = activity;
this.userId = userId; this.userId = userId;
this.video = video; this.video = video;

View file

@ -483,7 +483,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
public boolean mutedByAdmin() { public boolean mutedByAdmin() {
ChatObject.Call call = groupCall; ChatObject.Call call = groupCall;
if (call != null) { if (call != null) {
int selfId = getSelfId(); long selfId = getSelfId();
TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId); TLRPC.TL_groupCallParticipant participant = call.participants.get(selfId);
if (participant != null && !participant.can_self_unmute && participant.muted && !ChatObject.canManageCalls(chat)) { if (participant != null && !participant.can_self_unmute && participant.muted && !ChatObject.canManageCalls(chat)) {
return true; return true;
@ -666,14 +666,14 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
throw new IllegalStateException("No account specified when starting VoIP service"); throw new IllegalStateException("No account specified when starting VoIP service");
} }
classGuid = ConnectionsManager.generateClassGuid(); classGuid = ConnectionsManager.generateClassGuid();
int userID = intent.getIntExtra("user_id", 0); long userID = intent.getLongExtra("user_id", 0);
int chatID = intent.getIntExtra("chat_id", 0); long chatID = intent.getLongExtra("chat_id", 0);
createGroupCall = intent.getBooleanExtra("createGroupCall", false); createGroupCall = intent.getBooleanExtra("createGroupCall", false);
hasFewPeers = intent.getBooleanExtra("hasFewPeers", false); hasFewPeers = intent.getBooleanExtra("hasFewPeers", false);
joinHash = intent.getStringExtra("hash"); joinHash = intent.getStringExtra("hash");
int peerChannelId = intent.getIntExtra("peerChannelId", 0); long peerChannelId = intent.getLongExtra("peerChannelId", 0);
int peerChatId = intent.getIntExtra("peerChatId", 0); long peerChatId = intent.getLongExtra("peerChatId", 0);
int peerUserId = intent.getIntExtra("peerUserId", 0); long peerUserId = intent.getLongExtra("peerUserId", 0);
if (peerChatId != 0) { if (peerChatId != 0) {
groupCallPeer = new TLRPC.TL_inputPeerChat(); groupCallPeer = new TLRPC.TL_inputPeerChat();
groupCallPeer.chat_id = peerChatId; groupCallPeer.chat_id = peerChatId;
@ -836,7 +836,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
createGroupInstance(CAPTURE_DEVICE_CAMERA, false); createGroupInstance(CAPTURE_DEVICE_CAMERA, false);
} }
public int getCallerId() { public long getCallerId() {
if (user != null) { if (user != null) {
return user.id; return user.id;
} else { } else {
@ -1321,7 +1321,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
tgVoip[CAPTURE_DEVICE_CAMERA].onSignalingDataReceive(data.data); tgVoip[CAPTURE_DEVICE_CAMERA].onSignalingDataReceive(data.data);
} }
public int getSelfId() { public long getSelfId() {
if (groupCallPeer == null) { if (groupCallPeer == null) {
return UserConfig.getInstance(currentAccount).clientUserId; 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) { if (chat == null || groupCall == null || groupCall.call.id != update.call.id) {
return; return;
} }
int selfId = getSelfId(); long selfId = getSelfId();
for (int a = 0, N = update.participants.size(); a < N; a++) { for (int a = 0, N = update.participants.size(); a < N; a++) {
TLRPC.TL_groupCallParticipant participant = update.participants.get(a); TLRPC.TL_groupCallParticipant participant = update.participants.get(a);
if (participant.left) { if (participant.left) {
@ -1748,7 +1748,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
if (response != null) { if (response != null) {
AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_CAMERA] = ssrc); AndroidUtilities.runOnUIThread(() -> mySource[CAPTURE_DEVICE_CAMERA] = ssrc);
TLRPC.Updates updates = (TLRPC.Updates) response; TLRPC.Updates updates = (TLRPC.Updates) response;
int selfId = getSelfId(); long selfId = getSelfId();
for (int a = 0, N = updates.updates.size(); a < N; a++) { for (int a = 0, N = updates.updates.size(); a < N; a++) {
TLRPC.Update update = updates.updates.get(a); TLRPC.Update update = updates.updates.get(a);
if (update instanceof TLRPC.TL_updateGroupCallParticipants) { if (update instanceof TLRPC.TL_updateGroupCallParticipants) {
@ -1817,7 +1817,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
TLRPC.Updates updates = (TLRPC.Updates) response; TLRPC.Updates updates = (TLRPC.Updates) response;
AndroidUtilities.runOnUIThread(() -> { AndroidUtilities.runOnUIThread(() -> {
if (tgVoip[CAPTURE_DEVICE_SCREEN] != null) { if (tgVoip[CAPTURE_DEVICE_SCREEN] != null) {
int selfId = getSelfId(); long selfId = getSelfId();
for (int a = 0, N = updates.updates.size(); a < N; a++) { for (int a = 0, N = updates.updates.size(); a < N; a++) {
TLRPC.Update update = updates.updates.get(a); TLRPC.Update update = updates.updates.get(a);
if (update instanceof TLRPC.TL_updateGroupCallConnection) { 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) { if (groupCall == null || tgVoip[CAPTURE_DEVICE_CAMERA] == null) {
return; return;
} }
int selfId = getSelfId(); long selfId = getSelfId();
ArrayList<RequestedParticipant> participants = null; ArrayList<RequestedParticipant> participants = null;
for (int a = 0, N = unknown.length; a < N; a++) { for (int a = 0, N = unknown.length; a < N; a++) {
TLRPC.TL_groupCallParticipant p = groupCall.participantsBySources.get(unknown[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()); startForeground(ID_ONGOING_CALL_NOTIFICATION, builder.getNotification());
} }
private void startRingtoneAndVibration(int chatID) { private void startRingtoneAndVibration(long chatID) {
SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount); SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
boolean needRing = am.getRingerMode() != AudioManager.RINGER_MODE_SILENT; boolean needRing = am.getRingerMode() != AudioManager.RINGER_MODE_SILENT;

View file

@ -352,7 +352,7 @@ public class ConnectionsManager extends BaseController {
return connectionState; return connectionState;
} }
public void setUserId(int id) { public void setUserId(long id) {
native_setUserId(currentAccount, id); native_setUserId(currentAccount, id);
} }
@ -365,13 +365,14 @@ public class ConnectionsManager extends BaseController {
native_setPushConnectionEnabled(currentAccount, value); 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); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
String proxyAddress = preferences.getString("proxy_ip", ""); String proxyAddress = preferences.getString("proxy_ip", "");
String proxyUsername = preferences.getString("proxy_user", ""); String proxyUsername = preferences.getString("proxy_user", "");
String proxyPassword = preferences.getString("proxy_pass", ""); String proxyPassword = preferences.getString("proxy_pass", "");
String proxySecret = preferences.getString("proxy_secret", ""); String proxySecret = preferences.getString("proxy_secret", "");
int proxyPort = preferences.getInt("proxy_port", 1080); int proxyPort = preferences.getInt("proxy_port", 1080);
if (preferences.getBoolean("proxy_enabled", false) && !TextUtils.isEmpty(proxyAddress)) { if (preferences.getBoolean("proxy_enabled", false) && !TextUtils.isEmpty(proxyAddress)) {
native_setProxySettings(currentAccount, proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret); native_setProxySettings(currentAccount, proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret);
} }
@ -680,6 +681,7 @@ public class ConnectionsManager extends BaseController {
if (secret == null) { if (secret == null) {
secret = ""; secret = "";
} }
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) { for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (enabled && !TextUtils.isEmpty(address)) { if (enabled && !TextUtils.isEmpty(address)) {
native_setProxySettings(a, address, port, username, password, secret); 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_bindRequestToGuid(int currentAccount, int requestToken, int guid);
public static native void native_applyDatacenterAddress(int currentAccount, int datacenterId, String ipAddress, int port); 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 int native_getConnectionState(int currentAccount);
public static native void native_setUserId(int currentAccount, int id); 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, int userId, boolean enablePushConnection, boolean hasNetwork, int networkType); 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_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_setLangCode(int currentAccount, String langCode);
public static native void native_setRegId(int currentAccount, String regId); public static native void native_setRegId(int currentAccount, String regId);

View file

@ -5,6 +5,7 @@ import org.telegram.messenger.FileLog;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.util.LinkedList;
public class NativeByteBuffer extends AbstractSerializedData { public class NativeByteBuffer extends AbstractSerializedData {
@ -14,20 +15,19 @@ public class NativeByteBuffer extends AbstractSerializedData {
private int len; private int len;
public boolean reused = true; public boolean reused = true;
private static final ThreadLocal<NativeByteBuffer> addressWrapper = new ThreadLocal<NativeByteBuffer>() { private static final ThreadLocal<LinkedList<NativeByteBuffer>> addressWrappers = new ThreadLocal<LinkedList<NativeByteBuffer>>() {
@Override @Override
protected NativeByteBuffer initialValue() { protected LinkedList<NativeByteBuffer> initialValue() {
return new NativeByteBuffer(0, true); return new LinkedList<>();
} }
}; };
public static NativeByteBuffer wrap(long address) { public static NativeByteBuffer wrap(long address) {
NativeByteBuffer result = addressWrapper.get();
if (address != 0) { if (address != 0) {
if (!result.reused) { LinkedList<NativeByteBuffer> queue = addressWrappers.get();
if (BuildVars.LOGS_ENABLED) { NativeByteBuffer result = queue.poll();
FileLog.e("forgot to reuse?"); if (result == null) {
} result = new NativeByteBuffer(0, true);
} }
result.address = address; result.address = address;
result.reused = false; result.reused = false;
@ -38,8 +38,10 @@ public class NativeByteBuffer extends AbstractSerializedData {
result.buffer.position(position); result.buffer.position(position);
} }
result.buffer.order(ByteOrder.LITTLE_ENDIAN); result.buffer.order(ByteOrder.LITTLE_ENDIAN);
return result;
} else {
return null;
} }
return result;
} }
private NativeByteBuffer(int address, boolean wrap) { private NativeByteBuffer(int address, boolean wrap) {
@ -567,6 +569,7 @@ public class NativeByteBuffer extends AbstractSerializedData {
public void reuse() { public void reuse() {
if (address != 0) { if (address != 0) {
addressWrappers.get().add(this);
reused = true; reused = true;
native_reuse(address); native_reuse(address);
} }

View file

@ -0,0 +1,10 @@
package org.telegram.tgnet;
public interface ResultCallback<T> {
void onComplete(T result);
default void onError(TLRPC.TL_error error) {}
default void onError(Throwable throwable) {}
}

File diff suppressed because it is too large Load diff

View file

@ -120,10 +120,18 @@ public class ActionBar extends FrameLayout {
private boolean centerScale; private boolean centerScale;
private CharSequence subtitle; private CharSequence subtitle;
private View.OnTouchListener interceptTouchEventListener;
private final Theme.ResourcesProvider resourcesProvider;
EllipsizeSpanAnimator ellipsizeSpanAnimator = new EllipsizeSpanAnimator(this); EllipsizeSpanAnimator ellipsizeSpanAnimator = new EllipsizeSpanAnimator(this);
public ActionBar(Context context) { public ActionBar(Context context) {
this(context, null);
}
public ActionBar(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider;
setOnClickListener(v -> { setOnClickListener(v -> {
if (isSearchFieldVisible()) { if (isSearchFieldVisible()) {
return; 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) { protected boolean shouldClipChild(View child) {
@ -291,7 +299,7 @@ public class ActionBar extends FrameLayout {
subtitleTextView = new SimpleTextView(getContext()); subtitleTextView = new SimpleTextView(getContext());
subtitleTextView.setGravity(Gravity.LEFT); subtitleTextView.setGravity(Gravity.LEFT);
subtitleTextView.setVisibility(GONE); 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)); 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 = new SimpleTextView(getContext());
additionalSubtitleTextView.setGravity(Gravity.LEFT); additionalSubtitleTextView.setGravity(Gravity.LEFT);
additionalSubtitleTextView.setVisibility(GONE); 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)); 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) { if (titleColorToSet != 0) {
titleTextView[i].setTextColor(titleColorToSet); titleTextView[i].setTextColor(titleColorToSet);
} else { } else {
titleTextView[i].setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle)); titleTextView[i].setTextColor(getThemedColor(Theme.key_actionBarDefaultTitle));
} }
titleTextView[i].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleTextView[i].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(titleTextView[i], 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP)); 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.isActionMode = true;
actionMode.setClickable(true); actionMode.setClickable(true);
actionMode.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefault)); actionMode.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefault));
addView(actionMode, indexOfChild(backButtonImageView)); addView(actionMode, indexOfChild(backButtonImageView));
actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0); actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionMode.getLayoutParams(); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionMode.getLayoutParams();
@ -498,7 +506,7 @@ public class ActionBar extends FrameLayout {
if (occupyStatusBar && needTop && actionModeTop == null) { if (occupyStatusBar && needTop && actionModeTop == null) {
actionModeTop = new View(getContext()); actionModeTop = new View(getContext());
actionModeTop.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultTop)); actionModeTop.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultTop));
addView(actionModeTop); addView(actionModeTop);
layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams(); layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams();
layoutParams.height = AndroidUtilities.statusBarHeight; layoutParams.height = AndroidUtilities.statusBarHeight;
@ -755,7 +763,7 @@ public class ActionBar extends FrameLayout {
public void showActionModeTop() { public void showActionModeTop() {
if (occupyStatusBar && actionModeTop == null) { if (occupyStatusBar && actionModeTop == null) {
actionModeTop = new View(getContext()); actionModeTop = new View(getContext());
actionModeTop.setBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultTop)); actionModeTop.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultTop));
addView(actionModeTop); addView(actionModeTop);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams(); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) actionModeTop.getLayoutParams();
layoutParams.height = AndroidUtilities.statusBarHeight; layoutParams.height = AndroidUtilities.statusBarHeight;
@ -877,6 +885,10 @@ public class ActionBar extends FrameLayout {
interceptTouches = value; interceptTouches = value;
} }
public void setInterceptTouchEventListener(View.OnTouchListener listener) {
interceptTouchEventListener = listener;
}
public void setExtraHeight(int value) { public void setExtraHeight(int value) {
extraHeight = value; extraHeight = value;
if (actionMode != null) { if (actionMode != null) {
@ -1460,12 +1472,14 @@ public class ActionBar extends FrameLayout {
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) { public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
if (startValues != null && startValues.view instanceof SimpleTextView) { if (startValues != null && startValues.view instanceof SimpleTextView) {
AnimatorSet animatorSet = new AnimatorSet(); AnimatorSet animatorSet = new AnimatorSet();
Animator animator = super.createAnimator(sceneRoot, startValues, endValues); if (startValues != null && endValues != null) {
float s = (float) startValues.values.get("text_size") / (float) endValues.values.get("text_size"); Animator animator = super.createAnimator(sceneRoot, startValues, endValues);
startValues.view.setScaleX(s); float s = (float) startValues.values.get("text_size") / (float) endValues.values.get("text_size");
startValues.view.setScaleY(s); startValues.view.setScaleX(s);
if (animator != null) { startValues.view.setScaleY(s);
animatorSet.playTogether(animator); if (animator != null) {
animatorSet.playTogether(animator);
}
} }
animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_X, 1f)); animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_X, 1f));
animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_Y, 1f)); animatorSet.playTogether(ObjectAnimator.ofFloat(startValues.view, SCALE_Y, 1f));
@ -1495,4 +1509,12 @@ public class ActionBar extends FrameLayout {
TransitionManager.beginDelayedTransition(this, transitionSet); 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);
}
} }

View file

@ -24,9 +24,14 @@ import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Build; import android.os.Build;
import androidx.annotation.Keep; import androidx.annotation.Keep;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
import android.view.Gravity; import android.view.Gravity;
import android.view.HapticFeedbackConstants; import android.view.HapticFeedbackConstants;
import android.view.KeyEvent; import android.view.KeyEvent;
@ -54,14 +59,19 @@ import org.telegram.ui.Components.GroupCallPip;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
public class ActionBarLayout extends FrameLayout { public class ActionBarLayout extends FrameLayout {
public interface ActionBarLayoutDelegate { public interface ActionBarLayoutDelegate {
boolean onPreIme(); boolean onPreIme();
boolean needPresentFragment(BaseFragment fragment, boolean removeLast, boolean forceWithoutAnimation, ActionBarLayout layout); boolean needPresentFragment(BaseFragment fragment, boolean removeLast, boolean forceWithoutAnimation, ActionBarLayout layout);
boolean needAddFragmentToStack(BaseFragment fragment, ActionBarLayout layout); boolean needAddFragmentToStack(BaseFragment fragment, ActionBarLayout layout);
boolean needCloseLastFragment(ActionBarLayout layout); boolean needCloseLastFragment(ActionBarLayout layout);
void onRebuildAllFragments(ActionBarLayout layout, boolean last); void onRebuildAllFragments(ActionBarLayout layout, boolean last);
} }
@ -209,11 +219,32 @@ public class ActionBarLayout extends FrameLayout {
this.fragmentPanTranslationOffset = fragmentPanTranslationOffset; this.fragmentPanTranslationOffset = fragmentPanTranslationOffset;
invalidate(); invalidate();
} }
}
@Override public static class ThemeAnimationSettings {
public void setTranslationX(float translationX) {
Log.d("kek", "set translationX" + translationX); public final Theme.ThemeInfo theme;
super.setTranslationX(translationX); 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 boolean transitionAnimationPreviewMode;
private ArrayList<int[]> animateStartColors = new ArrayList<>(); private ArrayList<int[]> animateStartColors = new ArrayList<>();
private ArrayList<int[]> animateEndColors = new ArrayList<>(); private ArrayList<int[]> animateEndColors = new ArrayList<>();
StartColorsProvider startColorsProvider = new StartColorsProvider();
public Theme.MessageDrawable messageDrawableOutStart;
public Theme.MessageDrawable messageDrawableOutMediaStart;
public ThemeAnimationSettings.onAnimationProgress animationProgressListener;
private ArrayList<ArrayList<ThemeDescription>> themeAnimatorDescriptions = new ArrayList<>(); private ArrayList<ArrayList<ThemeDescription>> themeAnimatorDescriptions = new ArrayList<>();
private ArrayList<ThemeDescription> presentingFragmentDescriptions; private ArrayList<ThemeDescription> presentingFragmentDescriptions;
private ArrayList<ThemeDescription.ThemeDescriptionDelegate> themeAnimatorDelegate = new ArrayList<>(); private ArrayList<ThemeDescription.ThemeDescriptionDelegate> themeAnimatorDelegate = new ArrayList<>();
@ -372,8 +409,18 @@ public class ActionBarLayout extends FrameLayout {
invalidate(); invalidate();
if (fragmentsStack.size() >= 2 && containerView.getMeasuredWidth() > 0) { if (fragmentsStack.size() >= 2 && containerView.getMeasuredWidth() > 0) {
float progress = value / containerView.getMeasuredWidth();
BaseFragment prevFragment = fragmentsStack.get(fragmentsStack.size() - 2); 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.setAlpha((int) (0xff * alpha));
layerShadowDrawable.draw(canvas); layerShadowDrawable.draw(canvas);
} else if (child == containerViewBack) { } 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) { if (opacity < 0) {
opacity = 0; opacity = 0;
} }
@ -936,6 +983,12 @@ public class ActionBarLayout extends FrameLayout {
if (oldFragment != null) { if (oldFragment != null) {
oldFragment.onTransitionAnimationProgress(false, animationProgress); 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); float interpolated = decelerateInterpolator.getInterpolation(animationProgress);
if (open) { if (open) {
containerView.setAlpha(interpolated); containerView.setAlpha(interpolated);
@ -1635,7 +1688,7 @@ public class ActionBarLayout extends FrameLayout {
b = Math.min(255, (int) (bS + (bE - bS) * value)); b = Math.min(255, (int) (bS + (bE - bS) * value));
int color = Color.argb(a, r, g, b); int color = Color.argb(a, r, g, b);
ThemeDescription description = descriptions.get(i); ThemeDescription description = descriptions.get(i);
Theme.setAnimatedColor(description.getCurrentKey(), color); description.setAnimatedColor(color);
description.setColor(color, false, false); description.setColor(color, false, false);
} }
} }
@ -1643,6 +1696,7 @@ public class ActionBarLayout extends FrameLayout {
ThemeDescription.ThemeDescriptionDelegate delegate = themeAnimatorDelegate.get(j); ThemeDescription.ThemeDescriptionDelegate delegate = themeAnimatorDelegate.get(j);
if (delegate != null) { if (delegate != null) {
delegate.didSetColor(); delegate.didSetColor();
delegate.onAnimationProgress(value);
} }
} }
if (presentingFragmentDescriptions != null) { if (presentingFragmentDescriptions != null) {
@ -1652,6 +1706,9 @@ public class ActionBarLayout extends FrameLayout {
description.setColor(Theme.getColor(key), false, false); description.setColor(Theme.getColor(key), false, false);
} }
} }
if (animationProgressListener != null) {
animationProgressListener.setProgress(value);
}
} }
@Keep @Keep
@ -1688,11 +1745,15 @@ public class ActionBarLayout extends FrameLayout {
} }
public void animateThemedValues(Theme.ThemeInfo theme, int accentId, boolean nightTheme, boolean instant) { 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) { if (transitionAnimationInProgress || startedTracking) {
animateThemeAfterAnimation = true; animateThemeAfterAnimation = true;
animateSetThemeAfterAnimation = theme; animateSetThemeAfterAnimation = settings.theme;
animateSetThemeNightAfterAnimation = nightTheme; animateSetThemeNightAfterAnimation = settings.nightTheme;
animateSetThemeAccentIdAfterAnimation = accentId; animateSetThemeAccentIdAfterAnimation = settings.accentId;
return; return;
} }
if (themeAnimatorSet != null) { if (themeAnimatorSet != null) {
@ -1700,7 +1761,8 @@ public class ActionBarLayout extends FrameLayout {
themeAnimatorSet = null; themeAnimatorSet = null;
} }
boolean startAnimation = false; 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; BaseFragment fragment;
if (i == 0) { if (i == 0) {
fragment = getLastFragment(); fragment = getLastFragment();
@ -1712,6 +1774,15 @@ public class ActionBarLayout extends FrameLayout {
} }
if (fragment != null) { if (fragment != null) {
startAnimation = true; 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<ThemeDescription> descriptions = fragment.getThemeDescriptions(); ArrayList<ThemeDescription> descriptions = fragment.getThemeDescriptions();
addStartDescriptions(descriptions); addStartDescriptions(descriptions);
if (fragment.visibleDialog instanceof BottomSheet) { if (fragment.visibleDialog instanceof BottomSheet) {
@ -1722,11 +1793,16 @@ public class ActionBarLayout extends FrameLayout {
addStartDescriptions(dialog.getThemeDescriptions()); addStartDescriptions(dialog.getThemeDescriptions());
} }
if (i == 0) { if (i == 0) {
if (accentId != -1) { if (settings.applyTheme) {
theme.setCurrentAccentId(accentId); if (settings.accentId != -1) {
Theme.saveThemeAccents(theme, true, false, true, false); 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); addEndDescriptions(descriptions);
if (fragment.visibleDialog instanceof BottomSheet) { if (fragment.visibleDialog instanceof BottomSheet) {
@ -1743,16 +1819,26 @@ public class ActionBarLayout extends FrameLayout {
fragment.clearViews(); fragment.clearViews();
fragment.setParentLayout(this); fragment.setParentLayout(this);
} }
if (instant) { if (settings.instant) {
setThemeAnimationValue(1.0f); setThemeAnimationValue(1.0f);
themeAnimatorDescriptions.clear(); themeAnimatorDescriptions.clear();
animateStartColors.clear(); animateStartColors.clear();
animateEndColors.clear(); animateEndColors.clear();
themeAnimatorDelegate.clear(); themeAnimatorDelegate.clear();
presentingFragmentDescriptions = null; presentingFragmentDescriptions = null;
if (settings.afterAnimationRunnable != null) {
settings.afterAnimationRunnable.run();
}
return; return;
} }
Theme.setAnimatingColor(true); Theme.setAnimatingColor(true);
if (settings.beforeAnimationRunnable != null) {
settings.beforeAnimationRunnable.run();
}
animationProgressListener = settings.animationProgress;
if (animationProgressListener != null) {
animationProgressListener.setProgress(0);
}
themeAnimatorSet = new AnimatorSet(); themeAnimatorSet = new AnimatorSet();
themeAnimatorSet.addListener(new AnimatorListenerAdapter() { themeAnimatorSet.addListener(new AnimatorListenerAdapter() {
@Override @Override
@ -1765,6 +1851,9 @@ public class ActionBarLayout extends FrameLayout {
Theme.setAnimatingColor(false); Theme.setAnimatingColor(false);
presentingFragmentDescriptions = null; presentingFragmentDescriptions = null;
themeAnimatorSet = null; themeAnimatorSet = null;
if (settings.afterAnimationRunnable != null) {
settings.afterAnimationRunnable.run();
}
} }
} }
@ -1778,11 +1867,14 @@ public class ActionBarLayout extends FrameLayout {
Theme.setAnimatingColor(false); Theme.setAnimatingColor(false);
presentingFragmentDescriptions = null; presentingFragmentDescriptions = null;
themeAnimatorSet = null; themeAnimatorSet = null;
if (settings.afterAnimationRunnable != null) {
settings.afterAnimationRunnable.run();
}
} }
} }
}); });
themeAnimatorSet.playTogether(ObjectAnimator.ofFloat(this, "themeAnimationValue", 0.0f, 1.0f)); themeAnimatorSet.playTogether(ObjectAnimator.ofFloat(this, "themeAnimationValue", 0.0f, 1.0f));
themeAnimatorSet.setDuration(200); themeAnimatorSet.setDuration(settings.duration);
themeAnimatorSet.start(); themeAnimatorSet.start();
} }
} }
@ -1965,4 +2057,35 @@ public class ActionBarLayout extends FrameLayout {
} }
return null; return null;
} }
private class StartColorsProvider implements Theme.ResourcesProvider {
HashMap<String, Integer> 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));
}
}
}
} }

View file

@ -58,7 +58,11 @@ public class ActionBarMenu extends LinearLayout {
} }
public ActionBarMenuItem addItem(int id, int icon) { 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) { 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) { 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) { 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) { 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); menuItem.setTag(id);
if (text != null) { if (text != null) {
menuItem.textView.setText(text); menuItem.textView.setText(text);

View file

@ -165,13 +165,23 @@ public class ActionBarMenuItem extends FrameLayout {
private int notificationIndex = -1; private int notificationIndex = -1;
private float transitionOffset; private float transitionOffset;
private final Theme.ResourcesProvider resourcesProvider;
public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor) { public ActionBarMenuItem(Context context, ActionBarMenu menu, int backgroundColor, int iconColor) {
this(context, menu, backgroundColor, iconColor, false); 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) { 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); super(context);
this.resourcesProvider = resourcesProvider;
if (backgroundColor != 0) { if (backgroundColor != 0) {
setBackgroundDrawable(Theme.createSelectorDrawable(backgroundColor, text ? 5 : 1)); setBackgroundDrawable(Theme.createSelectorDrawable(backgroundColor, text ? 5 : 1));
} }
@ -325,7 +335,7 @@ public class ActionBarMenuItem extends FrameLayout {
} }
rect = new Rect(); rect = new Rect();
location = new int[2]; location = new int[2];
popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext()); popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext(), resourcesProvider);
popupLayout.setOnTouchListener((v, event) -> { popupLayout.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) { if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (popupWindow != null && popupWindow.isShowing()) { if (popupWindow != null && popupWindow.isShowing()) {
@ -388,7 +398,7 @@ public class ActionBarMenuItem extends FrameLayout {
public TextView addSubItem(int id, CharSequence text) { public TextView addSubItem(int id, CharSequence text) {
createPopupLayout(); createPopupLayout();
TextView textView = new TextView(getContext()); TextView textView = new TextView(getContext());
textView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem)); textView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubmenuItem));
textView.setBackgroundDrawable(Theme.getSelectorDrawable(false)); textView.setBackgroundDrawable(Theme.getSelectorDrawable(false));
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
textView.setGravity(Gravity.CENTER_VERTICAL); textView.setGravity(Gravity.CENTER_VERTICAL);
@ -435,6 +445,10 @@ public class ActionBarMenuItem extends FrameLayout {
return addSubItem(id, icon, null, text, true, false); 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) { public ActionBarMenuSubItem addSubItem(int id, int icon, CharSequence text, boolean needCheck) {
return addSubItem(id, icon, null, text, true, 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) { 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(); createPopupLayout();
ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), needCheck, false, false); ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getContext(), needCheck, false, false, resourcesProvider);
cell.setTextAndIcon(text, icon, iconDrawable); cell.setTextAndIcon(text, icon, iconDrawable);
cell.setMinimumWidth(AndroidUtilities.dp(196)); cell.setMinimumWidth(AndroidUtilities.dp(196));
cell.setTag(id); cell.setTag(id);
@ -857,7 +875,7 @@ public class ActionBarMenuItem extends FrameLayout {
} }
for (int i = 0; i < localFilters.size(); i++) { 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.setData(localFilters.get(i));
searchFilterView.setOnClickListener(view -> { searchFilterView.setOnClickListener(view -> {
int index = currentSearchFilters.indexOf(searchFilterView.getFilter()); int index = currentSearchFilters.indexOf(searchFilterView.getFilter());
@ -1140,7 +1158,7 @@ public class ActionBarMenuItem extends FrameLayout {
searchFieldCaption = new TextView(getContext()); searchFieldCaption = new TextView(getContext());
searchFieldCaption.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); searchFieldCaption.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
searchFieldCaption.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); searchFieldCaption.setTextColor(getThemedColor(Theme.key_actionBarDefaultSearch));
searchFieldCaption.setSingleLine(true); searchFieldCaption.setSingleLine(true);
searchFieldCaption.setEllipsize(TextUtils.TruncateAt.END); searchFieldCaption.setEllipsize(TextUtils.TruncateAt.END);
searchFieldCaption.setVisibility(GONE); searchFieldCaption.setVisibility(GONE);
@ -1191,10 +1209,10 @@ public class ActionBarMenuItem extends FrameLayout {
}; };
searchField.setScrollContainer(false); searchField.setScrollContainer(false);
searchField.setCursorWidth(1.5f); 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.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
searchField.setHintTextColor(Theme.getColor(Theme.key_actionBarDefaultSearchPlaceholder)); searchField.setHintTextColor(getThemedColor(Theme.key_actionBarDefaultSearchPlaceholder));
searchField.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); searchField.setTextColor(getThemedColor(Theme.key_actionBarDefaultSearch));
searchField.setSingleLine(true); searchField.setSingleLine(true);
searchField.setBackgroundResource(0); searchField.setBackgroundResource(0);
searchField.setPadding(0, 0, 0, 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() { public void collapseSearchFilters() {
@ -1618,6 +1643,11 @@ public class ActionBarMenuItem extends FrameLayout {
setTranslationX(0); 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 { private static class SearchFilterView extends FrameLayout {
Drawable thumbDrawable; 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); super(context);
this.resourcesProvider = resourcesProvider;
avatarImageView = new BackupImageView(context); avatarImageView = new BackupImageView(context);
addView(avatarImageView, LayoutHelper.createFrame(32, 32)); addView(avatarImageView, LayoutHelper.createFrame(32, 32));
@ -1658,10 +1691,10 @@ public class ActionBarMenuItem extends FrameLayout {
} }
private void updateColors() { private void updateColors() {
int defaultBackgroundColor = Theme.getColor(Theme.key_groupcreate_spanBackground); int defaultBackgroundColor = getThemedColor(Theme.key_groupcreate_spanBackground);
int selectedBackgroundColor = Theme.getColor(Theme.key_avatar_backgroundBlue); int selectedBackgroundColor = getThemedColor(Theme.key_avatar_backgroundBlue);
int textDefaultColor = Theme.getColor(Theme.key_windowBackgroundWhiteBlackText); int textDefaultColor = getThemedColor(Theme.key_windowBackgroundWhiteBlackText);
int textSelectedColor = Theme.getColor(Theme.key_avatar_actionBarIconBlue); int textSelectedColor = getThemedColor(Theme.key_avatar_actionBarIconBlue);
shapeDrawable.getPaint().setColor(ColorUtils.blendARGB(defaultBackgroundColor, selectedBackgroundColor, selectedProgress)); shapeDrawable.getPaint().setColor(ColorUtils.blendARGB(defaultBackgroundColor, selectedBackgroundColor, selectedProgress));
titleView.setTextColor(ColorUtils.blendARGB(textDefaultColor, textSelectedColor, selectedProgress)); titleView.setTextColor(ColorUtils.blendARGB(textDefaultColor, textSelectedColor, selectedProgress));
closeIconView.setColorFilter(textSelectedColor); closeIconView.setColorFilter(textSelectedColor);
@ -1671,8 +1704,8 @@ public class ActionBarMenuItem extends FrameLayout {
closeIconView.setScaleY(0.82f * selectedProgress); closeIconView.setScaleY(0.82f * selectedProgress);
if (thumbDrawable != null) { if (thumbDrawable != null) {
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
} }
avatarImageView.setAlpha(1f - selectedProgress); avatarImageView.setAlpha(1f - selectedProgress);
@ -1686,16 +1719,16 @@ public class ActionBarMenuItem extends FrameLayout {
this.data = data; this.data = data;
titleView.setText(data.title); titleView.setText(data.title);
thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled); thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
if (data.filterType == FiltersView.FILTER_TYPE_CHAT) { if (data.filterType == FiltersView.FILTER_TYPE_CHAT) {
if (data.chat instanceof TLRPC.User) { if (data.chat instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) data.chat; TLRPC.User user = (TLRPC.User) data.chat;
if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) { if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) {
CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved); CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved);
combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16));
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundSaved), false); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundSaved), false);
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
avatarImageView.setImageDrawable(combinedDrawable); avatarImageView.setImageDrawable(combinedDrawable);
} else { } else {
avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16)); avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16));
@ -1709,8 +1742,8 @@ public class ActionBarMenuItem extends FrameLayout {
} else if (data.filterType == FiltersView.FILTER_TYPE_ARCHIVE) { } else if (data.filterType == FiltersView.FILTER_TYPE_ARCHIVE) {
CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive); CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive);
combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16));
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false);
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
avatarImageView.setImageDrawable(combinedDrawable); avatarImageView.setImageDrawable(combinedDrawable);
} else { } else {
avatarImageView.setImageDrawable(thumbDrawable); avatarImageView.setImageDrawable(thumbDrawable);
@ -1757,5 +1790,10 @@ public class ActionBarMenuItem extends FrameLayout {
public FiltersView.MediaFilterData getFilter() { public FiltersView.MediaFilterData getFilter() {
return data; return data;
} }
private int getThemedColor(String key) {
Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
}
} }
} }

View file

@ -15,6 +15,8 @@ import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.ui.Components.CheckBox;
import org.telegram.ui.Components.CheckBox2;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
public class ActionBarMenuSubItem extends FrameLayout { public class ActionBarMenuSubItem extends FrameLayout {
@ -22,28 +24,42 @@ public class ActionBarMenuSubItem extends FrameLayout {
private TextView textView; private TextView textView;
private TextView subtextView; private TextView subtextView;
private ImageView imageView; private ImageView imageView;
private ImageView checkView; private CheckBox2 checkView;
private ImageView rightIcon; private ImageView rightIcon;
private int textColor = Theme.getColor(Theme.key_actionBarDefaultSubmenuItem); private int textColor;
private int iconColor = Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon); private int iconColor;
private int selectorColor = Theme.getColor(Theme.key_dialogButtonSelector); private int selectorColor;
boolean top; boolean top;
boolean bottom; boolean bottom;
private int itemHeight = 48; private int itemHeight = 48;
private final Theme.ResourcesProvider resourcesProvider;
public ActionBarMenuSubItem(Context context, boolean top, boolean bottom) { public ActionBarMenuSubItem(Context context, boolean top, boolean bottom) {
this(context, false, top, bottom); this(context, false, top, bottom);
} }
public ActionBarMenuSubItem(Context context, boolean needCheck, boolean top, boolean 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); super(context);
this.resourcesProvider = resourcesProvider;
this.top = top; this.top = top;
this.bottom = bottom; this.bottom = bottom;
textColor = getThemedColor(Theme.key_actionBarDefaultSubmenuItem);
iconColor = getThemedColor(Theme.key_actionBarDefaultSubmenuItemIcon);
selectorColor = getThemedColor(Theme.key_dialogButtonSelector);
updateBackground(); updateBackground();
setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0); 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)); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL));
if (needCheck) { if (needCheck) {
checkView = new ImageView(context); checkView = new CheckBox2(context, 26, resourcesProvider);
checkView.setImageResource(R.drawable.msg_text_check); checkView.setDrawUnchecked(false);
checkView.setScaleType(ImageView.ScaleType.CENTER); checkView.setColor(null, null, Theme.key_radioBackgroundChecked);
checkView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_radioBackgroundChecked), PorterDuff.Mode.MULTIPLY)); checkView.setDrawBackgroundAsArc(-1);
addView(checkView, LayoutHelper.createFrame(26, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT))); 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) { public void setItemHeight(int itemHeight) {
this.itemHeight = itemHeight; this.itemHeight = itemHeight;
} }
public void setChecked(boolean checked) { public void setChecked(boolean checked) {
if (checkView == null) { if (checkView == null) {
return; return;
} }
checkView.setVisibility(checked ? VISIBLE : INVISIBLE); checkView.setChecked(checked, true);
} }
public void setCheckColor(int color) { public void setCheckColor(String colorKey) {
checkView.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); checkView.setColor(null, null, colorKey);
} }
public void setRightIcon(int icon) { public void setRightIcon(int icon) {
@ -207,9 +224,14 @@ public class ActionBarMenuSubItem extends FrameLayout {
updateBackground(); updateBackground();
} }
private void updateBackground() { void updateBackground() {
int topBackgroundRadius = top ? 6 : 0; int topBackgroundRadius = top ? 6 : 0;
int bottomBackgroundRadius = bottom ? 6 : 0; int bottomBackgroundRadius = bottom ? 6 : 0;
setBackground(Theme.createRadSelectorDrawable(selectorColor, topBackgroundRadius, bottomBackgroundRadius)); 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);
}
} }

View file

@ -12,6 +12,7 @@ import android.animation.Animator;
import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet; import android.animation.AnimatorSet;
import android.animation.ObjectAnimator; import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color; import android.graphics.Color;
@ -57,6 +58,7 @@ public class ActionBarPopupWindow extends PopupWindow {
private boolean isClosingAnimated; private boolean isClosingAnimated;
private int currentAccount = UserConfig.selectedAccount; private int currentAccount = UserConfig.selectedAccount;
private boolean pauseNotifications; private boolean pauseNotifications;
private long outEmptyTime = -1;
static { static {
Field f = null; Field f = null;
@ -103,19 +105,25 @@ public class ActionBarPopupWindow extends PopupWindow {
protected Drawable backgroundDrawable; protected Drawable backgroundDrawable;
private boolean fitItems; private boolean fitItems;
private final Theme.ResourcesProvider resourcesProvider;
public ActionBarPopupWindowLayout(Context context) { 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); super(context);
this.resourcesProvider = resourcesProvider;
backgroundDrawable = getResources().getDrawable(resId).mutate(); backgroundDrawable = getResources().getDrawable(resId).mutate();
if (backgroundDrawable != null) { if (backgroundDrawable != null) {
backgroundDrawable.getPadding(bgPaddings); 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)); setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
setWillNotDraw(false); 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() { public ActionBarPopupWindow() {
@ -616,20 +629,34 @@ public class ActionBarPopupWindow extends PopupWindow {
isClosingAnimated = false; isClosingAnimated = false;
if (animationEnabled && animated) { if (animationEnabled && animated) {
isClosingAnimated = true; isClosingAnimated = true;
ActionBarPopupWindowLayout content = (ActionBarPopupWindowLayout) getContentView(); ViewGroup viewGroup = (ViewGroup) getContentView();
if (content.itemAnimators != null && !content.itemAnimators.isEmpty()) { ActionBarPopupWindowLayout content = null;
for (int a = 0, N = content.itemAnimators.size(); a < N; a++) { for (int i = 0; i < viewGroup.getChildCount(); i++) {
AnimatorSet animatorSet = content.itemAnimators.get(a); if (viewGroup.getChildAt(i) instanceof ActionBarPopupWindowLayout) {
animatorSet.removeAllListeners(); content = (ActionBarPopupWindowLayout) viewGroup.getChildAt(i);
animatorSet.cancel(); }
}
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 = new AnimatorSet();
windowAnimatorSet.playTogether( if (outEmptyTime > 0) {
ObjectAnimator.ofFloat(content, View.TRANSLATION_Y, AndroidUtilities.dp(content.shownFromBotton ? 5 : -5)), windowAnimatorSet.playTogether(ValueAnimator.ofFloat(0, 1f));
ObjectAnimator.ofFloat(content, View.ALPHA, 0.0f)); windowAnimatorSet.setDuration(outEmptyTime);
windowAnimatorSet.setDuration(dismissAnimationDuration); } 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() { windowAnimatorSet.addListener(new AnimatorListenerAdapter() {
@Override @Override
public void onAnimationEnd(Animator animation) { public void onAnimationEnd(Animator animation) {
@ -660,4 +687,8 @@ public class ActionBarPopupWindow extends PopupWindow {
unregisterListener(); unregisterListener();
} }
} }
public void setEmptyOutAnimation(long time) {
outEmptyTime = time;
}
} }

View file

@ -137,21 +137,24 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
private ArrayList<AlertDialogCell> itemViews = new ArrayList<>(); private ArrayList<AlertDialogCell> itemViews = new ArrayList<>();
private float aspectRatio; private float aspectRatio;
private boolean dimEnabled = true; private boolean dimEnabled = true;
private final Theme.ResourcesProvider resourcesProvider;
public static class AlertDialogCell extends FrameLayout { public static class AlertDialogCell extends FrameLayout {
private final Theme.ResourcesProvider resourcesProvider;
private TextView textView; private TextView textView;
private ImageView imageView; private ImageView imageView;
public AlertDialogCell(Context context) { public AlertDialogCell(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context); 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); setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0);
imageView = new ImageView(context); imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER); 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))); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 40, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)));
textView = new TextView(context); textView = new TextView(context);
@ -159,7 +162,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
textView.setSingleLine(true); textView.setSingleLine(true);
textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setEllipsize(TextUtils.TruncateAt.END); 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); 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)); 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); 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) { public AlertDialog(Context context, int progressStyle) {
this(context, progressStyle, null);
}
public AlertDialog(Context context, int progressStyle, Theme.ResourcesProvider resourcesProvider) {
super(context, R.style.TransparentDialog); super(context, R.style.TransparentDialog);
this.resourcesProvider = resourcesProvider;
backgroundPaddings = new Rect(); backgroundPaddings = new Rect();
if (progressStyle != 3) { if (progressStyle != 3) {
shadowDrawable = context.getResources().getDrawable(R.drawable.popup_fixed_alert).mutate(); 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); shadowDrawable.getPadding(backgroundPaddings);
} }
@ -468,7 +481,7 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
titleTextView = new TextView(getContext()); titleTextView = new TextView(getContext());
titleTextView.setText(title); titleTextView.setText(title);
titleTextView.setTextColor(getThemeColor(Theme.key_dialogTextBlack)); titleTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); 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) { if (secondTitle != null && title != null) {
secondTitleTextView = new TextView(getContext()); secondTitleTextView = new TextView(getContext());
secondTitleTextView.setText(secondTitle); secondTitleTextView.setText(secondTitle);
secondTitleTextView.setTextColor(getThemeColor(Theme.key_dialogTextGray3)); secondTitleTextView.setTextColor(getThemedColor(Theme.key_dialogTextGray3));
secondTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); secondTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
secondTitleTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP); 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)); 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) { if (subtitle != null) {
subtitleTextView = new TextView(getContext()); subtitleTextView = new TextView(getContext());
subtitleTextView.setText(subtitle); subtitleTextView.setText(subtitle);
subtitleTextView.setTextColor(getThemeColor(Theme.key_dialogIcon)); subtitleTextView.setTextColor(getThemedColor(Theme.key_dialogIcon));
subtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); subtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
subtitleTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); 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)); 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); 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)); containerView.addView(contentScrollView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 0, 0, 0));
scrollContainer = new LinearLayout(getContext()); scrollContainer = new LinearLayout(getContext());
@ -526,10 +539,10 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
} }
messageTextView = new TextView(getContext()); messageTextView = new TextView(getContext());
messageTextView.setTextColor(getThemeColor(Theme.key_dialogTextBlack)); messageTextView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
messageTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy()); messageTextView.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
messageTextView.setLinkTextColor(getThemeColor(Theme.key_dialogTextLink)); messageTextView.setLinkTextColor(getThemedColor(Theme.key_dialogTextLink));
if (!messageTextViewClickable) { if (!messageTextViewClickable) {
messageTextView.setClickable(false); messageTextView.setClickable(false);
messageTextView.setEnabled(false); messageTextView.setEnabled(false);
@ -539,8 +552,8 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
progressViewContainer = new FrameLayout(getContext()); progressViewContainer = new FrameLayout(getContext());
containerView.addView(progressViewContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 44, Gravity.LEFT | Gravity.TOP, 23, title == null ? 24 : 0, 23, 24)); 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()); RadialProgressView progressView = new RadialProgressView(getContext(), resourcesProvider);
progressView.setProgressColor(getThemeColor(Theme.key_dialogProgressCircle)); progressView.setProgressColor(getThemedColor(Theme.key_dialogProgressCircle));
progressViewContainer.addView(progressView, LayoutHelper.createFrame(44, 44, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP)); progressViewContainer.addView(progressView, LayoutHelper.createFrame(44, 44, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP));
messageTextView.setLines(1); messageTextView.setLines(1);
@ -551,14 +564,14 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
lineProgressView = new LineProgressView(getContext()); lineProgressView = new LineProgressView(getContext());
lineProgressView.setProgress(currentProgress / 100.0f, false); lineProgressView.setProgress(currentProgress / 100.0f, false);
lineProgressView.setProgressColor(getThemeColor(Theme.key_dialogLineProgress)); lineProgressView.setProgressColor(getThemedColor(Theme.key_dialogLineProgress));
lineProgressView.setBackColor(getThemeColor(Theme.key_dialogLineProgressBackground)); lineProgressView.setBackColor(getThemedColor(Theme.key_dialogLineProgressBackground));
containerView.addView(lineProgressView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 4, Gravity.LEFT | Gravity.CENTER_VERTICAL, 24, 0, 24, 0)); containerView.addView(lineProgressView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 4, Gravity.LEFT | Gravity.CENTER_VERTICAL, 24, 0, 24, 0));
lineProgressViewPercent = new TextView(getContext()); lineProgressViewPercent = new TextView(getContext());
lineProgressViewPercent.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); lineProgressViewPercent.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
lineProgressViewPercent.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); 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); 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)); containerView.addView(lineProgressViewPercent, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 23, 4, 23, 24));
updateLineProgressTextView(); updateLineProgressTextView();
@ -567,11 +580,11 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
setCancelable(false); setCancelable(false);
progressViewContainer = new FrameLayout(getContext()); 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)); containerView.addView(progressViewContainer, LayoutHelper.createLinear(86, 86, Gravity.CENTER));
RadialProgressView progressView = new RadialProgressView(getContext()); RadialProgressView progressView = new RadialProgressView(getContext(), resourcesProvider);
progressView.setProgressColor(getThemeColor(Theme.key_dialog_inlineProgress)); progressView.setProgressColor(getThemedColor(Theme.key_dialog_inlineProgress));
progressViewContainer.addView(progressView, LayoutHelper.createLinear(86, 86)); progressViewContainer.addView(progressView, LayoutHelper.createLinear(86, 86));
} else { } 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)); 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) { if (items[a] == null) {
continue; continue;
} }
AlertDialogCell cell = new AlertDialogCell(getContext()); AlertDialogCell cell = new AlertDialogCell(getContext(), resourcesProvider);
cell.setTextAndIcon(items[a], itemIcons != null ? itemIcons[a] : 0); cell.setTextAndIcon(items[a], itemIcons != null ? itemIcons[a] : 0);
cell.setTag(a); cell.setTag(a);
itemViews.add(cell); itemViews.add(cell);
@ -734,13 +747,13 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
textView.setMinWidth(AndroidUtilities.dp(64)); textView.setMinWidth(AndroidUtilities.dp(64));
textView.setTag(Dialog.BUTTON_POSITIVE); textView.setTag(Dialog.BUTTON_POSITIVE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(getThemeColor(dialogButtonColorKey)); textView.setTextColor(getThemedColor(dialogButtonColorKey));
textView.setGravity(Gravity.CENTER); textView.setGravity(Gravity.CENTER);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
// textView.setLines(1); // textView.setLines(1);
// textView.setSingleLine(true); //TODO // textView.setSingleLine(true); //TODO
textView.setText(positiveButtonText.toString().toUpperCase()); 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); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
if (verticalButtons) { if (verticalButtons) {
buttonsLayout.addView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); 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.setMinWidth(AndroidUtilities.dp(64));
textView.setTag(Dialog.BUTTON_NEGATIVE); textView.setTag(Dialog.BUTTON_NEGATIVE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(getThemeColor(dialogButtonColorKey)); textView.setTextColor(getThemedColor(dialogButtonColorKey));
textView.setGravity(Gravity.CENTER); textView.setGravity(Gravity.CENTER);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setEllipsize(TextUtils.TruncateAt.END); textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setSingleLine(true); textView.setSingleLine(true);
textView.setText(negativeButtonText.toString().toUpperCase()); 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); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
if (verticalButtons) { if (verticalButtons) {
buttonsLayout.addView(textView, 0, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); 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.setMinWidth(AndroidUtilities.dp(64));
textView.setTag(Dialog.BUTTON_NEUTRAL); textView.setTag(Dialog.BUTTON_NEUTRAL);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(getThemeColor(dialogButtonColorKey)); textView.setTextColor(getThemedColor(dialogButtonColorKey));
textView.setGravity(Gravity.CENTER); textView.setGravity(Gravity.CENTER);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setEllipsize(TextUtils.TruncateAt.END); textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setSingleLine(true); textView.setSingleLine(true);
textView.setText(neutralButtonText.toString().toUpperCase()); 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); textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
if (verticalButtons) { if (verticalButtons) {
buttonsLayout.addView(textView, 1, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36, LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT)); 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; positiveButtonListener = listener;
} }
protected int getThemeColor(String key) { protected int getThemedColor(String key) {
return Theme.getColor(key); Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
} }
public void showDelayed(long delay) { public void showDelayed(long delay) {
@ -1190,11 +1204,15 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
} }
public Builder(Context context) { public Builder(Context context) {
alertDialog = new AlertDialog(context, 0); this(context, null);
} }
public Builder(Context context, int progressViewStyle) { public Builder(Context context, Theme.ResourcesProvider resourcesProvider) {
alertDialog = new AlertDialog(context, progressViewStyle); this(context, 0, resourcesProvider);
}
public Builder(Context context, int progressViewStyle, Theme.ResourcesProvider resourcesProvider) {
alertDialog = new AlertDialog(context, progressViewStyle, resourcesProvider);
} }
public Context getContext() { public Context getContext() {
@ -1332,8 +1350,9 @@ public class AlertDialog extends Dialog implements Drawable.Callback {
alertDialog.aspectRatio = aspectRatio; alertDialog.aspectRatio = aspectRatio;
} }
public void setDimEnabled(boolean dimEnabled) { public Builder setDimEnabled(boolean dimEnabled) {
alertDialog.dimEnabled = dimEnabled; alertDialog.dimEnabled = dimEnabled;
return this;
} }
public void notDrawBackgroundOnTopView(boolean b) { public void notDrawBackgroundOnTopView(boolean b) {

View file

@ -17,17 +17,19 @@ import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock; import android.graphics.drawable.Drawable;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.Menu; import android.view.Menu;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.ViewParent; import android.view.ViewParent;
import android.view.Window;
import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityManager;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import org.telegram.messenger.AccountInstance; import org.telegram.messenger.AccountInstance;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DownloadController; import org.telegram.messenger.DownloadController;
@ -65,6 +67,8 @@ public abstract class BaseFragment {
protected boolean hasOwnBackground = false; protected boolean hasOwnBackground = false;
protected boolean isPaused = true; protected boolean isPaused = true;
protected Dialog parentDialog; protected Dialog parentDialog;
protected boolean inTransitionAnimation = false;
protected boolean fragmentBeginToShow;
public BaseFragment() { public BaseFragment() {
classGuid = ConnectionsManager.generateClassGuid(); classGuid = ConnectionsManager.generateClassGuid();
@ -215,11 +219,11 @@ public abstract class BaseFragment {
protected ActionBar createActionBar(Context context) { protected ActionBar createActionBar(Context context) {
ActionBar actionBar = new ActionBar(context); ActionBar actionBar = new ActionBar(context);
actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault)); actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarDefault));
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSelector), false); actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSelector), false);
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), true); actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), true);
actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultIcon), false); actionBar.setItemsColor(getThemedColor(Theme.key_actionBarDefaultIcon), false);
actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), true); actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), true);
if (inPreviewMode || inBubbleMode) { if (inPreviewMode || inBubbleMode) {
actionBar.setOccupyStatusBar(false); actionBar.setOccupyStatusBar(false);
} }
@ -435,11 +439,14 @@ public abstract class BaseFragment {
} }
protected void onTransitionAnimationStart(boolean isOpen, boolean backward) { protected void onTransitionAnimationStart(boolean isOpen, boolean backward) {
inTransitionAnimation = true;
if (isOpen) {
fragmentBeginToShow = true;
}
} }
protected void onTransitionAnimationEnd(boolean isOpen, boolean backward) { protected void onTransitionAnimationEnd(boolean isOpen, boolean backward) {
inTransitionAnimation = false;
} }
protected void onBecomeFullyVisible() { protected void onBecomeFullyVisible() {
@ -671,7 +678,40 @@ public abstract class BaseFragment {
return actionBarLayout; 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) { private void setParentDialog(Dialog dialog) {
parentDialog = dialog; parentDialog = dialog;
} }
public Theme.ResourcesProvider getResourceProvider() {
return null;
}
} }

View file

@ -157,6 +157,7 @@ public class BottomSheet extends Dialog {
protected int navBarColor; protected int navBarColor;
private OnDismissListener onHideListener; private OnDismissListener onHideListener;
protected Theme.ResourcesProvider resourcesProvider;
public void setDisableScroll(boolean b) { public void setDisableScroll(boolean b) {
disableScroll = b; disableScroll = b;
@ -573,7 +574,7 @@ public class BottomSheet extends Dialog {
super.dispatchDraw(canvas); super.dispatchDraw(canvas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (navBarColorKey != null) { if (navBarColorKey != null) {
backgroundPaint.setColor(Theme.getColor(navBarColorKey)); backgroundPaint.setColor(getThemedColor(navBarColorKey));
} else { } else {
backgroundPaint.setColor(navBarColor); backgroundPaint.setColor(navBarColor);
} }
@ -603,7 +604,7 @@ public class BottomSheet extends Dialog {
} }
if (containerView.getTranslationY() < 0) { 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); 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) { protected void onDraw(Canvas canvas) {
super.onDraw(canvas); super.onDraw(canvas);
if (lastInsets != null && keyboardHeight != 0) { 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); canvas.drawRect(containerView.getLeft() + backgroundPaddingLeft, getMeasuredHeight() - keyboardHeight - (drawNavigationBar ? bottomInset : 0), containerView.getRight() - backgroundPaddingLeft, getMeasuredHeight() - (drawNavigationBar ? bottomInset : 0), backgroundPaint);
} }
onContainerDraw(canvas); onContainerDraw(canvas);
@ -658,12 +659,18 @@ public class BottomSheet extends Dialog {
public static class BottomSheetCell extends FrameLayout { public static class BottomSheetCell extends FrameLayout {
private final Theme.ResourcesProvider resourcesProvider;
private TextView textView; private TextView textView;
private ImageView imageView; private ImageView imageView;
int currentType; int currentType;
public BottomSheetCell(Context context, int type) { public BottomSheetCell(Context context, int type) {
this(context, type, null);
}
public BottomSheetCell(Context context, int type, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider;
currentType = type; currentType = type;
setBackgroundDrawable(Theme.getSelectorDrawable(false)); setBackgroundDrawable(Theme.getSelectorDrawable(false));
@ -671,7 +678,7 @@ public class BottomSheet extends Dialog {
imageView = new ImageView(context); imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER); 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))); addView(imageView, LayoutHelper.createFrame(56, 48, Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT)));
textView = new TextView(context); textView = new TextView(context);
@ -680,21 +687,21 @@ public class BottomSheet extends Dialog {
textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setEllipsize(TextUtils.TruncateAt.END); textView.setEllipsize(TextUtils.TruncateAt.END);
if (type == 0) { if (type == 0) {
textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); 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)); addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL));
} else if (type == 1) { } else if (type == 1) {
textView.setGravity(Gravity.CENTER); 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.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
} else if (type == 2) { } else if (type == 2) {
textView.setGravity(Gravity.CENTER); 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.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); 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)); 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() { public ImageView getImageView() {
return imageView; 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) { public void setAllowNestedScroll(boolean value) {
@ -767,7 +779,12 @@ public class BottomSheet extends Dialog {
} }
public BottomSheet(Context context, boolean needFocus) { public BottomSheet(Context context, boolean needFocus) {
this(context, needFocus, null);
}
public BottomSheet(Context context, boolean needFocus, Theme.ResourcesProvider resourcesProvider) {
super(context, R.style.TransparentDialog); super(context, R.style.TransparentDialog);
this.resourcesProvider = resourcesProvider;
if (Build.VERSION.SDK_INT >= 30) { if (Build.VERSION.SDK_INT >= 30) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); 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(); Rect padding = new Rect();
shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate(); 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); shadowDrawable.getPadding(padding);
backgroundPaddingLeft = padding.left; backgroundPaddingLeft = padding.left;
backgroundPaddingTop = padding.top; backgroundPaddingTop = padding.top;
@ -871,12 +888,12 @@ public class BottomSheet extends Dialog {
titleView.setSingleLine(true); titleView.setSingleLine(true);
titleView.setText(title); titleView.setText(title);
if (bigTitle) { if (bigTitle) {
titleView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); titleView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8)); titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8));
} else { } else {
titleView.setTextColor(Theme.getColor(Theme.key_dialogTextGray2)); titleView.setTextColor(getThemedColor(Theme.key_dialogTextGray2));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8)); 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) { if (items[a] == null) {
continue; 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); 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)); containerView.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP, 0, topOffset, 0, 0));
topOffset += 48; topOffset += 48;
@ -1358,11 +1375,15 @@ public class BottomSheet extends Dialog {
private BottomSheet bottomSheet; private BottomSheet bottomSheet;
public Builder(Context context) { public Builder(Context context) {
bottomSheet = new BottomSheet(context, false); this(context, false);
} }
public Builder(Context context, boolean needFocus) { 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) { public Builder setItems(CharSequence[] items, final OnClickListener onClickListener) {
@ -1510,4 +1531,9 @@ public class BottomSheet extends Dialog {
public int getCurrentAccount() { public int getCurrentAccount() {
return currentAccount; return currentAccount;
} }
protected int getThemedColor(String key) {
Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
}
} }

View file

@ -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<String, Integer> lightCurrentColors;
private HashMap<String, Integer> 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<String, Integer> getCurrentColors(int currentAccount, boolean isDark) {
HashMap<String, Integer> 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<String, Integer> 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<String, String> fallbackKeys = Theme.getFallbackKeys();
for (Map.Entry<String, String> fallbackEntry : fallbackKeys.entrySet()) {
String colorKey = fallbackEntry.getKey();
if (!currentColors.containsKey(colorKey)) {
Integer color = currentColors.get(fallbackEntry.getValue());
currentColors.put(colorKey, color);
}
}
HashMap<String, Integer> defaultColors = Theme.getDefaultColors();
for (Map.Entry<String, Integer> 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<Pair<Long, Bitmap>> 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<Pair<Long, Bitmap>> 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<Integer> 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<String, Integer> getCurrentColors(Theme.ThemeInfo themeInfo) {
HashMap<String, Integer> 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<String, Integer> currentColors = new HashMap<>(currentColorsNoAccent);
Theme.ThemeAccent themeAccent = themeInfo.getAccent(false);
if (themeAccent != null) {
themeAccent.fillAccentColors(currentColorsNoAccent, currentColors);
}
return currentColors;
}
}

View file

@ -3,12 +3,13 @@ package org.telegram.ui.ActionBar;
import android.content.Context; import android.content.Context;
public class DarkAlertDialog extends AlertDialog { public class DarkAlertDialog extends AlertDialog {
public DarkAlertDialog(Context context, int progressStyle) { public DarkAlertDialog(Context context, int progressStyle) {
super(context, progressStyle); super(context, progressStyle);
} }
@Override @Override
protected int getThemeColor(String key) { protected int getThemedColor(String key) {
switch (key) { switch (key) {
case Theme.key_dialogBackground: case Theme.key_dialogBackground:
return 0xFF262626; return 0xFF262626;
@ -17,7 +18,7 @@ public class DarkAlertDialog extends AlertDialog {
case Theme.key_dialogScrollGlow: case Theme.key_dialogScrollGlow:
return 0xFFFFFFFF; return 0xFFFFFFFF;
} }
return super.getThemeColor(key); return super.getThemedColor(key);
} }
public static class Builder extends AlertDialog.Builder { public static class Builder extends AlertDialog.Builder {

View file

@ -107,9 +107,12 @@ public final class FloatingToolbar {
private final Comparator<MenuItem> mMenuItemComparator = (menuItem1, menuItem2) -> menuItem1.getOrder() - menuItem2.getOrder(); private final Comparator<MenuItem> mMenuItemComparator = (menuItem1, menuItem2) -> menuItem1.getOrder() - menuItem2.getOrder();
public FloatingToolbar(Context context, View windowView, int style) { private final Theme.ResourcesProvider resourcesProvider;
public FloatingToolbar(Context context, View windowView, int style, Theme.ResourcesProvider resourcesProvider) {
mWindowView = windowView; mWindowView = windowView;
currentStyle = style; currentStyle = style;
this.resourcesProvider = resourcesProvider;
mPopup = new FloatingToolbarPopup(context, windowView); mPopup = new FloatingToolbarPopup(context, windowView);
} }
@ -971,7 +974,7 @@ public final class FloatingToolbar {
return new LinearLayout(mContext) { return new LinearLayout(mContext) {
@Override @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isOverflowAnimating()) { if (isOverflowAnimating() && mMainPanelSize != null) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(mMainPanelSize.getWidth(), MeasureSpec.EXACTLY); widthMeasureSpec = MeasureSpec.makeMeasureSpec(mMainPanelSize.getWidth(), MeasureSpec.EXACTLY);
} }
super.onMeasure(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec);
@ -992,14 +995,14 @@ public final class FloatingToolbar {
overflowButton.setImageDrawable(mOverflow); overflowButton.setImageDrawable(mOverflow);
int color; int color;
if (currentStyle == STYLE_DIALOG) { if (currentStyle == STYLE_DIALOG) {
color = Theme.getColor(Theme.key_dialogTextBlack); color = getThemedColor(Theme.key_dialogTextBlack);
overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1)); overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1));
} else if (currentStyle == STYLE_BLACK) { } else if (currentStyle == STYLE_BLACK) {
color = 0xfffafafa; color = 0xfffafafa;
overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x40ffffff, 1)); overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x40ffffff, 1));
} else { } else {
color = Theme.getColor(Theme.key_windowBackgroundWhiteBlackText); color = getThemedColor(Theme.key_windowBackgroundWhiteBlackText);
overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 1)); overflowButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_listSelector), 1));
} }
mOverflow.setTint(color); mOverflow.setTint(color);
mArrow.setTint(color); mArrow.setTint(color);
@ -1204,13 +1207,13 @@ public final class FloatingToolbar {
textView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); textView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
textView.setFocusableInTouchMode(false); textView.setFocusableInTouchMode(false);
if (currentStyle == STYLE_DIALOG) { if (currentStyle == STYLE_DIALOG) {
textView.setTextColor(Theme.getColor(Theme.key_dialogTextBlack)); textView.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false)); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false));
} else if (currentStyle == STYLE_BLACK) { } else if (currentStyle == STYLE_BLACK) {
textView.setTextColor(0xfffafafa); textView.setTextColor(0xfffafafa);
menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(0x40ffffff, false)); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(0x40ffffff, false));
} else if (currentStyle == STYLE_THEME) { } else if (currentStyle == STYLE_THEME) {
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false)); menuItemButton.setBackgroundDrawable(Theme.getSelectorDrawable(false));
} }
textView.setPaddingRelative(AndroidUtilities.dp(11), 0, 0, 0); textView.setPaddingRelative(AndroidUtilities.dp(11), 0, 0, 0);
@ -1253,11 +1256,11 @@ public final class FloatingToolbar {
int r = AndroidUtilities.dp(6); int r = AndroidUtilities.dp(6);
shape.setCornerRadii(new float[] { r, r, r, r, r, r, r, r }); shape.setCornerRadii(new float[] { r, r, r, r, r, r, r, r });
if (currentStyle == STYLE_DIALOG) { if (currentStyle == STYLE_DIALOG) {
shape.setColor(Theme.getColor(Theme.key_dialogBackground)); shape.setColor(getThemedColor(Theme.key_dialogBackground));
} else if (currentStyle == STYLE_BLACK) { } else if (currentStyle == STYLE_BLACK) {
shape.setColor(0xf9222222); shape.setColor(0xf9222222);
} else if (currentStyle == STYLE_THEME) { } else if (currentStyle == STYLE_THEME) {
shape.setColor(Theme.getColor(Theme.key_windowBackgroundWhite)); shape.setColor(getThemedColor(Theme.key_windowBackgroundWhite));
} }
contentContainer.setBackgroundDrawable(shape); contentContainer.setBackgroundDrawable(shape);
contentContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); contentContainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
@ -1265,6 +1268,11 @@ public final class FloatingToolbar {
return contentContainer; 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) { private static PopupWindow createPopupWindow(ViewGroup content) {
ViewGroup popupContentHolder = new LinearLayout(content.getContext()); ViewGroup popupContentHolder = new LinearLayout(content.getContext());
PopupWindow popupWindow = new PopupWindow(popupContentHolder); PopupWindow popupWindow = new PopupWindow(popupContentHolder);

View file

@ -19,6 +19,7 @@ import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.StateListDrawable;
import android.os.Build; import android.os.Build;
import android.text.Spanned;
import android.text.SpannedString; import android.text.SpannedString;
import android.text.TextPaint; import android.text.TextPaint;
import android.view.View; import android.view.View;
@ -30,6 +31,7 @@ import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.ui.Components.AnimatedArrowDrawable;
import org.telegram.ui.Components.AudioPlayerAlert; import org.telegram.ui.Components.AudioPlayerAlert;
import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView; import org.telegram.ui.Components.BackupImageView;
@ -115,9 +117,11 @@ public class ThemeDescription {
private HashMap<String, Field> cachedFields; private HashMap<String, Field> cachedFields;
private HashMap<String, Boolean> notFoundCachedFields; private HashMap<String, Boolean> notFoundCachedFields;
public Theme.ResourcesProvider resourcesProvider;
public interface ThemeDescriptionDelegate { public interface ThemeDescriptionDelegate {
void didSetColor(); 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) { 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) { } else if (drawablesToUpdate[a] instanceof AvatarDrawable) {
((AvatarDrawable) drawablesToUpdate[a]).setColor(color); ((AvatarDrawable) drawablesToUpdate[a]).setColor(color);
} else if (drawablesToUpdate[a] instanceof AnimatedArrowDrawable) {
((AnimatedArrowDrawable) drawablesToUpdate[a]).setColor(color);
} else { } else {
drawablesToUpdate[a].setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY)); 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(); TextView textView = i == 0 ? ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getTextView() : ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getNextTextView();
if (textView != null) { if (textView != null) {
textView.setTextColor(color); 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() { 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() { public void setDefaultColor() {

View file

@ -460,7 +460,7 @@ public class ActionIntroActivity extends BaseFragment implements LocationControl
desctiptionLines[a * 2 + 1].setText(spanned); desctiptionLines[a * 2 + 1].setText(spanned);
} else if (a == 1) { } else if (a == 1) {
desctiptionLines[a * 2 + 1].setText(LocaleController.getString("AuthAnotherClientInfo2", R.string.AuthAnotherClientInfo2)); 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)); desctiptionLines[a * 2 + 1].setText(LocaleController.getString("AuthAnotherClientInfo3", R.string.AuthAnotherClientInfo3));
} }
if (LocaleController.isRTL) { if (LocaleController.isRTL) {
@ -555,9 +555,8 @@ public class ActionIntroActivity extends BaseFragment implements LocationControl
return; return;
} }
Bundle args = new Bundle(); Bundle args = new Bundle();
ArrayList<Integer> result = new ArrayList<>(); long[] array = new long[]{getUserConfig().getClientUserId()};
result.add(getUserConfig().getClientUserId()); args.putLongArray("result", array);
args.putIntegerArrayList("result", result);
args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP); args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP);
args.putString("address", currentGroupCreateAddress); args.putString("address", currentGroupCreateAddress);
args.putParcelable("location", currentGroupCreateLocation); args.putParcelable("location", currentGroupCreateLocation);

View file

@ -12,6 +12,7 @@ import android.location.Location;
import android.os.Build; import android.os.Build;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.UserConfig; 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.geo_point._long = AndroidUtilities.fixLocationCoord(coordinate.getLongitude());
req.flags |= 1; req.flags |= 1;
int lower_id = (int) dialogId; if (DialogObject.isEncryptedDialog(dialogId)) {
int high_id = (int) (dialogId >> 32);
if (lower_id != 0) {
req.peer = MessagesController.getInstance(currentAccount).getInputPeer(lower_id);
} else {
req.peer = new TLRPC.TL_inputPeerEmpty(); req.peer = new TLRPC.TL_inputPeerEmpty();
} else {
req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId);
} }
currentRequestNum = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> { currentRequestNum = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {

View file

@ -12,7 +12,6 @@ import android.content.Context;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Build; import android.os.Build;
import android.util.SparseArray;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -44,6 +43,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
public class ContactsAdapter extends RecyclerListView.SectionsAdapter { public class ContactsAdapter extends RecyclerListView.SectionsAdapter {
@ -52,8 +52,8 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter {
private Context mContext; private Context mContext;
private int onlyUsers; private int onlyUsers;
private boolean needPhonebook; private boolean needPhonebook;
private SparseArray<TLRPC.User> ignoreUsers; private LongSparseArray<TLRPC.User> ignoreUsers;
private SparseArray<?> checkedMap; private LongSparseArray<?> checkedMap;
private ArrayList<TLRPC.TL_contact> onlineContacts; private ArrayList<TLRPC.TL_contact> onlineContacts;
private boolean scrolling; private boolean scrolling;
private boolean isAdmin; private boolean isAdmin;
@ -63,7 +63,7 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter {
private boolean hasGps; private boolean hasGps;
private boolean isEmpty; private boolean isEmpty;
public ContactsAdapter(Context context, int onlyUsersType, boolean showPhoneBook, SparseArray<TLRPC.User> usersToIgnore, int flags, boolean gps) { public ContactsAdapter(Context context, int onlyUsersType, boolean showPhoneBook, LongSparseArray<TLRPC.User> usersToIgnore, int flags, boolean gps) {
mContext = context; mContext = context;
onlyUsers = onlyUsersType; onlyUsers = onlyUsersType;
needPhonebook = showPhoneBook; needPhonebook = showPhoneBook;
@ -82,7 +82,7 @@ public class ContactsAdapter extends RecyclerListView.SectionsAdapter {
if (sortType == 2) { if (sortType == 2) {
if (onlineContacts == null || force) { if (onlineContacts == null || force) {
onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts); 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++) { for (int a = 0, N = onlineContacts.size(); a < N; a++) {
if (onlineContacts.get(a).user_id == selfId) { if (onlineContacts.get(a).user_id == selfId) {
onlineContacts.remove(a); 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; checkedMap = map;
} }

View file

@ -184,9 +184,9 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts); onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts);
prevContactsCount = onlineContacts.size(); prevContactsCount = onlineContacts.size();
prevDialogsCount = messagesController.dialogs_dict.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++) { 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) { if (userId == selfId || messagesController.dialogs_dict.get(userId) != null) {
onlineContacts.remove(a); onlineContacts.remove(a);
a--; a--;
@ -354,7 +354,7 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
View view; View view;
switch (viewType) { switch (viewType) {
case 0: 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.setArchivedPullAnimation(pullForegroundDrawable);
dialogCell.setPreloader(preloader); dialogCell.setPreloader(preloader);
view = dialogCell; view = dialogCell;

View file

@ -12,8 +12,6 @@ import android.content.Context;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -24,12 +22,12 @@ import org.telegram.SQLite.SQLitePreparedStatement;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject; import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
@ -55,6 +53,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@ -84,7 +83,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
private int dialogsType; private int dialogsType;
private SearchAdapterHelper searchAdapterHelper; private SearchAdapterHelper searchAdapterHelper;
private RecyclerListView innerListView; private RecyclerListView innerListView;
private int selfUserId; private long selfUserId;
private int currentAccount = UserConfig.selectedAccount; private int currentAccount = UserConfig.selectedAccount;
@ -93,8 +92,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
private ArrayList<FiltersView.DateData> localTipDates = new ArrayList<>(); private ArrayList<FiltersView.DateData> localTipDates = new ArrayList<>();
private boolean localTipArchive; private boolean localTipArchive;
private FilteredSearchView.Delegate filtersDelegate; private FilteredSearchView.Delegate filtersDelegate;
private int folderId;
private int currentItemCount; private int currentItemCount;
private int folderId;
public boolean isSearching() { public boolean isSearching() {
return waitingResponseCount > 0; return waitingResponseCount > 0;
@ -115,7 +114,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
public interface DialogsSearchAdapterDelegate { public interface DialogsSearchAdapterDelegate {
void searchStateChanged(boolean searching, boolean animated); void searchStateChanged(boolean searching, boolean animated);
void didPressedOnSubDialog(long did); void didPressedOnSubDialog(long did);
void needRemoveHint(int did); void needRemoveHint(long did);
void needClearList(); void needClearList();
void runResultsEnterAnimation(); void runResultsEnterAnimation();
boolean isSelected(long dialogId); boolean isSelected(long dialogId);
@ -157,7 +156,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
TLRPC.Dialog dialog = new TLRPC.TL_dialog(); TLRPC.Dialog dialog = new TLRPC.TL_dialog();
TLRPC.Chat chat = null; TLRPC.Chat chat = null;
TLRPC.User user = null; TLRPC.User user = null;
int did = 0; long did = 0;
if (peer.peer.user_id != 0) { if (peer.peer.user_id != 0) {
did = peer.peer.user_id; did = peer.peer.user_id;
user = MessagesController.getInstance(currentAccount).getUser(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) { public DialogsSearchAdapter(Context context, int messagesSearch, int type) {
this.folderId = folderId;
searchAdapterHelper = new SearchAdapterHelper(false); searchAdapterHelper = new SearchAdapterHelper(false);
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() { searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override @Override
@ -282,14 +280,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1); MessageObject lastMessage = searchResultMessages.get(searchResultMessages.size() - 1);
req.offset_id = lastMessage.getId(); req.offset_id = lastMessage.getId();
req.offset_rate = nextSearchRate; req.offset_rate = nextSearchRate;
int id; long id = MessageObject.getPeerId(lastMessage.messageOwner.peer_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;
}
req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id); req.offset_peer = MessagesController.getInstance(currentAccount).getInputPeer(id);
} else { } else {
req.offset_rate = 0; req.offset_rate = 0;
@ -302,8 +293,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
final ArrayList<MessageObject> messageObjects = new ArrayList<>(); final ArrayList<MessageObject> messageObjects = new ArrayList<>();
if (error == null) { if (error == null) {
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
SparseArray<TLRPC.Chat> chatsMap = new SparseArray<>(); LongSparseArray<TLRPC.Chat> chatsMap = new LongSparseArray<>();
SparseArray<TLRPC.User> usersMap = new SparseArray<>(); LongSparseArray<TLRPC.User> usersMap = new LongSparseArray<>();
for (int a = 0; a < res.chats.size(); a++) { for (int a = 0; a < res.chats.size(); a++) {
TLRPC.Chat chat = res.chats.get(a); TLRPC.Chat chat = res.chats.get(a);
chatsMap.put(chat.id, chat); chatsMap.put(chat.id, chat);
@ -335,8 +326,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
for (int a = 0; a < res.messages.size(); a++) { for (int a = 0; a < res.messages.size(); a++) {
TLRPC.Message message = res.messages.get(a); TLRPC.Message message = res.messages.get(a);
long did = MessageObject.getDialogId(message); long did = MessageObject.getDialogId(message);
Integer maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did); int maxId = MessagesController.getInstance(currentAccount).deletedHistory.get(did);
if (maxId != null && message.id <= maxId) { if (maxId != 0 && message.id <= maxId) {
continue; continue;
} }
searchResultMessages.add(messageObjects.get(a)); searchResultMessages.add(messageObjects.get(a));
@ -391,8 +382,8 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
try { try {
SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1"); SQLiteCursor cursor = MessagesStorage.getInstance(currentAccount).getDatabase().queryFinalized("SELECT did, date FROM search_recent WHERE 1");
ArrayList<Integer> usersToLoad = new ArrayList<>(); ArrayList<Long> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Long> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>(); ArrayList<Integer> encryptedToLoad = new ArrayList<>();
ArrayList<TLRPC.User> encUsers = new ArrayList<>(); ArrayList<TLRPC.User> encUsers = new ArrayList<>();
@ -402,23 +393,22 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
long did = cursor.longValue(0); long did = cursor.longValue(0);
boolean add = false; boolean add = false;
int lower_id = (int) did; if (DialogObject.isEncryptedDialog(did)) {
int high_id = (int) (did >> 32); if (dialogsType == 0 || dialogsType == 3) {
if (lower_id != 0) { int encryptedChatId = DialogObject.getEncryptedChatId(did);
if (lower_id > 0) { if (!encryptedToLoad.contains(encryptedChatId)) {
if (dialogsType != 2 && !usersToLoad.contains(lower_id)) { encryptedToLoad.add(encryptedChatId);
usersToLoad.add(lower_id);
add = true;
}
} else {
if (!chatsToLoad.contains(-lower_id)) {
chatsToLoad.add(-lower_id);
add = true; add = true;
} }
} }
} else if (dialogsType == 0 || dialogsType == 3) { } else if (DialogObject.isUserDialog(did)) {
if (!encryptedToLoad.contains(high_id)) { if (dialogsType != 2 && !usersToLoad.contains(did)) {
encryptedToLoad.add(high_id); usersToLoad.add(did);
add = true;
}
} else {
if (!chatsToLoad.contains(-did)) {
chatsToLoad.add(-did);
add = true; add = true;
} }
} }
@ -439,7 +429,10 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>(); ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<>();
MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad); MessagesStorage.getInstance(currentAccount).getEncryptedChatsInternal(TextUtils.join(",", encryptedToLoad), encryptedChats, usersToLoad);
for (int a = 0; a < encryptedChats.size(); a++) { 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); arrayList.remove(recentSearchObject);
} }
} else { } 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; searchWas = true;
for (int a = 0; a < result.size(); a++) { for (int a = 0; a < result.size(); a++) {
Object obj = result.get(a); Object obj = result.get(a);
int dialogId = 0; long dialogId = 0;
if (obj instanceof TLRPC.User) { if (obj instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) obj; TLRPC.User user = (TLRPC.User) obj;
MessagesController.getInstance(currentAccount).putUser(user, true); MessagesController.getInstance(currentAccount).putUser(user, true);
@ -628,7 +624,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
if (dialogId != 0) { if (dialogId != 0) {
TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId); TLRPC.Dialog dialog = MessagesController.getInstance(currentAccount).dialogs_dict.get(dialogId);
if (dialog == null) { if (dialog == null) {
int finalDialogId = dialogId; long finalDialogId = dialogId;
MessagesStorage.getInstance(currentAccount).getDialogFolderId(dialogId, param -> { MessagesStorage.getInstance(currentAccount).getDialogFolderId(dialogId, param -> {
if (param != -1) { if (param != -1) {
TLRPC.Dialog newDialog = new TLRPC.TL_dialog(); TLRPC.Dialog newDialog = new TLRPC.TL_dialog();
@ -908,7 +904,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null; View view;
switch (viewType) { switch (viewType) {
case 0: case 0:
view = new ProfileSearchCell(mContext); view = new ProfileSearchCell(mContext);
@ -953,12 +949,12 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
horizontalListView.setAdapter(new CategoryAdapterRecycler(mContext, currentAccount, false)); horizontalListView.setAdapter(new CategoryAdapterRecycler(mContext, currentAccount, false));
horizontalListView.setOnItemClickListener((view1, position) -> { horizontalListView.setOnItemClickListener((view1, position) -> {
if (delegate != null) { if (delegate != null) {
delegate.didPressedOnSubDialog((Integer) view1.getTag()); delegate.didPressedOnSubDialog((Long) view1.getTag());
} }
}); });
horizontalListView.setOnItemLongClickListener((view12, position) -> { horizontalListView.setOnItemLongClickListener((view12, position) -> {
if (delegate != null) { if (delegate != null) {
delegate.needRemoveHint((Integer) view12.getTag()); delegate.needRemoveHint((Long) view12.getTag());
} }
return true; return true;
}); });
@ -966,6 +962,7 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
innerListView = horizontalListView; innerListView = horizontalListView;
break; break;
case 6: case 6:
default:
view = new TextCell(mContext, 16, false); view = new TextCell(mContext, 16, false);
break; break;
} }

View file

@ -75,8 +75,8 @@ public class FiltersView extends RecyclerListView {
private ArrayList<MediaFilterData> oldItems = new ArrayList<>(); private ArrayList<MediaFilterData> oldItems = new ArrayList<>();
LinearLayoutManager layoutManager; LinearLayoutManager layoutManager;
public FiltersView(Context context) { public FiltersView(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context, resourcesProvider);
layoutManager = new LinearLayoutManager(context) { layoutManager = new LinearLayoutManager(context) {
@Override @Override
public boolean supportsPredictiveItemAnimations() { public boolean supportsPredictiveItemAnimations() {
@ -199,7 +199,7 @@ public class FiltersView extends RecyclerListView {
setWillNotDraw(false); setWillNotDraw(false);
setHideIfEmpty(false); setHideIfEmpty(false);
setSelectorRadius(AndroidUtilities.dp(28)); 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(); ((FilterView) view).updateColors();
} }
} }
setSelectorDrawableColor(Theme.getColor(Theme.key_listSelector)); setSelectorDrawableColor(getThemedColor(Theme.key_listSelector));
} }
private class Adapter extends RecyclerListView.SelectionAdapter { private class Adapter extends RecyclerListView.SelectionAdapter {
@ -627,7 +627,7 @@ public class FiltersView extends RecyclerListView {
@NonNull @NonNull
@Override @Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 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)); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, AndroidUtilities.dp(32));
lp.topMargin = AndroidUtilities.dp(6); lp.topMargin = AndroidUtilities.dp(6);
holder.itemView.setLayoutParams(lp); holder.itemView.setLayoutParams(lp);
@ -692,13 +692,16 @@ public class FiltersView extends RecyclerListView {
public static class FilterView extends FrameLayout { public static class FilterView extends FrameLayout {
private final Theme.ResourcesProvider resourcesProvider;
BackupImageView avatarImageView; BackupImageView avatarImageView;
TextView titleView; TextView titleView;
CombinedDrawable thumbDrawable; CombinedDrawable thumbDrawable;
MediaFilterData data; MediaFilterData data;
public FilterView(Context context) { public FilterView(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context); super(context);
this.resourcesProvider = resourcesProvider;
avatarImageView = new BackupImageView(context); avatarImageView = new BackupImageView(context);
addView(avatarImageView, LayoutHelper.createFrame(32, 32)); addView(avatarImageView, LayoutHelper.createFrame(32, 32));
@ -709,15 +712,15 @@ public class FiltersView extends RecyclerListView {
} }
private void updateColors() { private void updateColors() {
setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(28), Theme.getColor(Theme.key_groupcreate_spanBackground))); setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(28), getThemedColor(Theme.key_groupcreate_spanBackground)));
titleView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); titleView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteBlackText));
if (thumbDrawable != null) { if (thumbDrawable != null) {
if (data.filterType == FILTER_TYPE_ARCHIVE) { if (data.filterType == FILTER_TYPE_ARCHIVE) {
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
} else { } else {
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
} }
} }
} }
@ -728,23 +731,23 @@ public class FiltersView extends RecyclerListView {
if (data.filterType == FILTER_TYPE_ARCHIVE) { if (data.filterType == FILTER_TYPE_ARCHIVE) {
thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive); thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_archive);
thumbDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); thumbDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16));
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundArchived), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundArchived), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
avatarImageView.setImageDrawable(thumbDrawable); avatarImageView.setImageDrawable(thumbDrawable);
titleView.setText(data.title); titleView.setText(data.title);
return; return;
} }
thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled); thumbDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), data.iconResFilled);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_backgroundBlue), false); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_backgroundBlue), false);
Theme.setCombinedDrawableColor(thumbDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(thumbDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
if (data.filterType == FILTER_TYPE_CHAT) { if (data.filterType == FILTER_TYPE_CHAT) {
if (data.chat instanceof TLRPC.User) { if (data.chat instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) data.chat; TLRPC.User user = (TLRPC.User) data.chat;
if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) { if (UserConfig.getInstance(UserConfig.selectedAccount).getCurrentUser().id == user.id) {
CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved); CombinedDrawable combinedDrawable = Theme.createCircleDrawableWithIcon(AndroidUtilities.dp(32), R.drawable.chats_saved);
combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16)); combinedDrawable.setIconSize(AndroidUtilities.dp(16), AndroidUtilities.dp(16));
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_backgroundSaved), false); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_backgroundSaved), false);
Theme.setCombinedDrawableColor(combinedDrawable, Theme.getColor(Theme.key_avatar_actionBarIconBlue), true); Theme.setCombinedDrawableColor(combinedDrawable, getThemedColor(Theme.key_avatar_actionBarIconBlue), true);
avatarImageView.setImageDrawable(combinedDrawable); avatarImageView.setImageDrawable(combinedDrawable);
} else { } else {
avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16)); avatarImageView.getImageReceiver().setRoundRadius(AndroidUtilities.dp(16));
@ -760,6 +763,11 @@ public class FiltersView extends RecyclerListView {
} }
titleView.setText(data.title); 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 { private class ViewHolder extends RecyclerListView.ViewHolder {

View file

@ -63,13 +63,15 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
private boolean needEmptyView; private boolean needEmptyView;
private Runnable updateRunnable; 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(); super();
mContext = context; mContext = context;
locationType = type; locationType = type;
dialogId = did; dialogId = did;
needEmptyView = emptyView; needEmptyView = emptyView;
this.resourcesProvider = resourcesProvider;
} }
public void setOverScrollHeight(int value) { public void setOverScrollHeight(int value) {
@ -119,7 +121,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
public void setLiveLocations(ArrayList<LocationActivity.LiveLocation> liveLocations) { public void setLiveLocations(ArrayList<LocationActivity.LiveLocation> liveLocations) {
currentLiveLocations = new 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++) { for (int a = 0; a < currentLiveLocations.size(); a++) {
if (currentLiveLocations.get(a).id == uid || currentLiveLocations.get(a).object.out) { if (currentLiveLocations.get(a).id == uid || currentLiveLocations.get(a).object.out) {
currentLiveLocations.remove(a); currentLiveLocations.remove(a);
@ -261,31 +263,31 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
}; };
break; break;
case 1: case 1:
view = new SendLocationCell(mContext, false); view = new SendLocationCell(mContext, false, resourcesProvider);
break; break;
case 2: case 2:
view = new HeaderCell(mContext); view = new HeaderCell(mContext, resourcesProvider);
break; break;
case 3: case 3:
view = new LocationCell(mContext, false); view = new LocationCell(mContext, false, resourcesProvider);
break; break;
case 4: case 4:
view = new LocationLoadingCell(mContext); view = new LocationLoadingCell(mContext, resourcesProvider);
break; break;
case 5: case 5:
view = new LocationPoweredCell(mContext); view = new LocationPoweredCell(mContext, resourcesProvider);
break; break;
case 6: { case 6: {
SendLocationCell cell = new SendLocationCell(mContext, true); SendLocationCell cell = new SendLocationCell(mContext, true, resourcesProvider);
cell.setDialogId(dialogId); cell.setDialogId(dialogId);
view = cell; view = cell;
break; break;
} }
case 7: 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; break;
case 8: { case 8: {
LocationDirectionCell cell = new LocationDirectionCell(mContext); LocationDirectionCell cell = new LocationDirectionCell(mContext, resourcesProvider);
cell.setOnButtonClick(v -> onDirectionClick()); cell.setOnButtonClick(v -> onDirectionClick());
view = cell; view = cell;
break; break;
@ -293,7 +295,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
case 9: { case 9: {
view = new ShadowSectionCell(mContext); view = new ShadowSectionCell(mContext);
Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow); 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); combinedDrawable.setFullsize(true);
view.setBackgroundDrawable(combinedDrawable); view.setBackgroundDrawable(combinedDrawable);
break; break;
@ -478,4 +480,9 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
} }
return viewType == 1 || viewType == 3 || viewType == 7; 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);
}
} }

View file

@ -33,7 +33,7 @@ public class LocationActivitySearchAdapter extends BaseLocationAdapter {
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 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 @Override

View file

@ -15,7 +15,6 @@ import android.content.pm.PackageManager;
import android.location.Location; import android.location.Location;
import android.os.Build; import android.os.Build;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.SparseArray;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -24,6 +23,7 @@ import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ContactsController; import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.Emoji; import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.ImageLocation; 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.MentionCell;
import org.telegram.ui.Cells.StickerCell; import org.telegram.ui.Cells.StickerCell;
import org.telegram.ui.ChatActivity; import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.EmojiView;
import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.RecyclerListView;
import java.io.File; import java.io.File;
@ -58,6 +59,7 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
public class MentionsAdapter extends RecyclerListView.SelectionAdapter implements NotificationCenter.NotificationCenterDelegate { 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 int currentAccount = UserConfig.selectedAccount;
private Context mContext; private Context mContext;
private long dialog_id; private long dialog_id;
private int threadMessageId;
private TLRPC.ChatFull info; private TLRPC.ChatFull info;
private SearchAdapterHelper searchAdapterHelper; private SearchAdapterHelper searchAdapterHelper;
private ArrayList<TLObject> searchResultUsernames; private ArrayList<TLObject> searchResultUsernames;
private SparseArray<TLObject> searchResultUsernamesMap; private LongSparseArray<TLObject> searchResultUsernamesMap;
private Runnable searchGlobalRunnable; private Runnable searchGlobalRunnable;
private ArrayList<String> searchResultHashtags; private ArrayList<String> searchResultHashtags;
private ArrayList<String> searchResultCommands; private ArrayList<String> searchResultCommands;
@ -85,7 +88,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
private ArrayList<TLRPC.BotInlineResult> searchResultBotContext; private ArrayList<TLRPC.BotInlineResult> searchResultBotContext;
private TLRPC.TL_inlineBotSwitchPM searchResultBotContextSwitch; private TLRPC.TL_inlineBotSwitchPM searchResultBotContextSwitch;
private MentionsAdapterDelegate delegate; private MentionsAdapterDelegate delegate;
private SparseArray<TLRPC.BotInfo> botInfo; private LongSparseArray<TLRPC.BotInfo> botInfo;
private int resultStartPosition; private int resultStartPosition;
private int resultLength; private int resultLength;
private String lastText; private String lastText;
@ -102,6 +105,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
private int channelReqId; private int channelReqId;
private boolean isSearchingMentions; private boolean isSearchingMentions;
private EmojiView.ChooseStickerActionTracker mentionsStickersActionTracker;
private boolean visibleByStickersSearch; private boolean visibleByStickersSearch;
private final static String punctuationsChars = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n"; private final static String punctuationsChars = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n";
@ -127,6 +132,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
private boolean delayLocalResults; private boolean delayLocalResults;
private ChatActivity parentFragment; private ChatActivity parentFragment;
private final Theme.ResourcesProvider resourcesProvider;
private static class StickerResult { private static class StickerResult {
public TLRPC.Document sticker; 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; mContext = context;
delegate = mentionsAdapterDelegate; delegate = mentionsAdapterDelegate;
isDarkTheme = darkTheme; isDarkTheme = darkTheme;
dialog_id = did; dialog_id = did;
this.threadMessageId = threadMessageId;
searchAdapterHelper = new SearchAdapterHelper(true); searchAdapterHelper = new SearchAdapterHelper(true);
searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() { searchAdapterHelper.setDelegate(new SearchAdapterHelper.SearchAdapterHelperDelegate() {
@Override @Override
@ -211,6 +219,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
} }
stickers.add(new StickerResult(document, parent)); stickers.add(new StickerResult(document, parent));
stickersMap.put(key, document); stickersMap.put(key, document);
if (mentionsStickersActionTracker != null) {
mentionsStickersActionTracker.checkVisibility();
}
} }
private void addStickersToResult(ArrayList<TLRPC.Document> documents, Object parent) { private void addStickersToResult(ArrayList<TLRPC.Document> documents, Object parent) {
@ -306,6 +317,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
ConnectionsManager.getInstance(currentAccount).cancelRequest(lastReqId, true); ConnectionsManager.getInstance(currentAccount).cancelRequest(lastReqId, true);
lastReqId = 0; lastReqId = 0;
} }
if (mentionsStickersActionTracker != null) {
mentionsStickersActionTracker.checkVisibility();
}
} }
public void onDestroy() { public void onDestroy() {
@ -367,7 +381,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
needBotContext = value; needBotContext = value;
} }
public void setBotInfo(SparseArray<TLRPC.BotInfo> info) { public void setBotInfo(LongSparseArray<TLRPC.BotInfo> info) {
botInfo = info; botInfo = info;
} }
@ -388,7 +402,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
return searchResultBotContextSwitch; return searchResultBotContextSwitch;
} }
public int getContextBotId() { public long getContextBotId() {
return foundContextBot != null ? foundContextBot.id : 0; return foundContextBot != null ? foundContextBot.id : 0;
} }
@ -623,7 +637,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
if (user.bot_inline_geo && lastKnownLocation == null) { if (user.bot_inline_geo && lastKnownLocation == null) {
return; 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); final MessagesStorage messagesStorage = MessagesStorage.getInstance(currentAccount);
RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> { RequestDelegate requestDelegate = (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (!query.equals(searchingContextQuery)) { 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.lat = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLatitude());
req.geo_point._long = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLongitude()); req.geo_point._long = AndroidUtilities.fixLocationCoord(lastKnownLocation.getLongitude());
} }
int lower_id = (int) dialog_id; if (DialogObject.isEncryptedDialog(dialog_id)) {
int high_id = (int) (dialog_id >> 32);
if (lower_id != 0) {
req.peer = MessagesController.getInstance(currentAccount).getInputPeer(lower_id);
} else {
req.peer = new TLRPC.TL_inputPeerEmpty(); req.peer = new TLRPC.TL_inputPeerEmpty();
} else {
req.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialog_id);
} }
contextQueryReqid = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors); contextQueryReqid = ConnectionsManager.getInstance(currentAccount).sendRequest(req, requestDelegate, ConnectionsManager.RequestFlagFailOnServerErrors);
} }
@ -966,9 +978,9 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
return; return;
} }
if (foundType == 0) { if (foundType == 0) {
final ArrayList<Integer> users = new ArrayList<>(); final ArrayList<Long> users = new ArrayList<>();
for (int a = 0; a < Math.min(100, messageObjects.size()); a++) { 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)) { if (from_id > 0 && !users.contains(from_id)) {
users.add(from_id); users.add(from_id);
} }
@ -976,8 +988,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
final String usernameString = result.toString().toLowerCase(); final String usernameString = result.toString().toLowerCase();
boolean hasSpace = usernameString.indexOf(' ') >= 0; boolean hasSpace = usernameString.indexOf(' ') >= 0;
ArrayList<TLObject> newResult = new ArrayList<>(); ArrayList<TLObject> newResult = new ArrayList<>();
final SparseArray<TLRPC.User> newResultsHashMap = new SparseArray<>(); final LongSparseArray<TLRPC.User> newResultsHashMap = new LongSparseArray<>();
final SparseArray<TLObject> newMap = new SparseArray<>(); final LongSparseArray<TLObject> newMap = new LongSparseArray<>();
ArrayList<TLRPC.TL_topPeer> inlineBots = MediaDataController.getInstance(currentAccount).inlineBots; ArrayList<TLRPC.TL_topPeer> inlineBots = MediaDataController.getInstance(currentAccount).inlineBots;
if (!usernameOnly && needBotContext && dogPostion == 0 && !inlineBots.isEmpty()) { if (!usernameOnly && needBotContext && dogPostion == 0 && !inlineBots.isEmpty()) {
int count = 0; int count = 0;
@ -1015,11 +1027,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
String firstName; String firstName;
String lastName; String lastName;
TLObject object; TLObject object;
int id; long id;
if (a == -1) { if (a == -1) {
if (chat == null) {
continue;
}
if (usernameString.length() == 0) { if (usernameString.length() == 0) {
newResult.add(chat); newResult.add(chat);
continue; continue;
@ -1058,7 +1067,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
} }
Collections.sort(newResult, new Comparator<TLObject>() { Collections.sort(newResult, new Comparator<TLObject>() {
private int getId(TLObject object) { private long getId(TLObject object) {
if (object instanceof TLRPC.User) { if (object instanceof TLRPC.User) {
return ((TLRPC.User) object).id; return ((TLRPC.User) object).id;
} else { } else {
@ -1068,8 +1077,8 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
@Override @Override
public int compare(TLObject lhs, TLObject rhs) { public int compare(TLObject lhs, TLObject rhs) {
int id1 = getId(lhs); long id1 = getId(lhs);
int id2 = getId(rhs); long id2 = getId(rhs);
if (newMap.indexOfKey(id1) >= 0 && newMap.indexOfKey(id2) >= 0) { if (newMap.indexOfKey(id1) >= 0 && newMap.indexOfKey(id2) >= 0) {
return 0; return 0;
} else if (newMap.indexOfKey(id1) >= 0) { } else if (newMap.indexOfKey(id1) >= 0) {
@ -1133,10 +1142,10 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
messagesController.putChats(res.chats, false); messagesController.putChats(res.chats, false);
boolean hasResults = !searchResultUsernames.isEmpty(); boolean hasResults = !searchResultUsernames.isEmpty();
if (!res.participants.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++) { for (int a = 0; a < res.participants.size(); a++) {
TLRPC.ChannelParticipant participant = res.participants.get(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) { if (searchResultUsernamesMap.indexOfKey(peerId) >= 0 || !isSearchingMentions && peerId == currentUserId) {
continue; continue;
} }
@ -1241,7 +1250,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
} }
} }
private void showUsersResult(ArrayList<TLObject> newResult, SparseArray<TLObject> newMap, boolean notify) { private void showUsersResult(ArrayList<TLObject> newResult, LongSparseArray<TLObject> newMap, boolean notify) {
searchResultUsernames = newResult; searchResultUsernames = newResult;
searchResultUsernamesMap = newMap; searchResultUsernamesMap = newMap;
if (cancelDelayRunnable != null) { if (cancelDelayRunnable != null) {
@ -1412,7 +1421,7 @@ public class MentionsAdapter extends RecyclerListView.SelectionAdapter implement
TextView textView = new TextView(mContext); TextView textView = new TextView(mContext);
textView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8)); textView.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); textView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText2));
view = textView; view = textView;
break; break;
case 4: 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);
}
} }

View file

@ -15,6 +15,7 @@ import android.view.ViewGroup;
import org.telegram.messenger.MediaDataController; import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.DialogCell; import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Cells.LoadingCell; import org.telegram.ui.Cells.LoadingCell;
import org.telegram.ui.Components.RecyclerListView; import org.telegram.ui.Components.RecyclerListView;
@ -29,8 +30,10 @@ public class MessagesSearchAdapter extends RecyclerListView.SelectionAdapter {
private ArrayList<MessageObject> searchResultMessages = new ArrayList<>(); private ArrayList<MessageObject> searchResultMessages = new ArrayList<>();
private int currentAccount = UserConfig.selectedAccount; 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; mContext = context;
} }
@ -67,7 +70,7 @@ public class MessagesSearchAdapter extends RecyclerListView.SelectionAdapter {
View view = null; View view = null;
switch (viewType) { switch (viewType) {
case 0: case 0:
view = new DialogCell(null, mContext, false, true); view = new DialogCell(null, mContext, false, true, currentAccount, resourcesProvider);
break; break;
case 1: case 1:
view = new LoadingCell(mContext); view = new LoadingCell(mContext);

View file

@ -12,7 +12,6 @@ import android.content.Context;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.Spanned; import android.text.Spanned;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -40,16 +39,17 @@ import java.util.ArrayList;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import androidx.collection.LongSparseArray;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
public class SearchAdapter extends RecyclerListView.SelectionAdapter { public class SearchAdapter extends RecyclerListView.SelectionAdapter {
private Context mContext; private Context mContext;
private SparseArray<TLRPC.User> ignoreUsers; private LongSparseArray<TLRPC.User> ignoreUsers;
private ArrayList<Object> searchResult = new ArrayList<>(); private ArrayList<Object> searchResult = new ArrayList<>();
private ArrayList<CharSequence> searchResultNames = new ArrayList<>(); private ArrayList<CharSequence> searchResultNames = new ArrayList<>();
private SearchAdapterHelper searchAdapterHelper; private SearchAdapterHelper searchAdapterHelper;
private SparseArray<?> checkedMap; private LongSparseArray<?> checkedMap;
private Timer searchTimer; private Timer searchTimer;
private boolean allowUsernameSearch; private boolean allowUsernameSearch;
private boolean useUserCell; private boolean useUserCell;
@ -58,13 +58,13 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
private boolean allowBots; private boolean allowBots;
private boolean allowSelf; private boolean allowSelf;
private boolean allowPhoneNumbers; private boolean allowPhoneNumbers;
private int channelId; private long channelId;
private boolean searchInProgress; private boolean searchInProgress;
private int searchReqId; private int searchReqId;
private int searchPointer; private int searchPointer;
public SearchAdapter(Context context, SparseArray<TLRPC.User> arg1, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) { public SearchAdapter(Context context, LongSparseArray<TLRPC.User> arg1, boolean usernameSearch, boolean mutual, boolean chats, boolean bots, boolean self, boolean phones, int searchChannelId) {
mContext = context; mContext = context;
ignoreUsers = arg1; ignoreUsers = arg1;
onlyMutual = mutual; onlyMutual = mutual;
@ -85,13 +85,13 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
} }
@Override @Override
public SparseArray<TLRPC.User> getExcludeUsers() { public LongSparseArray<TLRPC.User> getExcludeUsers() {
return ignoreUsers; return ignoreUsers;
} }
}); });
} }
public void setCheckedMap(SparseArray<?> map) { public void setCheckedMap(LongSparseArray<?> map) {
checkedMap = map; checkedMap = map;
} }
@ -312,7 +312,7 @@ public class SearchAdapter extends RecyclerListView.SelectionAdapter {
case 0: { case 0: {
TLObject object = (TLObject) getItem(position); TLObject object = (TLObject) getItem(position);
if (object != null) { if (object != null) {
int id = 0; long id = 0;
String un = null; String un = null;
boolean self = false; boolean self = false;
if (object instanceof TLRPC.User) { if (object instanceof TLRPC.User) {

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