Update to 8.0.1 (2428)

This commit is contained in:
xaxtix 2021-09-20 01:10:42 +03:00
parent 368822d20f
commit 418f478a62
351 changed files with 22086 additions and 13428 deletions

View File

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

View File

@ -1,11 +1,11 @@
cmake_minimum_required(VERSION 3.6.0)
set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID")
set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1")
set(CMAKE_CXX_FLAGS "-std=c++14 -DANDROID -g")
set(CMAKE_C_FLAGS "-w -std=c11 -DANDROID -D_LARGEFILE_SOURCE=1 -g")
set(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections -Wl,--exclude-libs,libtgvoip.a,libtgcalls.a,libtgcalls_tp.a,libtgnet.a,liblz4.a,libwebp.a,libflac.a,librlottie.a,libsqlite.a,
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--exclude-libs,libtgvoip.a,libtgcalls.a,libtgcalls_tp.a,libtgnet.a,liblz4.a,libwebp.a,libflac.a,librlottie.a,libsqlite.a,
${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libswscale.a,
${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavformat.a,
${CMAKE_HOME_DIRECTORY}/ffmpeg/${ANDROID_ABI}/libavcodec.a,

View File

@ -190,7 +190,7 @@ jint getConnectionState(JNIEnv *env, jclass c, jint instanceNum) {
return ConnectionsManager::getInstance(instanceNum).getConnectionState();
}
void setUserId(JNIEnv *env, jclass c, jint instanceNum, int32_t id) {
void setUserId(JNIEnv *env, jclass c, jint instanceNum, int64_t id) {
ConnectionsManager::getInstance(instanceNum).setUserId(id);
}
@ -371,7 +371,7 @@ void setSystemLangCode(JNIEnv *env, jclass c, jint instanceNum, jstring langCode
}
}
void init(JNIEnv *env, jclass c, jint instanceNum, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring systemLangCode, jstring configPath, jstring logPath, jstring regId, jstring cFingerprint, jstring installerId, jstring packageId, jint timezoneOffset, jint userId, jboolean enablePushConnection, jboolean hasNetwork, jint networkType) {
void init(JNIEnv *env, jclass c, jint instanceNum, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring systemLangCode, jstring configPath, jstring logPath, jstring regId, jstring cFingerprint, jstring installerId, jstring packageId, jint timezoneOffset, jlong userId, jboolean enablePushConnection, jboolean hasNetwork, jint networkType) {
const char *deviceModelStr = env->GetStringUTFChars(deviceModel, 0);
const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0);
const char *appVersionStr = env->GetStringUTFChars(appVersion, 0);
@ -443,8 +443,8 @@ static JNINativeMethod ConnectionsManagerMethods[] = {
{"native_applyDatacenterAddress", "(IILjava/lang/String;I)V", (void *) applyDatacenterAddress},
{"native_setProxySettings", "(ILjava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", (void *) setProxySettings},
{"native_getConnectionState", "(I)I", (void *) getConnectionState},
{"native_setUserId", "(II)V", (void *) setUserId},
{"native_init", "(IIIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIZZI)V", (void *) init},
{"native_setUserId", "(IJ)V", (void *) setUserId},
{"native_init", "(IIIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IJZZI)V", (void *) init},
{"native_setLangCode", "(ILjava/lang/String;)V", (void *) setLangCode},
{"native_setRegId", "(ILjava/lang/String;)V", (void *) setRegId},
{"native_setSystemLangCode", "(ILjava/lang/String;)V", (void *) setSystemLangCode},

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

View File

@ -295,7 +295,7 @@ public:
class User : public TLObject {
public:
int32_t id;
int64_t id;
std::string first_name;
std::string last_name;
std::string username;
@ -315,7 +315,7 @@ public:
class TL_userEmpty : public User {
public:
static const uint32_t constructor = 0x200250ba;
static const uint32_t constructor = 0xd3bc4b7a;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -324,7 +324,7 @@ public:
class TL_user : public User {
public:
static const uint32_t constructor = 0x938458c1;
static const uint32_t constructor = 0x3ff6ecb0;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -333,9 +333,9 @@ public:
class InputPeer : public TLObject {
public:
int32_t user_id;
int32_t chat_id;
int32_t channel_id;
int64_t user_id;
int64_t chat_id;
int64_t channel_id;
int64_t access_hash;
static InputPeer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error);
@ -352,7 +352,7 @@ public:
class TL_inputPeerUser : public InputPeer {
public:
static const uint32_t constructor = 0x7b8e7de6;
static const uint32_t constructor = 0xdde8a54c;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -361,7 +361,7 @@ public:
class TL_inputPeerChat : public InputPeer {
public:
static const uint32_t constructor = 0x179be863;
static const uint32_t constructor = 0x35a95cb9;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -370,7 +370,7 @@ public:
class TL_inputPeerUserFromMessage : public InputPeer {
public:
static const uint32_t constructor = 0x17bae2e6;
static const uint32_t constructor = 0xa87b0a1c;
std::unique_ptr<InputPeer> peer;
int32_t msg_id;
@ -382,7 +382,7 @@ public:
class TL_inputPeerChannelFromMessage : public InputPeer {
public:
static const uint32_t constructor = 0x9c95f7bb;
static const uint32_t constructor = 0xbd2a0840;
std::unique_ptr<InputPeer> peer;
int32_t msg_id;
@ -394,7 +394,7 @@ public:
class TL_inputPeerChannel : public InputPeer {
public:
static const uint32_t constructor = 0x20adaef8;
static const uint32_t constructor = 0x27bcbbfc;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -411,7 +411,7 @@ public:
class InputUser : public TLObject {
public:
int32_t user_id;
int64_t user_id;
int64_t access_hash;
static InputUser *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error);
@ -428,7 +428,7 @@ public:
class TL_inputUser : public InputUser {
public:
static const uint32_t constructor = 0xd8292816;
static const uint32_t constructor = 0xf21158c6;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -445,7 +445,7 @@ public:
class TL_inputUserFromMessage : public InputUser {
public:
static const uint32_t constructor = 0x2d117597;
static const uint32_t constructor = 0x1da448e2;
std::unique_ptr<InputPeer> peer;
int32_t msg_id;
@ -539,9 +539,9 @@ public:
class TL_messageEntityMentionName : public MessageEntity {
public:
static const uint32_t constructor = 0x352dca58;
static const uint32_t constructor = 0xdc7b1140;
int32_t user_id;
int64_t user_id;
void readParams(NativeByteBuffer *stream, int32_t instanceNum, bool &error);
void serializeToStream(NativeByteBuffer *stream);
@ -693,9 +693,9 @@ public:
class TL_auth_exportedAuthorization : public TLObject {
public:
static const uint32_t constructor = 0xdf969c2d;
static const uint32_t constructor = 0xb434e2b8;
int32_t id;
int64_t id;
std::unique_ptr<ByteArray> bytes;
static TL_auth_exportedAuthorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, int32_t instanceNum, bool &error);
@ -717,9 +717,9 @@ public:
class TL_auth_importAuthorization : public TLObject {
public:
static const uint32_t constructor = 0xe3ef9613;
static const uint32_t constructor = 0xa57a7dad;
int32_t id;
int64_t id;
std::unique_ptr<ByteArray> bytes;
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] {
int32_t oldUserId = currentUserId;
currentUserId = userId;
@ -3261,7 +3261,7 @@ void ConnectionsManager::applyDnsConfig(NativeByteBuffer *buffer, std::string ph
});
}
void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int32_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType) {
void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType) {
currentVersion = version;
currentLayer = layer;
currentApiId = apiId;

View File

@ -57,13 +57,13 @@ public:
void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port);
void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate);
ConnectionState getConnectionState();
void setUserId(int32_t userId);
void setUserId(int64_t userId);
void switchBackend(bool restart);
void resumeNetwork(bool partial);
void pauseNetwork();
void setNetworkAvailable(bool value, int32_t type, bool slow);
void setIpStrategy(uint8_t value);
void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerprint, std::string installerId, std::string packageId, int32_t timezoneOffset, int32_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType);
void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerprint, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType);
void setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret);
void setLangCode(std::string langCode);
void setRegId(std::string regId);
@ -222,7 +222,7 @@ private:
std::string currentSystemLangCode;
std::string currentConfigPath;
std::string currentLogPath;
int32_t currentUserId = 0;
int64_t currentUserId = 0;
bool registeredForInternalPush = false;
bool pushConnectionEnabled = true;

View File

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

View File

@ -340,16 +340,6 @@
<action android:name="android.media.browse.MediaBrowserService"/>
</intent-filter>
</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">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />

View File

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

View File

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

View File

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

View File

@ -243,6 +243,8 @@ public class AndroidUtilities {
R.drawable.media_doc_yellow_b
};
public static final String STICKERS_PLACEHOLDER_PACK_NAME = "tg_placeholders_android";
private static boolean containsUnsupportedCharacters(String text) {
if (text.contains("\u202C")) {
return true;
@ -337,13 +339,13 @@ public class AndroidUtilities {
return str;
}
public static CharSequence highlightText(CharSequence str, ArrayList<String> query) {
public static CharSequence highlightText(CharSequence str, ArrayList<String> query, Theme.ResourcesProvider resourcesProvider) {
if (query == null) {
return null;
}
int emptyCount = 0;
for (int i = 0; i < query.size(); i++) {
CharSequence strTmp = highlightText(str, query.get(i));
CharSequence strTmp = highlightText(str, query.get(i), resourcesProvider);
if (strTmp != null) {
str = strTmp;
} else {
@ -356,7 +358,7 @@ public class AndroidUtilities {
return str;
}
public static CharSequence highlightText(CharSequence str, String query) {
public static CharSequence highlightText(CharSequence str, String query, Theme.ResourcesProvider resourcesProvider) {
if (TextUtils.isEmpty(query) || TextUtils.isEmpty(str)) {
return null;
}
@ -365,7 +367,7 @@ public class AndroidUtilities {
int i = s.indexOf(query);
while (i >= 0) {
try {
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), i, Math.min(i + query.length(), str.length()), 0);
spannableStringBuilder.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), i, Math.min(i + query.length(), str.length()), 0);
} catch (Exception e) {
FileLog.e(e);
}
@ -1616,6 +1618,15 @@ public class AndroidUtilities {
return -1;
}
public static int compare(long lhs, long rhs) {
if (lhs == rhs) {
return 0;
} else if (lhs > rhs) {
return 1;
}
return -1;
}
public static float dpf2(float value) {
if (value == 0) {
return 0;
@ -2231,12 +2242,33 @@ public class AndroidUtilities {
}*/
public static void startAppCenter(Activity context) {
// if (BuildConfig.DEBUG) {
// return;
// }
// try {
// if (BuildVars.DEBUG_VERSION) {
// Distribute.setEnabledForDebuggableBuild(true);
// AppCenter.start(context.getApplication(), BuildVars.DEBUG_VERSION ? BuildVars.APPCENTER_HASH_DEBUG : BuildVars.APPCENTER_HASH, Distribute.class, Crashes.class);
// AppCenter.setUserId("uid=" + UserConfig.getInstance(UserConfig.selectedAccount).clientUserId);
// }
// } catch (Throwable e) {
// FileLog.e(e);
// }
}
private static long lastUpdateCheckTime;
public static void checkForUpdates() {
// try {
// if (BuildVars.DEBUG_VERSION) {
// if (SystemClock.elapsedRealtime() - lastUpdateCheckTime < 60 * 60 * 1000) {
// return;
// }
// lastUpdateCheckTime = SystemClock.elapsedRealtime();
// Distribute.checkForUpdate();
// }
// } catch (Throwable e) {
// FileLog.e(e);
// }
}
public static void addToClipboard(CharSequence str) {
@ -2804,7 +2836,7 @@ public class AndroidUtilities {
}
}
public static boolean openForView(File f, String fileName, String mimeType, final Activity activity) {
public static boolean openForView(File f, String fileName, String mimeType, final Activity activity, Theme.ResourcesProvider resourcesProvider) {
if (f != null && f.exists()) {
String realMimeType = null;
Intent intent = new Intent(Intent.ACTION_VIEW);
@ -2822,7 +2854,7 @@ public class AndroidUtilities {
}
}
if (Build.VERSION.SDK_INT >= 26 && realMimeType != null && realMimeType.equals("application/vnd.android.package-archive") && !ApplicationLoader.applicationContext.getPackageManager().canRequestPackageInstalls()) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog.Builder builder = new AlertDialog.Builder(activity, resourcesProvider);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("ApkRestricted", R.string.ApkRestricted));
builder.setPositiveButton(LocaleController.getString("PermissionOpenSettings", R.string.PermissionOpenSettings), (dialogInterface, i) -> {
@ -2860,7 +2892,7 @@ public class AndroidUtilities {
return false;
}
public static boolean openForView(MessageObject message, Activity activity) {
public static boolean openForView(MessageObject message, Activity activity, Theme.ResourcesProvider resourcesProvider) {
File f = null;
if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
f = new File(message.messageOwner.attachPath);
@ -2869,13 +2901,13 @@ public class AndroidUtilities {
f = FileLoader.getPathToMessage(message.messageOwner);
}
String mimeType = message.type == 9 || message.type == 0 ? message.getMimeType() : null;
return openForView(f, message.getFileName(), mimeType, activity);
return openForView(f, message.getFileName(), mimeType, activity, resourcesProvider);
}
public static boolean openForView(TLRPC.Document document, boolean forceCache, Activity activity) {
String fileName = FileLoader.getAttachFileName(document);
File f = FileLoader.getPathToAttach(document, true);
return openForView(f, fileName, document.mime_type, activity);
return openForView(f, fileName, document.mime_type, activity, null);
}
public static CharSequence replaceNewLines(CharSequence original) {
@ -3740,4 +3772,12 @@ public class AndroidUtilities {
view.setTag(null);
}
}
public static long getPrefIntOrLong(SharedPreferences preferences, String key, long defaultValue) {
try {
return preferences.getLong(key, defaultValue);
} catch (Exception e) {
return preferences.getInt(key, (int) defaultValue);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -19,13 +19,13 @@ public class BuildVars {
public static boolean USE_CLOUD_STRINGS = true;
public static boolean CHECK_UPDATES = true;
public static boolean NO_SCOPED_STORAGE = true/* || Build.VERSION.SDK_INT <= 28*/;
public static int BUILD_VERSION = 2406;
public static String BUILD_VERSION_STRING = "8.0.0";
public static int BUILD_VERSION = 2428;
public static String BUILD_VERSION_STRING = "8.0.1";
public static int APP_ID = 4;
public static String APP_HASH = "014b35b6184100b085b0d0572f9b5103";
public static String APPCENTER_HASH = "a5b5c4f5-51da-dedc-9918-d9766a22ca7c";
public static String APPCENTER_HASH_DEBUG = "f9726602-67c9-48d2-b5d0-4761f1c1a8f3";
//
// public static String APPCENTER_HASH = "a5b5c4f5-51da-dedc-9918-d9766a22ca7c";
//public static String APPCENTER_HASH_DEBUG = "f9726602-67c9-48d2-b5d0-4761f1c1a8f3";
// public static String APPCENTER_HASH_DEBUG = DEBUG_PRIVATE_VERSION ? "1cfd375f-093f-4614-abe2-14e21c0dcf5c" : "f9726602-67c9-48d2-b5d0-4761f1c1a8f3";
public static String SMS_HASH = isStandaloneApp() ? "w0lkcmTZkKh" : (DEBUG_VERSION ? "O2P2z+/jBpJ" : "oLeq9AcOZkT");
public static String PLAYSTORE_APP_URL = "https://play.google.com/store/apps/details?id=org.telegram.messenger";

View File

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

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

View File

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

View File

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

View File

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

View File

@ -16,28 +16,12 @@ public class DialogObject {
return dialog != null && (dialog.flags & 1) != 0;
}
public static long makeSecretDialogId(int chatId) {
return ((long) chatId) << 32;
}
public static long makeFolderDialogId(int folderId) {
return (((long) 2) << 32) | folderId;
return 0x2000000000000000L | (long) folderId;
}
public static boolean isFolderDialogId(long dialogId) {
int lowerId = (int) dialogId;
int highId = (int) (dialogId >> 32);
return lowerId != 0 && highId == 2;
}
public static boolean isPeerDialogId(long dialogId) {
int lowerId = (int) dialogId;
int highId = (int) (dialogId >> 32);
return lowerId != 0 && highId != 2 && highId != 1;
}
public static boolean isSecretDialogId(long dialogId) {
return ((int) dialogId) == 0;
return (dialogId & 0x2000000000000000L) != 0 && (dialogId & 0x8000000000000000L) == 0;
}
public static void initDialog(TLRPC.Dialog dialog) {
@ -90,4 +74,28 @@ public class DialogObject {
public static long getLastMessageOrDraftDate(TLRPC.Dialog dialog, TLRPC.DraftMessage draftMessage) {
return draftMessage != null && draftMessage.date >= dialog.last_message_date ? draftMessage.date : dialog.last_message_date;
}
public static boolean isChatDialog(long dialogId) {
return !isEncryptedDialog(dialogId) && !isFolderDialogId(dialogId) && dialogId < 0;
}
public static boolean isUserDialog(long dialogId) {
return !isEncryptedDialog(dialogId) && !isFolderDialogId(dialogId) && dialogId > 0;
}
public static boolean isEncryptedDialog(long dialogId) {
return (dialogId & 0x4000000000000000L) != 0 && (dialogId & 0x8000000000000000L) == 0;
}
public static long makeEncryptedDialogId(long chatId) {
return 0x4000000000000000L | (chatId & 0x00000000ffffffffL);
}
public static int getEncryptedChatId(long dialogId) {
return (int) (dialogId & 0x00000000ffffffffL);
}
public static int getFolderId(long dialogId) {
return (int) dialogId;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -56,7 +56,7 @@ public abstract class FourierTransform {
}
if (whichAverage == LINAVG) {
int avgWidth = (int) spectrum.length / averages.length;
int avgWidth = spectrum.length / averages.length;
for (int i = 0; i < averages.length; i++) {
float avg = 0;
int j;
@ -140,15 +140,6 @@ public abstract class FourierTransform {
whichAverage = LOGAVG;
}
/**
* Sets the window to use on the samples before taking the forward transform.
* If an invalid window is asked for, an error will be reported and the
* current window will not be changed.
*
* @param windowFunction
*/
/**
* Returns the length of the time domain signal expected by this transform.
*
@ -225,8 +216,7 @@ public abstract class FourierTransform {
if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1;
// all other cases
float fraction = freq / (float) sampleRate;
int i = Math.round(timeSize * fraction);
return i;
return Math.round(timeSize * fraction);
}
/**

View File

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

View File

@ -34,7 +34,7 @@ public class GoogleVoiceClientService extends SearchActionVerificationClientServ
if (!TextUtils.isEmpty(text)) {
String contactUri = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_URI");
String id = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID");
int uid = Integer.parseInt(id);
long uid = Long.parseLong(id);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(uid);
if (user == null) {
user = MessagesStorage.getInstance(currentAccount).getUserSync(uid);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -374,7 +374,7 @@ public class VideoEditedInfo {
}
public boolean needConvert() {
return mediaEntities != null || paintPath != null || filterState != null || cropState != null || !roundVideo || roundVideo && (startTime > 0 || endTime != -1 && endTime != estimatedDuration);
return mediaEntities != null || paintPath != null || filterState != null || cropState != null || !roundVideo || startTime > 0 || endTime != -1 && endTime != estimatedDuration;
}
public boolean canAutoPlaySourceVideo() {

View File

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

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

View File

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

View File

@ -264,8 +264,6 @@ public class CameraSession {
if (params.getMaxNumMeteringAreas() > 0) {
meteringAreaSupported = true;
}
}
}
} 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.os.Build;
import com.google.android.exoplayer2.util.Log;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.NotificationsController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.VideoEditedInfo;
import org.telegram.ui.Components.Bulletin;
import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.LaunchActivity;
import java.io.File;
import java.nio.ByteBuffer;
@ -70,6 +81,7 @@ public class MediaCodecVideoConvertor {
boolean isPhoto,
MediaController.CropState cropState) {
long time = System.currentTimeMillis();
boolean error = false;
boolean repeatWithIncreasedTimeout = false;
int videoTrackIndex = -5;
@ -784,6 +796,11 @@ public class MediaCodecVideoConvertor {
isPhoto, cropState);
}
long timeLeft = System.currentTimeMillis() - time;
if (BuildVars.LOGS_ENABLED) {
FileLog.d("compression completed time=" + timeLeft + " needCompress=" + needCompress + " w=" + resultWidth + " h=" + resultHeight + " bitrate=" + bitrate);
}
return error;
}

View File

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

View File

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

View File

@ -352,7 +352,7 @@ public class ConnectionsManager extends BaseController {
return connectionState;
}
public void setUserId(int id) {
public void setUserId(long id) {
native_setUserId(currentAccount, id);
}
@ -365,13 +365,14 @@ public class ConnectionsManager extends BaseController {
native_setPushConnectionEnabled(currentAccount, value);
}
public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, int timezoneOffset, int userId, boolean enablePushConnection) {
public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, int timezoneOffset, long userId, boolean enablePushConnection) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
String proxyAddress = preferences.getString("proxy_ip", "");
String proxyUsername = preferences.getString("proxy_user", "");
String proxyPassword = preferences.getString("proxy_pass", "");
String proxySecret = preferences.getString("proxy_secret", "");
int proxyPort = preferences.getInt("proxy_port", 1080);
if (preferences.getBoolean("proxy_enabled", false) && !TextUtils.isEmpty(proxyAddress)) {
native_setProxySettings(currentAccount, proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret);
}
@ -680,6 +681,7 @@ public class ConnectionsManager extends BaseController {
if (secret == null) {
secret = "";
}
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (enabled && !TextUtils.isEmpty(address)) {
native_setProxySettings(a, address, port, username, password, secret);
@ -711,8 +713,8 @@ public class ConnectionsManager extends BaseController {
public static native void native_bindRequestToGuid(int currentAccount, int requestToken, int guid);
public static native void native_applyDatacenterAddress(int currentAccount, int datacenterId, String ipAddress, int port);
public static native int native_getConnectionState(int currentAccount);
public static native void native_setUserId(int currentAccount, int id);
public static native void native_init(int currentAccount, int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, String installer, String packageId, int timezoneOffset, int userId, boolean enablePushConnection, boolean hasNetwork, int networkType);
public static native void native_setUserId(int currentAccount, long id);
public static native void native_init(int currentAccount, int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, String regId, String cFingerprint, String installer, String packageId, int timezoneOffset, long userId, boolean enablePushConnection, boolean hasNetwork, int networkType);
public static native void native_setProxySettings(int currentAccount, String address, int port, String username, String password, String secret);
public static native void native_setLangCode(int currentAccount, String langCode);
public static native void native_setRegId(int currentAccount, String regId);

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -17,17 +17,19 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.accessibility.AccessibilityManager;
import android.widget.FrameLayout;
import org.telegram.messenger.AccountInstance;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.DownloadController;
@ -65,6 +67,8 @@ public abstract class BaseFragment {
protected boolean hasOwnBackground = false;
protected boolean isPaused = true;
protected Dialog parentDialog;
protected boolean inTransitionAnimation = false;
protected boolean fragmentBeginToShow;
public BaseFragment() {
classGuid = ConnectionsManager.generateClassGuid();
@ -215,11 +219,11 @@ public abstract class BaseFragment {
protected ActionBar createActionBar(Context context) {
ActionBar actionBar = new ActionBar(context);
actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault));
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSelector), false);
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), true);
actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultIcon), false);
actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarActionModeDefaultIcon), true);
actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarDefault));
actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarDefaultSelector), false);
actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), true);
actionBar.setItemsColor(getThemedColor(Theme.key_actionBarDefaultIcon), false);
actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), true);
if (inPreviewMode || inBubbleMode) {
actionBar.setOccupyStatusBar(false);
}
@ -435,11 +439,14 @@ public abstract class BaseFragment {
}
protected void onTransitionAnimationStart(boolean isOpen, boolean backward) {
inTransitionAnimation = true;
if (isOpen) {
fragmentBeginToShow = true;
}
}
protected void onTransitionAnimationEnd(boolean isOpen, boolean backward) {
inTransitionAnimation = false;
}
protected void onBecomeFullyVisible() {
@ -671,7 +678,40 @@ public abstract class BaseFragment {
return actionBarLayout;
}
public int getThemedColor(String key) {
return Theme.getColor(key);
}
public Drawable getThemedDrawable(String key) {
return Theme.getThemeDrawable(key);
}
public int getNavigationBarColor() {
return Theme.getColor(Theme.key_windowBackgroundGray);
}
public void setNavigationBarColor(int color) {
Activity activity = getParentActivity();
if (activity != null) {
Window window = activity.getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && window != null && window.getNavigationBarColor() != color) {
window.setNavigationBarColor(color);
final float brightness = AndroidUtilities.computePerceivedBrightness(color);
AndroidUtilities.setLightNavigationBar(window, brightness >= 0.721f);
}
}
}
public boolean isBeginToShow() {
return fragmentBeginToShow;
}
private void setParentDialog(Dialog dialog) {
parentDialog = dialog;
}
public Theme.ResourcesProvider getResourceProvider() {
return null;
}
}

View File

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

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;
public class DarkAlertDialog extends AlertDialog {
public DarkAlertDialog(Context context, int progressStyle) {
super(context, progressStyle);
}
@Override
protected int getThemeColor(String key) {
protected int getThemedColor(String key) {
switch (key) {
case Theme.key_dialogBackground:
return 0xFF262626;
@ -17,7 +18,7 @@ public class DarkAlertDialog extends AlertDialog {
case Theme.key_dialogScrollGlow:
return 0xFFFFFFFF;
}
return super.getThemeColor(key);
return super.getThemedColor(key);
}
public static class Builder extends AlertDialog.Builder {

View File

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

View File

@ -19,6 +19,7 @@ import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextPaint;
import android.view.View;
@ -30,6 +31,7 @@ import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.ui.Components.AnimatedArrowDrawable;
import org.telegram.ui.Components.AudioPlayerAlert;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
@ -115,9 +117,11 @@ public class ThemeDescription {
private HashMap<String, Field> cachedFields;
private HashMap<String, Boolean> notFoundCachedFields;
public Theme.ResourcesProvider resourcesProvider;
public interface ThemeDescriptionDelegate {
void didSetColor();
default void onAnimationProgress(float progress) {}
}
public ThemeDescription(View view, int flags, Class[] classes, Paint[] paint, Drawable[] drawables, ThemeDescriptionDelegate themeDescriptionDelegate, String key, Object unused) {
@ -254,6 +258,8 @@ public class ThemeDescription {
}
} else if (drawablesToUpdate[a] instanceof AvatarDrawable) {
((AvatarDrawable) drawablesToUpdate[a]).setColor(color);
} else if (drawablesToUpdate[a] instanceof AnimatedArrowDrawable) {
((AnimatedArrowDrawable) drawablesToUpdate[a]).setColor(color);
} else {
drawablesToUpdate[a].setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
}
@ -734,6 +740,15 @@ public class ThemeDescription {
TextView textView = i == 0 ? ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getTextView() : ((AudioPlayerAlert.ClippingTextViewSwitcher) object).getNextTextView();
if (textView != null) {
textView.setTextColor(color);
CharSequence text = textView.getText();
if (text instanceof SpannedString) {
TypefaceSpan[] spans = ((SpannedString) text).getSpans(0, text.length(), TypefaceSpan.class);
if (spans != null && spans.length > 0) {
for (int spanIdx = 0; spanIdx < spans.length; spanIdx++) {
spans[spanIdx].setColor(color);
}
}
}
}
}
}
@ -765,7 +780,16 @@ public class ThemeDescription {
}
public int getSetColor() {
return Theme.getColor(currentKey);
Integer color = resourcesProvider != null ? resourcesProvider.getColor(currentKey) : null;
return color != null ? color : Theme.getColor(currentKey);
}
public void setAnimatedColor(int color) {
if (resourcesProvider != null) {
resourcesProvider.setAnimatedColor(getCurrentKey(), color);
} else {
Theme.setAnimatedColor(getCurrentKey(), color);
}
}
public void setDefaultColor() {

View File

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

View File

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

View File

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

View File

@ -184,9 +184,9 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
onlineContacts = new ArrayList<>(ContactsController.getInstance(currentAccount).contacts);
prevContactsCount = onlineContacts.size();
prevDialogsCount = messagesController.dialogs_dict.size();
int selfId = UserConfig.getInstance(currentAccount).clientUserId;
long selfId = UserConfig.getInstance(currentAccount).clientUserId;
for (int a = 0, N = onlineContacts.size(); a < N; a++) {
int userId = onlineContacts.get(a).user_id;
long userId = onlineContacts.get(a).user_id;
if (userId == selfId || messagesController.dialogs_dict.get(userId) != null) {
onlineContacts.remove(a);
a--;
@ -354,7 +354,7 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
View view;
switch (viewType) {
case 0:
DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount);
DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount, null);
dialogCell.setArchivedPullAnimation(pullForegroundDrawable);
dialogCell.setPreloader(preloader);
view = dialogCell;

View File

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

View File

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

View File

@ -63,13 +63,15 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
private boolean needEmptyView;
private Runnable updateRunnable;
private final Theme.ResourcesProvider resourcesProvider;
public LocationActivityAdapter(Context context, int type, long did, boolean emptyView) {
public LocationActivityAdapter(Context context, int type, long did, boolean emptyView, Theme.ResourcesProvider resourcesProvider) {
super();
mContext = context;
locationType = type;
dialogId = did;
needEmptyView = emptyView;
this.resourcesProvider = resourcesProvider;
}
public void setOverScrollHeight(int value) {
@ -119,7 +121,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
public void setLiveLocations(ArrayList<LocationActivity.LiveLocation> liveLocations) {
currentLiveLocations = new ArrayList<>(liveLocations);
int uid = UserConfig.getInstance(currentAccount).getClientUserId();
long uid = UserConfig.getInstance(currentAccount).getClientUserId();
for (int a = 0; a < currentLiveLocations.size(); a++) {
if (currentLiveLocations.get(a).id == uid || currentLiveLocations.get(a).object.out) {
currentLiveLocations.remove(a);
@ -261,31 +263,31 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
};
break;
case 1:
view = new SendLocationCell(mContext, false);
view = new SendLocationCell(mContext, false, resourcesProvider);
break;
case 2:
view = new HeaderCell(mContext);
view = new HeaderCell(mContext, resourcesProvider);
break;
case 3:
view = new LocationCell(mContext, false);
view = new LocationCell(mContext, false, resourcesProvider);
break;
case 4:
view = new LocationLoadingCell(mContext);
view = new LocationLoadingCell(mContext, resourcesProvider);
break;
case 5:
view = new LocationPoweredCell(mContext);
view = new LocationPoweredCell(mContext, resourcesProvider);
break;
case 6: {
SendLocationCell cell = new SendLocationCell(mContext, true);
SendLocationCell cell = new SendLocationCell(mContext, true, resourcesProvider);
cell.setDialogId(dialogId);
view = cell;
break;
}
case 7:
view = new SharingLiveLocationCell(mContext, true, locationType == LocationActivity.LOCATION_TYPE_GROUP || locationType == LocationActivity.LOCATION_TYPE_GROUP_VIEW ? 16 : 54);
view = new SharingLiveLocationCell(mContext, true, locationType == LocationActivity.LOCATION_TYPE_GROUP || locationType == LocationActivity.LOCATION_TYPE_GROUP_VIEW ? 16 : 54, resourcesProvider);
break;
case 8: {
LocationDirectionCell cell = new LocationDirectionCell(mContext);
LocationDirectionCell cell = new LocationDirectionCell(mContext, resourcesProvider);
cell.setOnButtonClick(v -> onDirectionClick());
view = cell;
break;
@ -293,7 +295,7 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
case 9: {
view = new ShadowSectionCell(mContext);
Drawable drawable = Theme.getThemedDrawable(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow);
CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable);
CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(getThemedColor(Theme.key_windowBackgroundGray)), drawable);
combinedDrawable.setFullsize(true);
view.setBackgroundDrawable(combinedDrawable);
break;
@ -478,4 +480,9 @@ public class LocationActivityAdapter extends BaseLocationAdapter implements Loca
}
return viewType == 1 || viewType == 3 || viewType == 7;
}
private int getThemedColor(String key) {
Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
}
}

View File

@ -33,7 +33,7 @@ public class LocationActivitySearchAdapter extends BaseLocationAdapter {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new RecyclerListView.Holder(new LocationCell(mContext, false));
return new RecyclerListView.Holder(new LocationCell(mContext, false, null));
}
@Override

View File

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

View File

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

View File

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

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