merge official 9.1.6

This commit is contained in:
luvletter2333 2022-12-02 16:57:16 +08:00
commit b95fa5971d
No known key found for this signature in database
GPG Key ID: A26A8880836E1978
142 changed files with 5740 additions and 1782 deletions

View File

@ -1198,11 +1198,11 @@ void ConnectionsManager::processServerResponse(TLObject *message, int64_t messag
bool ignoreResult = false;
if (hasResult) {
TLObject *object = response->result.get();
if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received rpc_result with %s", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name());
if (LOGS_ENABLED) DEBUG_D("message_id %lld connection(%p, account%u, dc%u, type %d) received rpc_result with %s", messageId, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name());
}
RpcError *error = hasResult ? dynamic_cast<RpcError *>(response->result.get()) : nullptr;
if (error != nullptr) {
if (LOGS_ENABLED) DEBUG_E("connection(%p, account%u, dc%u, type %d) rpc error %d: %s", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), error->error_code, error->error_message.c_str());
if (LOGS_ENABLED) DEBUG_E("message_id %lld connection(%p, account%u, dc%u, type %d) rpc error %d: %s", messageId, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), error->error_code, error->error_message.c_str());
if (error->error_code == 303) {
uint32_t migrateToDatacenterId = DEFAULT_DATACENTER_ID;

View File

@ -465,14 +465,15 @@
<service android:name=".KeepAliveJob"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE"/>
<service android:name=".BringAppForegroundService" android:enabled="true"/>
<service android:name=".NotificationsService" android:enabled="true"/>
<service android:name=".BringAppForegroundService" android:enabled="true" android:exported="true"/>
<service android:name=".NotificationsService" android:enabled="true" android:exported="true"/>
<service android:name=".NotificationRepeat" android:exported="false"/>
<service android:name=".VideoEncodingService" android:enabled="true"/>
<service android:name=".ImportingService" android:enabled="true"/>
<service android:name=".VideoEncodingService" android:enabled="true" android:exported="true"/>
<service android:name=".ImportingService" android:enabled="true" android:exported="true"/>
<service android:name=".LocationSharingService"
android:foregroundServiceType="location"
android:enabled="true"/>
android:enabled="true"
android:exported="true"/>
<service android:name=".voip.VoIPService" android:enabled="true" android:foregroundServiceType="mediaProjection|camera|microphone|mediaPlayback"/>
<service android:name=".MusicPlayerService" android:exported="true" android:enabled="true" android:foregroundServiceType="mediaPlayback"/>
<service android:name=".MusicBrowserService" android:exported="true">
@ -497,7 +498,7 @@
</intent-filter>
</service>
<receiver android:name=".MusicPlayerReceiver" android:exported="true" >
<receiver android:name=".MusicPlayerReceiver" android:exported="false">
<intent-filter>
<action android:name="org.telegram.android.musicplayer.close" />
<action android:name="org.telegram.android.musicplayer.pause" />
@ -514,7 +515,7 @@
</intent-filter>
</receiver>
<receiver android:name=".AppStartReceiver" android:enabled="true" android:exported="true">
<receiver android:name=".AppStartReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="org.telegram.start" />
<action android:name="android.intent.action.BOOT_COMPLETED" />

View File

@ -127,6 +127,7 @@ listSelector=771751936
chat_outPreviewInstantText=-1
chat_inMenuSelected=-1517440301
avatar_backgroundOrange=-869276
avatar_background2Orange=-1734333
avatar_actionBarSelectorGreen=-12758164
chat_outLocationIcon=-1
chat_inLoaderSelected=-11297295
@ -155,6 +156,7 @@ chat_messageTextOut=-328966
chat_inInstant=-8796932
groupcreate_cursor=-10177041
avatar_backgroundSaved=-11558424
avatar_background2Saved=-15038233
returnToCallBackground=-10639897
checkboxSquareUnchecked=-11245959
dialogCheckboxSquareDisabled=-12040120
@ -201,6 +203,7 @@ calls_callReceivedGreenIcon=-12001930
chats_pinnedOverlay=201326591
windowBackgroundWhiteInputField=-11513776
avatar_backgroundRed=-2326437
avatar_background2Red=-2863816
statisticChartLine_green=-12729793
chat_emojiPanelIconSelector=-10177041
chat_emojiPanelBadgeBackground=-11291403

View File

@ -350,8 +350,8 @@ public class ApplicationLoader extends Application {
} else AndroidUtilities.runOnUIThread(() -> {
applicationContext.stopService(new Intent(applicationContext, NotificationsService.class));
PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), PendingIntent.FLAG_IMMUTABLE);
AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), PendingIntent.FLAG_MUTABLE);
AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pintent);
if (pendingIntent != null) {
alarm.cancel(pendingIntent);

View File

@ -110,7 +110,7 @@ public class ChatsWidgetProvider extends AppWidgetProvider {
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, contentIntent);
appWidgetManager.updateAppWidget(appWidgetId, rv);

View File

@ -23,6 +23,8 @@ import android.widget.RemoteViewsService;
import androidx.collection.LongSparseArray;
import com.google.android.exoplayer2.util.Log;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AvatarDrawable;
@ -350,6 +352,8 @@ class ChatsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.shortcut_widget_item, fillInIntent);
Log.d("kek", "kek " + name);
rv.setViewVisibility(R.id.shortcut_widget_item_divider, position == getCount() ? View.GONE : View.VISIBLE);
return rv;

View File

@ -111,7 +111,7 @@ public class ContactsWidgetProvider extends AppWidgetProvider {
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, contentIntent);

View File

@ -20,6 +20,8 @@ import android.widget.RemoteViewsService;
import androidx.collection.LongSparseArray;
import com.google.android.exoplayer2.util.Log;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AvatarDrawable;
@ -201,6 +203,8 @@ class ContactsRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactor
}
extras.putInt("currentAccount", accountInstance.getCurrentAccount());
Log.d("kek", "kek " + name);
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(a == 0 ? R.id.contacts_widget_item1 : R.id.contacts_widget_item2, fillInIntent);

View File

@ -18,6 +18,7 @@ public class DispatchQueuePoolBackground {
private int totalTasksCount;
private boolean cleanupScheduled;
public static final String THREAD_PREFIX = "DispatchQueuePoolThreadSafety_";
static ArrayList<Runnable> updateTaskCollection;
private static DispatchQueuePoolBackground backgroundQueue;
@ -62,7 +63,7 @@ public class DispatchQueuePoolBackground {
if (!busyQueues.isEmpty() && (totalTasksCount / 2 <= busyQueues.size() || queues.isEmpty() && createdCount >= maxCount)) {
queue = busyQueues.remove(0);
} else if (queues.isEmpty()) {
queue = new DispatchQueue("DispatchQueuePoolThreadSafety" + guid + "_" + Utilities.random.nextInt());
queue = new DispatchQueue(THREAD_PREFIX + guid + "_" + Utilities.random.nextInt());
queue.setPriority(Thread.MAX_PRIORITY);
createdCount++;
} else {
@ -104,6 +105,10 @@ public class DispatchQueuePoolBackground {
@UiThread
public static void execute(Runnable runnable) {
execute(runnable, false);
}
@UiThread
public static void execute(Runnable runnable, boolean now) {
if (BuildVars.DEBUG_PRIVATE_VERSION && Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("wrong thread");
}
@ -113,10 +118,16 @@ public class DispatchQueuePoolBackground {
} else {
updateTaskCollection = new ArrayList<>(100);
}
AndroidUtilities.runOnUIThread(finishCollectUpdateRunnable);
if (!now) {
AndroidUtilities.runOnUIThread(finishCollectUpdateRunnable);
}
}
updateTaskCollection.add(runnable);
if (now) {
AndroidUtilities.cancelRunOnUIThread(finishCollectUpdateRunnable);
finishCollectUpdateRunnable.run();
}
}
private static void finishCollectUpdateRunnables() {
@ -127,7 +138,7 @@ public class DispatchQueuePoolBackground {
ArrayList<Runnable> arrayList = updateTaskCollection;
updateTaskCollection = null;
if (backgroundQueue == null) {
backgroundQueue = new DispatchQueuePoolBackground(Math.max(1, Runtime.getRuntime().availableProcessors() - 2));
backgroundQueue = new DispatchQueuePoolBackground(Math.max(1, Runtime.getRuntime().availableProcessors()));
}
Utilities.globalQueue.postRunnable(() -> {
backgroundQueue.execute(arrayList);

View File

@ -42,14 +42,14 @@ public class FeedWidgetProvider extends AppWidgetProvider {
intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent2.setData(Uri.parse(intent2.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.feed_widget_layout);
rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent2);
rv.setRemoteAdapter(R.id.list_view, intent2);
rv.setEmptyView(R.id.list_view, R.id.empty_view);
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, contentIntent);

View File

@ -1285,114 +1285,127 @@ public class FileLoadOperation {
if (BuildVars.DEBUG_VERSION) {
FileLog.d("finished preloading file to " + cacheFileTemp + " loaded " + totalPreloadedBytes + " of " + totalBytesCount);
}
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
} else {
if (cacheIvTemp != null) {
cacheIvTemp.delete();
cacheIvTemp = null;
}
if (cacheFileParts != null) {
cacheFileParts.delete();
cacheFileParts = null;
}
if (cacheFilePreload != null) {
cacheFilePreload.delete();
cacheFilePreload = null;
}
if (cacheFileTemp != null) {
if (ungzip) {
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(cacheFileTemp));
FileLoader.copyFile(gzipInputStream, cacheFileGzipTemp, 1024 * 1024 * 2);
gzipInputStream.close();
cacheFileTemp.delete();
cacheFileTemp = cacheFileGzipTemp;
ungzip = false;
} catch (ZipException zipException) {
ungzip = false;
} catch (Throwable e) {
FileLog.e(e);
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to ungzip temp = " + cacheFileTemp + " to final = " + cacheFileFinal);
final File cacheIvTempFinal = cacheIvTemp;
final File cacheFilePartsFinal = cacheFileParts;
final File cacheFilePreloadFinal = cacheFilePreload;
final File cacheFileTempFinal = cacheFileTemp;
Utilities.globalQueue.postRunnable(() -> {
if (cacheIvTempFinal != null) {
cacheIvTempFinal.delete();
}
if (cacheFilePartsFinal != null) {
cacheFilePartsFinal.delete();
}
if (cacheFilePreloadFinal != null) {
cacheFilePreloadFinal.delete();
}
File cacheFileTempLocal = cacheFileTempFinal;
if (cacheFileTempLocal != null) {
if (ungzip) {
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(cacheFileTempLocal));
FileLoader.copyFile(gzipInputStream, cacheFileGzipTemp, 1024 * 1024 * 2);
gzipInputStream.close();
cacheFileTempLocal.delete();
cacheFileTempLocal = cacheFileGzipTemp;
ungzip = false;
} catch (ZipException zipException) {
ungzip = false;
} catch (Throwable e) {
FileLog.e(e);
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to ungzip temp = " + cacheFileTempFinal + " to final = " + cacheFileFinal);
}
}
}
}
if (!ungzip) {
boolean renameResult;
if (parentObject instanceof TLRPC.TL_theme) {
try {
renameResult = AndroidUtilities.copyFile(cacheFileTemp, cacheFileFinal);
} catch (Exception e) {
renameResult = false;
FileLog.e(e);
}
} else {
try {
if (pathSaveData != null) {
synchronized (lockObject) {
cacheFileFinal = new File(storePath, storeFileName);
int count = 1;
while (cacheFileFinal.exists()) {
int lastDotIndex = storeFileName.lastIndexOf('.');
String newFileName;
if (lastDotIndex > 0) {
newFileName = storeFileName.substring(0, lastDotIndex) + " (" + count + ")" + storeFileName.substring(lastDotIndex);
} else {
newFileName = storeFileName + " (" + count + ")";
if (!ungzip) {
boolean renameResult;
if (parentObject instanceof TLRPC.TL_theme) {
try {
renameResult = AndroidUtilities.copyFile(cacheFileTempLocal, cacheFileFinal);
} catch (Exception e) {
renameResult = false;
FileLog.e(e);
}
} else {
try {
if (pathSaveData != null) {
synchronized (lockObject) {
cacheFileFinal = new File(storePath, storeFileName);
int count = 1;
while (cacheFileFinal.exists()) {
int lastDotIndex = storeFileName.lastIndexOf('.');
String newFileName;
if (lastDotIndex > 0) {
newFileName = storeFileName.substring(0, lastDotIndex) + " (" + count + ")" + storeFileName.substring(lastDotIndex);
} else {
newFileName = storeFileName + " (" + count + ")";
}
cacheFileFinal = new File(storePath, newFileName);
count++;
}
cacheFileFinal = new File(storePath, newFileName);
count++;
}
}
renameResult = cacheFileTempLocal.renameTo(cacheFileFinal);
} catch (Exception e) {
renameResult = false;
FileLog.e(e);
}
renameResult = cacheFileTemp.renameTo(cacheFileFinal);
} catch (Exception e) {
renameResult = false;
FileLog.e(e);
}
}
if (!renameResult) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to rename temp = " + cacheFileTemp + " to final = " + cacheFileFinal + " retry = " + renameRetryCount);
if (!renameResult) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("unable to rename temp = " + cacheFileTempLocal + " to final = " + cacheFileFinal + " retry = " + renameRetryCount);
}
renameRetryCount++;
if (renameRetryCount < 3) {
state = stateDownloading;
Utilities.stageQueue.postRunnable(() -> {
try {
onFinishLoadingFile(increment);
} catch (Exception e) {
onFail(false, 0);
}
}, 200);
return;
}
cacheFileFinal = cacheFileTempLocal;
} else {
if (pathSaveData != null && cacheFileFinal.exists()) {
delegate.saveFilePath(pathSaveData, cacheFileFinal);
}
}
renameRetryCount++;
if (renameRetryCount < 3) {
state = stateDownloading;
Utilities.stageQueue.postRunnable(() -> {
try {
onFinishLoadingFile(increment);
} catch (Exception e) {
onFail(false, 0);
}
}, 200);
return;
}
cacheFileFinal = cacheFileTemp;
} else {
if (pathSaveData != null && cacheFileFinal.exists()) {
delegate.saveFilePath(pathSaveData, cacheFileFinal);
Utilities.stageQueue.postRunnable(() -> {
onFail(false, 0);
});
return;
}
}
Utilities.stageQueue.postRunnable(() -> {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("finished downloading file to " + cacheFileFinal + " time = " + (System.currentTimeMillis() - startTime));
}
if (increment) {
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_AUDIOS, 1);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_VIDEOS, 1);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_PHOTOS, 1);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_FILES, 1);
}
}
} else {
onFail(false, 0);
return;
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("finished downloading file to " + cacheFileFinal + " time = " + (System.currentTimeMillis() - startTime));
}
if (increment) {
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_AUDIOS, 1);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_VIDEOS, 1);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_PHOTOS, 1);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementReceivedItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_FILES, 1);
}
}
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
});
});
cacheIvTemp = null;
cacheFileParts = null;
cacheFilePreload = null;
}
delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal);
}
private void delayRequestInfo(RequestInfo requestInfo) {
@ -1502,7 +1515,7 @@ public class FileLoadOperation {
protected boolean processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) {
if (state != stateDownloading) {
if (BuildVars.DEBUG_VERSION && state == stateFinished) {
FileLog.e(new FileLog.IgnoreSentException("trying to write to finished file " + fileName + " offset " + requestInfo.offset + " " + totalBytesCount));
FileLog.e("trying to write to finished file " + fileName + " offset " + requestInfo.offset + " " + totalBytesCount);
}
return false;
}

View File

@ -94,6 +94,7 @@ public class FileLog {
try {
String metadata = "requestMsgId=" + requestMsgId + " requestingTime=" + (System.currentTimeMillis() - startRequestTimeInMillis) + " request_token=" + requestToken;
FileLog.getInstance().tlStreamWriter.write(getInstance().dateFormat.format(time) + " " + metadata);
FileLog.getInstance().tlStreamWriter.write("\n");
FileLog.getInstance().tlStreamWriter.write(req);
FileLog.getInstance().tlStreamWriter.write("\n");
FileLog.getInstance().tlStreamWriter.write(finalRes);
@ -127,6 +128,7 @@ public class FileLog {
String metadata = getInstance().dateFormat.format(time);// + " msgId=" + messageId;
FileLog.getInstance().tlStreamWriter.write(metadata);
FileLog.getInstance().tlStreamWriter.write("\n");
FileLog.getInstance().tlStreamWriter.write(messageStr);
FileLog.getInstance().tlStreamWriter.write("\n\n");
FileLog.getInstance().tlStreamWriter.flush();
@ -273,7 +275,7 @@ public class FileLog {
}
private static boolean needSent(Throwable e) {
if (e instanceof InterruptedException || e instanceof MediaCodecVideoConvertor.ConversionCanceledException || e instanceof IgnoreSentException) {
if (e instanceof InterruptedException || e instanceof MediaCodecVideoConvertor.ConversionCanceledException) {
return false;
}
return true;

View File

@ -140,7 +140,6 @@ public class FilePathDatabase {
CountDownLatch syncLatch = new CountDownLatch(1);
String[] res = new String[1];
long time = System.currentTimeMillis();
dispatchQueue.postRunnable(() -> {
if (database != null) {

View File

@ -70,7 +70,9 @@ public class FileRefController extends BaseController {
}
public static String getKeyForParentObject(Object parentObject) {
if (parentObject instanceof TLRPC.TL_availableReaction) {
if (parentObject instanceof TLRPC.TL_help_premiumPromo) {
return "premium_promo";
} else if (parentObject instanceof TLRPC.TL_availableReaction) {
return "available_reaction_" + ((TLRPC.TL_availableReaction) parentObject).reaction;
} else if (parentObject instanceof TLRPC.BotInfo) {
TLRPC.BotInfo botInfo = (TLRPC.BotInfo) parentObject;
@ -318,7 +320,18 @@ public class FileRefController extends BaseController {
}
private void requestReferenceFromServer(Object parentObject, String locationKey, String parentKey, Object[] args) {
if (parentObject instanceof TLRPC.TL_availableReaction) {
if (parentObject instanceof TLRPC.TL_help_premiumPromo) {
TLRPC.TL_help_getPremiumPromo req = new TLRPC.TL_help_getPremiumPromo();
getConnectionsManager().sendRequest(req, (response, error) -> {
int date = (int) (System.currentTimeMillis() / 1000);
if (response instanceof TLRPC.TL_help_premiumPromo) {
TLRPC.TL_help_premiumPromo r = (TLRPC.TL_help_premiumPromo) response;
getMediaDataController().processLoadedPremiumPromo(r, date, false);
}
onRequestComplete(locationKey, parentKey, response, true, false);
});
} else if (parentObject instanceof TLRPC.TL_availableReaction) {
TLRPC.TL_messages_getAvailableReactions req = new TLRPC.TL_messages_getAvailableReactions();
req.hash = 0;
getConnectionsManager().sendRequest(req, (response, error) -> onRequestComplete(locationKey, parentKey, response, true, false));
@ -675,7 +688,9 @@ public class FileRefController extends BaseController {
private boolean onRequestComplete(String locationKey, String parentKey, TLObject response, boolean cache, boolean fromCache) {
boolean found = false;
String cacheKey = parentKey;
if (response instanceof TLRPC.TL_account_wallPapers) {
if (response instanceof TLRPC.TL_help_premiumPromo) {
cacheKey = "premium_promo";
} else if (response instanceof TLRPC.TL_account_wallPapers) {
cacheKey = "wallpaper";
} else if (response instanceof TLRPC.TL_messages_savedGifs) {
cacheKey = "gif";
@ -755,6 +770,14 @@ public class FileRefController extends BaseController {
}
}
}
} else if (response instanceof TLRPC.TL_help_premiumPromo) {
TLRPC.TL_help_premiumPromo premiumPromo = (TLRPC.TL_help_premiumPromo) response;
for (TLRPC.Document document : premiumPromo.videos) {
result = getFileReference(document, requester.location, needReplacement, locationReplacement);
if (result != null) {
break;
}
}
} else if (response instanceof TLRPC.TL_messages_availableReactions) {
TLRPC.TL_messages_availableReactions availableReactions = (TLRPC.TL_messages_availableReactions) response;
getMediaDataController().processLoadedReactions(availableReactions.reactions, availableReactions.hash, (int) (System.currentTimeMillis() / 1000), false);

View File

@ -378,15 +378,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
if (userFull == null) {
MessagesController.getInstance(currentAccount).loadFullUser(user, currentGuid, false);
} else {
if (userFull.profile_photo != null && userFull.profile_photo.video_sizes != null && !userFull.profile_photo.video_sizes.isEmpty()) {
TLRPC.VideoSize videoSize = userFull.profile_photo.video_sizes.get(0);
for (int i = 0; i < userFull.profile_photo.video_sizes.size(); i++) {
if ("p".equals(userFull.profile_photo.video_sizes.get(i).type)) {
videoSize = userFull.profile_photo.video_sizes.get(i);
break;
if (userFull.profile_photo != null) {
TLRPC.Photo photo = userFull.profile_photo;
if (photo != null && photo.video_sizes != null && !photo.video_sizes.isEmpty()) {
TLRPC.VideoSize videoSize = photo.video_sizes.get(0);
for (int i = 0; i < photo.video_sizes.size(); i++) {
if ("p".equals(photo.video_sizes.get(i).type)) {
videoSize = photo.video_sizes.get(i);
break;
}
}
videoLocation = ImageLocation.getForPhoto(videoSize, photo);
}
videoLocation = ImageLocation.getForPhoto(videoSize, userFull.profile_photo);
}
}
}
@ -1474,7 +1477,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
if (time == 0) {
time = System.currentTimeMillis();
}
((SvgHelper.SvgDrawable) drawable).drawInternal(canvas, true, time, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH);
((SvgHelper.SvgDrawable) drawable).drawInternal(canvas, true, backgroundThreadDrawHolder.threadIndex, time, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH);
} else {
drawable.draw(canvas);
}
@ -1491,9 +1494,9 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private void drawBitmapDrawable(Canvas canvas, BitmapDrawable bitmapDrawable, BackgroundThreadDrawHolder backgroundThreadDrawHolder, int alpha) {
if (backgroundThreadDrawHolder != null) {
if (bitmapDrawable instanceof RLottieDrawable) {
((RLottieDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter);
((RLottieDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter, backgroundThreadDrawHolder.threadIndex);
} else if (bitmapDrawable instanceof AnimatedFileDrawable) {
((AnimatedFileDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter);
((AnimatedFileDrawable) bitmapDrawable).drawInBackground(canvas, backgroundThreadDrawHolder.imageX, backgroundThreadDrawHolder.imageY, backgroundThreadDrawHolder.imageW, backgroundThreadDrawHolder.imageH, alpha, backgroundThreadDrawHolder.colorFilter, backgroundThreadDrawHolder.threadIndex);
} else {
Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null) {
@ -1512,9 +1515,9 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
} else {
bitmapDrawable.setAlpha(alpha);
if (bitmapDrawable instanceof RLottieDrawable) {
((RLottieDrawable) bitmapDrawable).drawInternal(canvas, false, currentTime);
((RLottieDrawable) bitmapDrawable).drawInternal(canvas, false, currentTime, 0);
} else if (bitmapDrawable instanceof AnimatedFileDrawable) {
((AnimatedFileDrawable) bitmapDrawable).drawInternal(canvas, false, currentTime);
((AnimatedFileDrawable) bitmapDrawable).drawInternal(canvas, false, currentTime, 0);
} else {
bitmapDrawable.draw(canvas);
}
@ -2899,10 +2902,11 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return fileLoadingPriority;
}
public BackgroundThreadDrawHolder setDrawInBackgroundThread(BackgroundThreadDrawHolder holder) {
public BackgroundThreadDrawHolder setDrawInBackgroundThread(BackgroundThreadDrawHolder holder, int threadIndex) {
if (holder == null) {
holder = new BackgroundThreadDrawHolder();
}
holder.threadIndex = threadIndex;
holder.animation = getAnimation();
holder.lottieDrawable = getLottieAnimation();
for (int i = 0; i < 4; i++) {
@ -2935,6 +2939,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
public boolean animationNotReady;
public float overrideAlpha;
public long time;
public int threadIndex;
private AnimatedFileDrawable animation;
private RLottieDrawable lottieDrawable;
private int[] roundRadius = new int[4];

View File

@ -132,7 +132,7 @@ public class LocationSharingService extends Service implements NotificationCente
Intent intent2 = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
intent2.setAction("org.tmessages.openlocations");
intent2.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent2, PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent2, PendingIntent.FLAG_MUTABLE);
builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
builder.setWhen(System.currentTimeMillis());
@ -142,7 +142,7 @@ public class LocationSharingService extends Service implements NotificationCente
builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL);
builder.setContentTitle(LocaleController.getString("NekoX", R.string.NekoX));
Intent stopIntent = new Intent(ApplicationLoader.applicationContext, StopLiveLocationReceiver.class);
builder.addAction(0, LocaleController.getString("StopLiveLocation", R.string.StopLiveLocation), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE));
builder.addAction(0, LocaleController.getString("StopLiveLocation", R.string.StopLiveLocation), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, stopIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
updateNotification(false);

View File

@ -52,7 +52,6 @@ import android.provider.OpenableColumns;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.HapticFeedbackConstants;
import android.view.TextureView;
@ -5017,7 +5016,11 @@ public class MediaController implements AudioManager.OnAudioFocusChangeListener,
FileLog.e(e);
}
retriever.release();
try {
retriever.release();
} catch (Throwable throwable) {
FileLog.e(throwable);
}
return bitrate;
}

View File

@ -34,6 +34,7 @@ import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Pair;
import android.util.SparseArray;
import android.widget.Toast;
@ -68,7 +69,6 @@ import org.telegram.ui.Components.Bulletin;
import org.telegram.ui.Components.ChatThemeBottomSheet;
import org.telegram.ui.Components.RLottieDrawable;
import org.telegram.ui.Components.Reactions.ReactionsEffectOverlay;
import org.telegram.ui.Components.Reactions.ReactionsUtils;
import org.telegram.ui.Components.StickerSetBulletinLayout;
import org.telegram.ui.Components.StickersArchiveAlert;
import org.telegram.ui.Components.TextStyleSpan;
@ -523,7 +523,7 @@ public class MediaDataController extends BaseController {
}
}
private void processLoadedPremiumPromo(TLRPC.TL_help_premiumPromo premiumPromo, int date, boolean cache) {
public void processLoadedPremiumPromo(TLRPC.TL_help_premiumPromo premiumPromo, int date, boolean cache) {
this.premiumPromo = premiumPromo;
premiumPromoUpdateDate = date;
getMessagesController().putUsers(premiumPromo.users, cache);
@ -638,7 +638,7 @@ public class MediaDataController extends BaseController {
reactionsUpdateDate = date;
if (reactions != null) {
AndroidUtilities.runOnUIThread(() -> {
preloadReactions();
preloadDefaultReactions();
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.reactionsDidLoad);
});
}
@ -651,21 +651,23 @@ public class MediaDataController extends BaseController {
}
}
public void preloadReactions() {
public void preloadDefaultReactions() {
if (reactionsList == null || reactionsCacheGenerated) {
return;
}
reactionsCacheGenerated = true;
ArrayList<TLRPC.TL_availableReaction> arrayList = new ArrayList<>(reactionsList);
for (int i = 0; i < arrayList.size(); i++) {
TLRPC.TL_availableReaction reaction = arrayList.get(i);
preloadImage(ImageLocation.getForDocument(reaction.activate_animation), null);
preloadImage(ImageLocation.getForDocument(reaction.appear_animation), null);
}
for (int i = 0; i < arrayList.size(); i++) {
TLRPC.TL_availableReaction reaction = arrayList.get(i);
int size = ReactionsEffectOverlay.sizeForBigReaction();
preloadImage(ImageLocation.getForDocument(reaction.around_animation), ReactionsEffectOverlay.getFilterForAroundAnimation(), true);
preloadImage(ImageLocation.getForDocument(reaction.effect_animation), size + "_" + size);
preloadImage(ImageLocation.getForDocument(reaction.activate_animation), null);
preloadImage(ImageLocation.getForDocument(reaction.appear_animation), ReactionsUtils.APPEAR_ANIMATION_FILTER);
preloadImage(ImageLocation.getForDocument(reaction.center_icon), null);
preloadImage(ImageLocation.getForDocument(reaction.effect_animation), null);
}
}
@ -675,6 +677,9 @@ public class MediaDataController extends BaseController {
private void preloadImage(ImageLocation location, String filter, boolean log) {
ImageReceiver imageReceiver = new ImageReceiver();
imageReceiver.setAllowStartAnimation(false);
imageReceiver.setAllowStartLottieAnimation(false);
imageReceiver.setAllowDecodeSingleFrame(false);
imageReceiver.setDelegate((imageReceiver1, set, thumb, memCache) -> {
if (set) {
RLottieDrawable rLottieDrawable = imageReceiver.getLottieAnimation();
@ -6106,6 +6111,19 @@ public class MediaDataController extends BaseController {
return threads.get(threadId);
}
public Pair<Integer, TLRPC.DraftMessage> getOneThreadDraft(long dialogId) {
SparseArray<TLRPC.DraftMessage> threads = drafts.get(dialogId);
if (threads == null || threads.size() <= 0) {
return null;
}
for (int i = 0; i < threads.size(); ++i) {
if (threads.keyAt(i) != 0) {
return new Pair(threads.keyAt(i), threads.valueAt(i));
}
}
return null;
}
public TLRPC.Message getDraftMessage(long dialogId, int threadId) {
SparseArray<TLRPC.Message> threads = draftMessages.get(dialogId);
if (threads == null) {
@ -7282,7 +7300,7 @@ public class MediaDataController extends BaseController {
@Override
public void run() {
for (int i = 0; i < previewItems.size(); i++) {
if (previewItems.get(i).chatTheme != null) {
if (previewItems.get(i) != null && previewItems.get(i).chatTheme != null) {
previewItems.get(i).chatTheme.loadPreviewColors(0);
}
}

View File

@ -179,6 +179,8 @@ public class MessageObject {
public boolean sponsoredShowPeerPhoto;
public boolean sponsoredRecommended;
public TLRPC.TL_forumTopic replyToForumTopic; // used only for reply message in view all messages
public String botStartParam;
public boolean animateComments;
@ -2557,7 +2559,7 @@ public class MessageObject {
}
public boolean hasValidReplyMessageObject() {
return !(replyMessageObject == null || replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty || replyMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear);
return !(replyMessageObject == null || replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty || replyMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionHistoryClear || replyMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate);
}
public void generatePaymentSentMessageText(TLRPC.User fromUser) {
@ -3452,10 +3454,13 @@ public class MessageObject {
TLRPC.TL_messageActionTopicEdit editAction = (TLRPC.TL_messageActionTopicEdit) messageOwner.action;
String name = null;
TLObject object = null;
if (fromUser != null) {
name = ContactsController.formatName(fromUser.first_name, fromUser.last_name);
object = fromUser;
} else if (fromChat != null) {
name = fromChat.title;
object = fromChat;
}
if (name != null) {
name = name.trim();
@ -3465,10 +3470,10 @@ public class MessageObject {
if ((messageOwner.action.flags & 4) > 0) {
if (((TLRPC.TL_messageActionTopicEdit) messageOwner.action).closed) {
messageText = LocaleController.formatString("TopicClosed2", R.string.TopicClosed2, name);
messageText = replaceWithLink(LocaleController.getString("TopicClosed2", R.string.TopicClosed2), "%s", object);
messageTextShort = LocaleController.getString("TopicClosed", R.string.TopicClosed);
} else {
messageText = LocaleController.formatString("TopicRestarted2", R.string.TopicRestarted2, name);
messageText = replaceWithLink(LocaleController.getString("TopicRestarted2", R.string.TopicRestarted2), "%s", object);
messageTextShort = LocaleController.getString("TopicRestarted", R.string.TopicRestarted);
}
} else {
@ -4802,6 +4807,10 @@ public class MessageObject {
}
public static Spannable replaceAnimatedEmoji(CharSequence text, ArrayList<TLRPC.MessageEntity> entities, Paint.FontMetricsInt fontMetricsInt) {
return replaceAnimatedEmoji(text, entities, fontMetricsInt, false);
}
public static Spannable replaceAnimatedEmoji(CharSequence text, ArrayList<TLRPC.MessageEntity> entities, Paint.FontMetricsInt fontMetricsInt, boolean top) {
Spannable spannable = text instanceof Spannable ? (Spannable) text : new SpannableString(text);
if (entities == null) {
return spannable;
@ -4838,6 +4847,7 @@ public class MessageObject {
} else {
span = new AnimatedEmojiSpan(entity.document_id, fontMetricsInt);
}
span.top = top;
spannable.setSpan(span, messageEntity.offset, messageEntity.offset + messageEntity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
@ -5555,6 +5565,22 @@ public class MessageObject {
return false;
}
public static boolean peersEqual(TLRPC.Chat a, TLRPC.Peer b) {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (ChatObject.isChannel(a) && b instanceof TLRPC.TL_peerChannel) {
return a.id == b.channel_id;
}
if (!ChatObject.isChannel(a) && b instanceof TLRPC.TL_peerChat) {
return a.id == b.chat_id;
}
return false;
}
public long getFromChatId() {
return getFromChatId(messageOwner);
}

View File

@ -11,11 +11,13 @@ package org.telegram.messenger;
import static org.telegram.messenger.NotificationsController.TYPE_CHANNEL;
import static org.telegram.messenger.NotificationsController.TYPE_PRIVATE;
import android.Manifest;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
@ -29,6 +31,7 @@ import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import androidx.collection.LongSparseArray;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.util.Consumer;
@ -93,6 +96,7 @@ public class MessagesController extends BaseController implements NotificationCe
private ConcurrentHashMap<Integer, TLRPC.EncryptedChat> encryptedChats = new ConcurrentHashMap<>(10, 1.0f, 2);
private ConcurrentHashMap<Long, TLRPC.User> users = new ConcurrentHashMap<>(100, 1.0f, 2);
private ConcurrentHashMap<String, TLObject> objectsByUsernames = new ConcurrentHashMap<>(100, 1.0f, 2);
public static int stableIdPointer = 100;
private HashMap<Long, TLRPC.Chat> activeVoiceChatsMap = new HashMap<>();
@ -129,6 +133,7 @@ public class MessagesController extends BaseController implements NotificationCe
public LongSparseArray<SparseArray<Integer>> printingStringsTypes = new LongSparseArray<>();
public LongSparseArray<SparseArray<Boolean>>[] sendingTypings = new LongSparseArray[12];
public ConcurrentHashMap<Long, Integer> onlinePrivacy = new ConcurrentHashMap<>(20, 1.0f, 2);
private LongSparseIntArray pendingUnreadCounter = new LongSparseIntArray();
private int lastPrintingStringCount;
private boolean dialogsInTransaction;
@ -382,6 +387,7 @@ public class MessagesController extends BaseController implements NotificationCe
public int reactionsUserMaxPremium;
public int reactionsInChatMax;
public int forumUpgradeParticipantsMin;
public int topicsPinnedLimit;
public int uploadMaxFileParts;
public int uploadMaxFilePartsPremium;
@ -609,6 +615,13 @@ public class MessagesController extends BaseController implements NotificationCe
getMessagesStorage().updateRepliesMaxReadId(-did, topic.id, topic.top_message, 0, true);
}
}
getMessagesStorage().getStorageQueue().postRunnable(() -> {
getMessagesStorage().resetAllUnreadCounters(false);
AndroidUtilities.runOnUIThread(() -> {
getMessagesController().sortDialogs(null);
getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload, true);
});
});
});
});
}
@ -1193,6 +1206,7 @@ public class MessagesController extends BaseController implements NotificationCe
premiumLocked = mainPreferences.getBoolean("premiumLocked", false);
transcribeButtonPressed = mainPreferences.getInt("transcribeButtonPressed", 0);
forumUpgradeParticipantsMin = mainPreferences.getInt("forumUpgradeParticipantsMin", 200);
topicsPinnedLimit = mainPreferences.getInt("topicsPinnedLimit", 3);
// BuildVars.GOOGLE_AUTH_CLIENT_ID = mainPreferences.getString("googleAuthClientId", BuildVars.GOOGLE_AUTH_CLIENT_ID);
Set<String> currencySet = mainPreferences.getStringSet("directPaymentsCurrency", null);
@ -1411,6 +1425,7 @@ public class MessagesController extends BaseController implements NotificationCe
sendLoadPeersRequest(req3, requests, pinnedDialogs, pinnedRemoteDialogs, users, chats, filtersToSave, filtersToDelete, filtersOrder, filterDialogRemovals, filterUserRemovals, filtersUnreadCounterReset);
}
//no
TLRPC.TL_messages_getPeerDialogs req4 = null;
for (HashMap.Entry<Long, TLRPC.InputPeer> entry : dialogsToLoadMap.entrySet()) {
if (req4 == null) {
@ -2716,6 +2731,16 @@ public class MessagesController extends BaseController implements NotificationCe
}
break;
}
case "topics_pinned_limit": {
if (value.value instanceof TLRPC.TL_jsonNumber) {
TLRPC.TL_jsonNumber number = (TLRPC.TL_jsonNumber) value.value;
if (number.value != topicsPinnedLimit) {
topicsPinnedLimit = (int) number.value;
editor.putInt("topicsPinnedLimit", topicsPinnedLimit);
changed = true;
}
}
}
}
}
if (changed) {
@ -3458,7 +3483,7 @@ public class MessagesController extends BaseController implements NotificationCe
editor = emojiPreferences.edit();
editor.putLong("lastGifLoadTime", 0).putLong("lastStickersLoadTime", 0).putLong("lastStickersLoadTimeMask", 0).putLong("lastStickersLoadTimeFavs", 0).commit();
editor = mainPreferences.edit();
editor.remove("archivehint").remove("proximityhint").remove("archivehint_l").remove("gifhint").remove("reminderhint").remove("soundHint").remove("dcDomainName2").remove("webFileDatacenterId").remove("themehint").remove("showFiltersTooltip").commit();
editor.remove("archivehint").remove("proximityhint").remove("archivehint_l").remove("gifhint").remove("reminderhint").remove("soundHint").remove("dcDomainName2").remove("webFileDatacenterId").remove("themehint").remove("showFiltersTooltip").remove("transcribeButtonPressed").commit();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("shortcut_widget", Activity.MODE_PRIVATE);
SharedPreferences.Editor widgetEditor = null;
@ -4213,6 +4238,7 @@ public class MessagesController extends BaseController implements NotificationCe
if (did == 0 && (dialogs == null || dialogs.isEmpty())) {
return;
}
//probably
TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs();
if (dialogs != null) {
for (int a = 0; a < dialogs.size(); a++) {
@ -7526,6 +7552,7 @@ public class MessagesController extends BaseController implements NotificationCe
getConnectionsManager().bindRequestToGuid(reqId, classGuid);
} else {
if (loadDialog && (load_type == 3 || load_type == 2) && last_message_id == 0) {
//probably--
TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs();
TLRPC.InputPeer inputPeer = getInputPeer(dialogId);
TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer();
@ -8292,6 +8319,7 @@ public class MessagesController extends BaseController implements NotificationCe
FileLog.d("load unknown dialog " + dialogId);
}
//probably--
TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs();
TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer();
inputDialogPeer.peer = peer;
@ -9387,6 +9415,7 @@ public class MessagesController extends BaseController implements NotificationCe
if (BuildVars.DEBUG_PRIVATE_VERSION) {
FileLog.d("can't update dialog " + dialogId + " with new unread " + dialogsToUpdate.valueAt(a));
}
pendingUnreadCounter.put(dialogId, dialogsToUpdate.valueAt(a));
}
if (currentDialog != null) {
int prevCount = currentDialog.unread_count;
@ -11476,6 +11505,7 @@ public class MessagesController extends BaseController implements NotificationCe
gettingUnknownChannels.put(channel.id, true);
//no
TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs();
TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer();
inputDialogPeer.peer = inputPeer;
@ -12783,6 +12813,8 @@ public class MessagesController extends BaseController implements NotificationCe
return ((TLRPC.TL_updateReadChannelInbox) update).channel_id;
} else if (update instanceof TLRPC.TL_updateChannelPinnedTopic) {
return ((TLRPC.TL_updateChannelPinnedTopic) update).channel_id;
} else if (update instanceof TLRPC.TL_updateChannelPinnedTopics) {
return ((TLRPC.TL_updateChannelPinnedTopics) update).channel_id;
} else if (update instanceof TLRPC.TL_updateReadChannelDiscussionInbox) {
return ((TLRPC.TL_updateReadChannelDiscussionInbox) update).channel_id;
} else if (update instanceof TLRPC.TL_updateReadChannelDiscussionOutbox) {
@ -13411,8 +13443,8 @@ public class MessagesController extends BaseController implements NotificationCe
for (int c = 0, size3 = updates.size(); c < size3; c++) {
TLRPC.Update baseUpdate = updates.get(c);
if (BuildVars.LOGS_ENABLED) {
FileLog.d("process update " + baseUpdate);
if (BuildVars.LOGS_ENABLED && baseUpdate != null) {
FileLog.d("process update " + baseUpdate.getClass().getSimpleName());
}
if (baseUpdate instanceof TLRPC.TL_updateNewMessage || baseUpdate instanceof TLRPC.TL_updateNewChannelMessage || baseUpdate instanceof TLRPC.TL_updateNewScheduledMessage) {
TLRPC.Message message;
@ -14135,7 +14167,10 @@ public class MessagesController extends BaseController implements NotificationCe
stillUnreadMessagesCount.put(dialogId, update.still_unread_count);
dialogs_read_inbox_max.put(dialogId, Math.max(value, update.max_id));
FileLog.d("TL_updateReadChannelInbox " + dialogId + " new unread = " + update.still_unread_count + " max id = " + update.max_id + " from get diff " + fromGetDifference);
} else if (baseUpdate instanceof TLRPC.TL_updateChannelPinnedTopic) {
} else if (
baseUpdate instanceof TLRPC.TL_updateChannelPinnedTopic ||
baseUpdate instanceof TLRPC.TL_updateChannelPinnedTopics
) {
if (updatesOnMainThread == null) {
updatesOnMainThread = new ArrayList<>();
}
@ -15040,14 +15075,21 @@ public class MessagesController extends BaseController implements NotificationCe
} else if (baseUpdate instanceof TLRPC.TL_updateChannelPinnedTopic) {
TLRPC.TL_updateChannelPinnedTopic update = (TLRPC.TL_updateChannelPinnedTopic) baseUpdate;
ArrayList<TLRPC.TL_forumTopic> topics = getTopicsController().getTopics(update.channel_id);
if (topics != null) {
for (int i = 0; i < topics.size(); ++i) {
topics.get(i).pinned = update.topic_id == topics.get(i).id;
}
ArrayList<Integer> newOrder = getTopicsController().getCurrentPinnedOrder(update.channel_id);
newOrder.remove((Integer) update.topic_id);
if (update.pinned) {
newOrder.add(0, update.topic_id);
}
getTopicsController().applyPinnedOrder(update.channel_id, newOrder);
updateMask |= UPDATE_MASK_SELECT_DIALOG;
} else if (baseUpdate instanceof TLRPC.TL_updateChannelPinnedTopics) {
TLRPC.TL_updateChannelPinnedTopics update = (TLRPC.TL_updateChannelPinnedTopics) baseUpdate;
if ((update.flags & 1) > 0) {
getTopicsController().applyPinnedOrder(update.channel_id, update.order);
} else {
getTopicsController().reloadTopics(update.channel_id, false);
}
} else if (baseUpdate instanceof TLRPC.TL_updatePhoneCallSignalingData) {
TLRPC.TL_updatePhoneCallSignalingData data = (TLRPC.TL_updatePhoneCallSignalingData) baseUpdate;
VoIPService svc = VoIPService.getSharedInstance();
@ -15107,7 +15149,16 @@ public class MessagesController extends BaseController implements NotificationCe
}
}
TelephonyManager tm = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
if (svc != null || VoIPService.callIShouldHavePutIntoIntent != null || tm.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
boolean callStateIsIdle = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//TODO check
if (ActivityCompat.checkSelfPermission(ApplicationLoader.applicationContext, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
callStateIsIdle = tm.getCallState() == TelephonyManager.CALL_STATE_IDLE;
}
} else {
callStateIsIdle = tm.getCallState() == TelephonyManager.CALL_STATE_IDLE;
}
if (svc != null || VoIPService.callIShouldHavePutIntoIntent != null || !callStateIsIdle) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("Auto-declining call " + call.id + " because there's already active one");
}
@ -15772,6 +15823,7 @@ public class MessagesController extends BaseController implements NotificationCe
}
if (needReload) {
if (topicId == 0) {
//no
TLRPC.TL_messages_getPeerDialogs req = new TLRPC.TL_messages_getPeerDialogs();
TLRPC.TL_inputDialogPeer inputDialogPeer = new TLRPC.TL_inputDialogPeer();
inputDialogPeer.peer = getInputPeer(dialogId);
@ -16233,11 +16285,27 @@ public class MessagesController extends BaseController implements NotificationCe
if (BuildVars.LOGS_ENABLED) {
FileLog.d("not found dialog with id " + dialogId + " dictCount = " + dialogs_dict.size() + " allCount = " + allDialogs.size());
}
boolean filterDialogsChanged = false;
dialog = new TLRPC.TL_dialog();
dialog.id = dialogId;
int mid = dialog.top_message = lastMessage.getId();
dialog.last_message_date = lastMessage.messageOwner.date;
dialog.flags = ChatObject.isChannel(chat) ? 1 : 0;
if (pendingUnreadCounter.get(dialogId, 0) > 0) {
dialog.unread_count = pendingUnreadCounter.get(dialogId);
pendingUnreadCounter.delete(dialogId);
if (!isDialogMuted(dialogId, 0)) {
unreadUnmutedDialogs++;
}
for (int b = 0; b < selectedDialogFilter.length; b++) {
if (selectedDialogFilter[b] != null && (selectedDialogFilter[b].flags & DIALOG_FILTER_FLAG_EXCLUDE_READ) != 0) {
filterDialogsChanged = true;
break;
}
}
}
dialogs_dict.put(dialogId, dialog);
allDialogs.add(dialog);
ArrayList<MessageObject> arrayList = new ArrayList<MessageObject>();
@ -16256,6 +16324,10 @@ public class MessagesController extends BaseController implements NotificationCe
dialogMessage.put(dialogId, arrayList);
changed = true;
if (filterDialogsChanged) {
sortDialogs(null);
getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
}
TLRPC.Dialog dialogFinal = dialog;
getMessagesStorage().getDialogFolderId(dialogId, param -> {
if (param != -1) {

View File

@ -2391,10 +2391,14 @@ public class MessagesStorage extends BaseController {
SQLitePreparedStatement state = null;
try {
HashSet<Integer> existingTopics = new HashSet<>();
HashMap<Integer, Integer> pinnedValues = new HashMap<>();
for (int i = 0; i < topics.size(); i++) {
TLRPC.TL_forumTopic topic = topics.get(i);
SQLiteCursor cursor = database.queryFinalized("SELECT did FROM topics WHERE did = " + dialogId + " AND topic_id = " + topic.id);
SQLiteCursor cursor = database.queryFinalized("SELECT did, pinned FROM topics WHERE did = " + dialogId + " AND topic_id = " + topic.id);
boolean exist = cursor.next();
if (exist) {
pinnedValues.put(i, cursor.intValue(2));
}
cursor.dispose();
cursor = null;
if (exist) {
@ -2430,7 +2434,11 @@ public class MessagesStorage extends BaseController {
state.bindInteger(8, topic.unread_mentions_count);
state.bindInteger(9, topic.unread_reactions_count);
state.bindInteger(10, topic.read_outbox_max_id);
state.bindInteger(11, topic.pinned ? 1 : 0);
if (topic.isShort && pinnedValues.containsKey(i)) {
state.bindInteger(11, pinnedValues.get(i));
} else {
state.bindInteger(11, topic.pinned ? 1 + topic.pinnedOrder : 0);
}
state.step();
messageData.reuse();
@ -2495,8 +2503,9 @@ public class MessagesStorage extends BaseController {
}
if ((flags & TopicsController.TOPIC_FLAG_PIN) != 0) {
topicToUpdate.pinned = fromTopic.pinned;
topicToUpdate.pinnedOrder = fromTopic.pinnedOrder;
}
boolean pinned = topicToUpdate.pinned;
int pinnedOrder = topicToUpdate.pinned ? 1 + topicToUpdate.pinnedOrder : 0;
if ((flags & TopicsController.TOPIC_FLAG_CLOSE) != 0) {
topicToUpdate.closed = fromTopic.closed;
}
@ -2505,7 +2514,7 @@ public class MessagesStorage extends BaseController {
NativeByteBuffer data = new NativeByteBuffer(topicToUpdate.getObjectSize());
topicToUpdate.serializeToStream(data);
state.bindByteBuffer(1, data);
state.bindInteger(2, pinned ? 1 : 0);
state.bindInteger(2, pinnedOrder);
state.bindLong(3, dialogId);
state.bindInteger(4, topicToUpdate.id);
state.step();
@ -2530,7 +2539,7 @@ public class MessagesStorage extends BaseController {
ArrayList<TLRPC.TL_forumTopic> topics = null;
SQLiteCursor cursor = null;
try {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT top_message, data, topic_message, unread_count, max_read_id, unread_mentions, unread_reactions, read_outbox FROM topics WHERE did = %d ORDER BY pinned DESC", dialogId));
cursor = database.queryFinalized(String.format(Locale.US, "SELECT top_message, data, topic_message, unread_count, max_read_id, unread_mentions, unread_reactions, read_outbox, pinned FROM topics WHERE did = %d ORDER BY pinned ASC", dialogId));
SparseArray<ArrayList<TLRPC.TL_forumTopic>> topicsByTopMessageId = null;
HashSet<Integer> topMessageIds = null;
@ -2567,6 +2576,8 @@ public class MessagesStorage extends BaseController {
topic.unread_mentions_count = cursor.intValue(5);
topic.unread_reactions_count = cursor.intValue(6);
topic.read_outbox_max_id = cursor.intValue(7);
topic.pinnedOrder = cursor.intValue(8) - 1;
topic.pinned = topic.pinnedOrder >= 0;
}
data.reuse();
@ -2627,6 +2638,38 @@ public class MessagesStorage extends BaseController {
}
}
cursor2.dispose();
if (!topMessageIds.isEmpty()) {
cursor2 = database.queryFinalized("SELECT mid, data FROM messages_topics WHERE uid = " + dialogId + " AND mid IN (" + TextUtils.join(",", topMessageIds) + ")");
try {
while (cursor2.next()) {
int messageId = cursor2.intValue(0);
NativeByteBuffer data = cursor2.byteBufferValue(1);
if (data != null) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
if (message != null) {
message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId);
}
data.reuse();
topMessageIds.remove(messageId);
addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad, null);
ArrayList<TLRPC.TL_forumTopic> topicsList = topicsByTopMessageId.get(messageId);
if (topicsList != null) {
for (int i = 0; i < topicsList.size(); i++) {
topicsList.get(i).topMessage = message;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad, false);
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
ArrayList<TLRPC.User> users = new ArrayList<>();
if (!chatsToLoad.isEmpty()) {
@ -2645,35 +2688,6 @@ public class MessagesStorage extends BaseController {
}
});
cursor2.dispose();
if (!topMessageIds.isEmpty()) {
cursor2 = database.queryFinalized("SELECT mid, data FROM messages_topics WHERE uid = " + dialogId + " AND mid IN (" + TextUtils.join(",", topMessageIds) + ")");
try {
while (cursor2.next()) {
int messageId = cursor2.intValue(0);
NativeByteBuffer data = cursor2.byteBufferValue(1);
if (data != null) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
if (message != null) {
message.readAttachPath(data, UserConfig.getInstance(currentAccount).clientUserId);
}
data.reuse();
topMessageIds.remove(messageId);
ArrayList<TLRPC.TL_forumTopic> topicsList = topicsByTopMessageId.get(messageId);
if (topicsList != null) {
for (int i = 0; i < topicsList.size(); i++) {
topicsList.get(i).topMessage = message;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
loadReplyMessages(replyMessageOwners, dialogReplyMessagesIds, usersToLoad, chatsToLoad, false);
loadGroupedMessagesForTopics(dialogId, topics);
}
@ -10205,6 +10219,7 @@ public class MessagesStorage extends BaseController {
private int malformedCleanupCount = 0;
public void checkMalformed(Exception e) {
if (e != null && e.getMessage() != null && e.getMessage().contains("malformed") && malformedCleanupCount < 3) {
FileLog.e("detected database malformed error, cleaning up...");
malformedCleanupCount++;
cleanup(false);
}
@ -10253,6 +10268,7 @@ public class MessagesStorage extends BaseController {
}
} catch (Exception e) {
FileLog.e(e);
checkMalformed(e);
}
}
cursor.dispose();
@ -10785,31 +10801,34 @@ public class MessagesStorage extends BaseController {
SQLiteCursor cursor = null;
try {
long dialogId = -chatId;
state = database.executeFast("UPDATE messages_v2 SET replies_data = ? WHERE mid = ? AND uid = ?");
TLRPC.MessageReplies currentReplies = null;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT replies_data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, dialogId));
if (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
currentReplies = TLRPC.MessageReplies.TLdeserialize(data, data.readInt32(false), false);
if (!isForum(-chatId)) {
state = database.executeFast("UPDATE messages_v2 SET replies_data = ? WHERE mid = ? AND uid = ?");
TLRPC.MessageReplies currentReplies = null;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT replies_data FROM messages_v2 WHERE mid = %d AND uid = %d", mid, dialogId));
if (cursor.next()) {
NativeByteBuffer data = cursor.byteBufferValue(0);
if (data != null) {
currentReplies = TLRPC.MessageReplies.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
}
}
cursor.dispose();
cursor = null;
if (currentReplies != null) {
currentReplies.read_max_id = readMaxId;
state.requery();
NativeByteBuffer data = new NativeByteBuffer(currentReplies.getObjectSize());
currentReplies.serializeToStream(data);
state.bindByteBuffer(1, data);
state.bindInteger(2, mid);
state.bindLong(3, dialogId);
state.step();
data.reuse();
}
state.dispose();
state = null;
}
cursor.dispose();
cursor = null;
if (currentReplies != null) {
currentReplies.read_max_id = readMaxId;
state.requery();
NativeByteBuffer data = new NativeByteBuffer(currentReplies.getObjectSize());
currentReplies.serializeToStream(data);
state.bindByteBuffer(1, data);
state.bindInteger(2, mid);
state.bindLong(3, dialogId);
state.step();
data.reuse();
}
state.dispose();
state = null;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT max_read_id FROM topics WHERE did = %d AND topic_id = %d", -chatId, mid));
@ -10824,23 +10843,44 @@ public class MessagesStorage extends BaseController {
cursor = null;
database.executeFast(String.format(Locale.US, "UPDATE messages_topics SET read_state = read_state | 1 WHERE uid = %d AND topic_id = %d AND mid <= %d AND read_state IN(0,2) AND out = 0", -chatId, mid, readMaxId)).stepThis().dispose();
//mark mentions as read
database.executeFast(String.format(Locale.US, "UPDATE messages_topics SET read_state = read_state | 2 WHERE uid = %d AND topic_id = %d AND mid <= %d AND read_state IN(0,1) AND out = 0", -chatId, mid, readMaxId)).stepThis().dispose();
int unreadMentionsCount = -1;
if (unreadCount < 0) {
unreadCount = 0;
cursor = database.queryFinalized(String.format(Locale.US, "SELECT count(mid) FROM messages_topics WHERE uid = %d AND topic_id = %d AND mid > %d AND read_state IN(0,2) AND out = 0", -chatId, mid, readMaxId));
cursor = database.queryFinalized(String.format(Locale.US, "SELECT count(mid) FROM messages_topics WHERE uid = %d AND topic_id = %d AND mid > %d AND read_state IN(0,2) AND out = 0", -chatId, mid, readMaxId));
if (cursor.next()) {
unreadCount = cursor.intValue(0);
}
cursor.dispose();
cursor = null;
if (unreadCount == 0) {
unreadMentionsCount = 0;
} else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT count(mid) FROM messages_topics WHERE uid = %d AND topic_id = %d AND mid > %d AND read_state < 2 AND out = 0", -chatId, mid, readMaxId));
if (cursor.next()) {
unreadMentionsCount = cursor.intValue(0);
}
cursor.dispose();
cursor = null;
}
} else if (unreadCount == 0) {
unreadMentionsCount = 0;
}
if (updateTopic) {
database.executeFast(String.format(Locale.ENGLISH, "UPDATE topics SET max_read_id = %d, unread_count = %d WHERE did = %d AND topic_id = %d", readMaxId, unreadCount, -chatId, mid)).stepThis().dispose();
if (unreadMentionsCount >= 0) {
database.executeFast(String.format(Locale.ENGLISH, "UPDATE topics SET max_read_id = %d, unread_count = %d, unread_mentions = %d WHERE did = %d AND topic_id = %d", readMaxId, unreadCount, unreadMentionsCount, -chatId, mid)).stepThis().dispose();
} else {
database.executeFast(String.format(Locale.ENGLISH, "UPDATE topics SET max_read_id = %d, unread_count = %d WHERE did = %d AND topic_id = %d", readMaxId, unreadCount, -chatId, mid)).stepThis().dispose();
}
int finalUnreadCount = unreadCount;
int finalUnreadMentionsCount = unreadMentionsCount;
AndroidUtilities.runOnUIThread(() -> {
getMessagesController().getTopicsController().updateMaxReadId(chatId, mid, readMaxId, finalUnreadCount);
getMessagesController().getTopicsController().updateMaxReadId(chatId, mid, readMaxId, finalUnreadCount, finalUnreadMentionsCount);
});
resetForumBadgeIfNeed(-chatId);
@ -11934,7 +11974,7 @@ public class MessagesStorage extends BaseController {
topicUpdate.topicId = topicKey.topicId;
topicUpdate.reloadTopic = true;
topicUpdatesInUi.add(topicUpdate);
FileLog.d("unknown topic need reload" + topicKey.dialogId + " " + topicKey.topicId);
FileLog.d("unknown topic need reload " + topicKey.dialogId + " " + topicKey.topicId);
continue;
}
Integer newMessagesInteger = topicsNewUnreadMessages.get(topicKey);
@ -12123,7 +12163,6 @@ public class MessagesStorage extends BaseController {
private void createOrEditTopic(long dialogId, TLRPC.Message message) {
TLRPC.TL_forumTopic forumTopic = new TLRPC.TL_forumTopic();
forumTopic.topicStartMessage = message;
forumTopic.top_message = message.id;
forumTopic.topMessage = message;
@ -15030,6 +15069,7 @@ public class MessagesStorage extends BaseController {
encryptedChats.clear();
FileLog.e(e);
getMessagesController().processLoadedDialogs(dialogs, encryptedChats, folderId, 0, 100, 1, true, false, true);
checkMalformed(e);
} finally {
if (cursor != null) {
cursor.dispose();

View File

@ -97,7 +97,7 @@ public class MusicBrowserService extends MediaBrowserService implements Notifica
Context context = getApplicationContext();
Intent intent = new Intent(context, LaunchActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
mediaSession.setSessionActivity(pi);
Bundle extras = new Bundle();

View File

@ -173,7 +173,7 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
audioManager.registerMediaButtonEventReceiver(remoteComponentName);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(remoteComponentName);
PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, PendingIntent.FLAG_IMMUTABLE);
PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, PendingIntent.FLAG_MUTABLE);
remoteControlClient = new RemoteControlClient(mediaPendingIntent);
audioManager.registerRemoteControlClient(remoteControlClient);
}
@ -220,7 +220,7 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
intent.setAction("com.tmessages.openplayer");
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE);
Notification notification;
@ -250,9 +250,9 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
PendingIntent pendingPrev = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PREVIOUS).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
//PendingIntent pendingStop = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_CLOSE).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingStop = PendingIntent.getService(getApplicationContext(), 0, new Intent(this, getClass()).setAction(getPackageName() + ".STOP_PLAYER"), PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingPlaypause = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(isPlaying ? NOTIFY_PAUSE : NOTIFY_PLAY).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingNext = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingSeek = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_SEEK).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingPlaypause = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(isPlaying ? NOTIFY_PAUSE : NOTIFY_PLAY).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingNext = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingSeek = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_SEEK).setComponent(new ComponentName(this, MusicPlayerReceiver.class)), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder bldr = new Notification.Builder(this);
bldr.setSmallIcon(R.drawable.player)
@ -481,15 +481,15 @@ public class MusicPlayerService extends Service implements NotificationCenter.No
}
public void setListeners(RemoteViews view) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PREVIOUS), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.player_previous, pendingIntent);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_CLOSE), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_CLOSE), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.player_close, pendingIntent);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PAUSE), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PAUSE), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.player_pause, pendingIntent);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_NEXT), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.player_next, pendingIntent);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PLAY), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(NOTIFY_PLAY), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.player_play, pendingIntent);
}

View File

@ -130,6 +130,7 @@ public class NotificationCenter {
public static final int voiceTranscriptionUpdate = totalEvents++;
public static final int animatedEmojiDocumentLoaded = totalEvents++;
public static final int recentEmojiStatusesUpdate = totalEvents++;
public static final int updateSearchSettings = totalEvents++;
public static final int didGenerateFingerprintKeyPair = totalEvents++;

View File

@ -58,6 +58,8 @@ import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;
import com.google.android.exoplayer2.util.Log;
import org.telegram.messenger.support.LongSparseIntArray;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
@ -68,6 +70,7 @@ import org.telegram.ui.PopupNotificationActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -525,8 +528,13 @@ public class NotificationsController extends BaseController {
smartNotificationsDialogs.remove(dialogId);
}
if (!newCount.equals(currentCount)) {
total_unread_count -= currentCount;
total_unread_count += newCount;
if (getMessagesController().isForum(dialogId)) {
total_unread_count -= currentCount > 0 ? 1 : 0;
total_unread_count += newCount > 0 ? 1 : 0;
} else {
total_unread_count -= currentCount;
total_unread_count += newCount;
}
pushDialogs.put(dialogId, newCount);
}
if (newCount == 0) {
@ -617,8 +625,13 @@ public class NotificationsController extends BaseController {
smartNotificationsDialogs.remove(dialogId);
}
if (!newCount.equals(currentCount)) {
total_unread_count -= currentCount;
total_unread_count += newCount;
if (getMessagesController().isForum(dialogId)) {
total_unread_count -= currentCount > 0 ? 1 : 0;
total_unread_count += newCount > 0 ? 1 : 0;
} else {
total_unread_count -= currentCount;
total_unread_count += newCount;
}
pushDialogs.put(dialogId, newCount);
}
if (newCount == 0) {
@ -1026,10 +1039,15 @@ public class NotificationsController extends BaseController {
}
if (canAddValue) {
if (currentCount != null) {
total_unread_count -= currentCount;
if (getMessagesController().isForum(dialog_id)) {
total_unread_count -= currentCount != null && currentCount > 0 ? 1 : 0;
total_unread_count += newCount > 0 ? 1 : 0;
} else {
if (currentCount != null) {
total_unread_count -= currentCount;
}
total_unread_count += newCount;
}
total_unread_count += newCount;
pushDialogs.put(dialog_id, newCount);
}
if (old_unread_count != total_unread_count) {
@ -1110,7 +1128,11 @@ public class NotificationsController extends BaseController {
}
if (canAddValue || newCount == 0) {
if (currentCount != null) {
total_unread_count -= currentCount;
if (getMessagesController().isForum(dialogId)) {
total_unread_count -= currentCount > 0 ? 1 : 0;
} else {
total_unread_count -= currentCount;
}
}
}
if (newCount == 0) {
@ -1142,7 +1164,11 @@ public class NotificationsController extends BaseController {
}
}
} else if (canAddValue) {
total_unread_count += newCount;
if (getMessagesController().isForum(dialogId)) {
total_unread_count += newCount > 0 ? 1 : 0;
} else {
total_unread_count += newCount;
}
pushDialogs.put(dialogId, newCount);
}
}
@ -1268,7 +1294,11 @@ public class NotificationsController extends BaseController {
}
int count = dialogs.valueAt(a);
pushDialogs.put(dialog_id, count);
total_unread_count += count;
if (getMessagesController().isForum(dialog_id)) {
total_unread_count += count > 0 ? 1 : 0;
} else {
total_unread_count += count;
}
}
if (push != null) {
@ -1329,10 +1359,17 @@ public class NotificationsController extends BaseController {
Integer currentCount = pushDialogs.get(dialogId);
int newCount = currentCount != null ? currentCount + 1 : 1;
if (currentCount != null) {
total_unread_count -= currentCount;
if (getMessagesController().isForum(dialogId)) {
if (currentCount != null) {
total_unread_count -= currentCount > 0 ? 1 : 0;
}
total_unread_count += newCount > 0 ? 1 : 0;
} else {
if (currentCount != null) {
total_unread_count -= currentCount;
}
total_unread_count += newCount;
}
total_unread_count += newCount;
pushDialogs.put(dialogId, newCount);
}
}
@ -1372,8 +1409,8 @@ public class NotificationsController extends BaseController {
continue;
}
}
if (dialog != null && dialog.unread_count != 0) {
count += dialog.unread_count;
if (dialog != null) {
count += MessagesController.getInstance(a).getDialogUnreadCount(dialog);
}
}
} catch (Exception e) {
@ -1393,7 +1430,7 @@ public class NotificationsController extends BaseController {
continue;
}
}
if (dialog.unread_count != 0) {
if (MessagesController.getInstance(a).getDialogUnreadCount(dialog) != 0) {
count++;
}
}
@ -2669,7 +2706,7 @@ public class NotificationsController extends BaseController {
try {
Intent intent = new Intent(ApplicationLoader.applicationContext, NotificationRepeat.class);
intent.putExtra("currentAccount", currentAccount);
PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE);
SharedPreferences preferences = getAccountInstance().getNotificationsSettings();
int minutes = preferences.getInt("repeat_messages", 60);
if (minutes > 0 && personalCount > 0) {
@ -3052,7 +3089,7 @@ public class NotificationsController extends BaseController {
if (!NekoConfig.disableNotificationBubbles.Bool()) {
NotificationCompat.BubbleMetadata.Builder bubbleBuilder =
new NotificationCompat.BubbleMetadata.Builder(
PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE),
PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE),
icon);
bubbleBuilder.setSuppressNotification(openedDialogId == did);
bubbleBuilder.setAutoExpandBubble(false);
@ -3801,7 +3838,7 @@ public class NotificationsController extends BaseController {
}
}
intent.putExtra("currentAccount", currentAccount);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);
mBuilder.setContentTitle(name)
.setSmallIcon(R.drawable.notification)
@ -3825,7 +3862,7 @@ public class NotificationsController extends BaseController {
Intent dismissIntent = new Intent(ApplicationLoader.applicationContext, NotificationDismissReceiver.class);
dismissIntent.putExtra("messageDate", lastMessageObject.messageOwner.date);
dismissIntent.putExtra("currentAccount", currentAccount);
mBuilder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 1, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE));
mBuilder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 1, dismissIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
if (photoPath != null) {
BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
@ -3949,7 +3986,7 @@ public class NotificationsController extends BaseController {
callbackIntent.putExtra("data", button.data);
}
callbackIntent.putExtra("mid", lastMessageObject.getId());
mBuilder.addAction(0, button.text, PendingIntent.getBroadcast(ApplicationLoader.applicationContext, lastButtonId++, callbackIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE));
mBuilder.addAction(0, button.text, PendingIntent.getBroadcast(ApplicationLoader.applicationContext, lastButtonId++, callbackIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE));
hasCallback = true;
}
}
@ -3961,9 +3998,9 @@ public class NotificationsController extends BaseController {
Intent replyIntent = new Intent(ApplicationLoader.applicationContext, PopupReplyReceiver.class);
replyIntent.putExtra("currentAccount", currentAccount);
if (Build.VERSION.SDK_INT <= 19) {
mBuilder.addAction(R.drawable.ic_ab_reply2, LocaleController.getString("Reply", R.string.Reply), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT));
mBuilder.addAction(R.drawable.ic_ab_reply2, LocaleController.getString("Reply", R.string.Reply), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
} else {
mBuilder.addAction(R.drawable.ic_ab_reply, LocaleController.getString("Reply", R.string.Reply), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE));
mBuilder.addAction(R.drawable.ic_ab_reply, LocaleController.getString("Reply", R.string.Reply), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, replyIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE));
}
}
showExtraNotifications(mBuilder, detailText, dialog_id, topicId, chatName, vibrationPattern, ledColor, sound, configImportance, isDefault, isInApp, notifyDisabled, chatType);
@ -4266,7 +4303,7 @@ public class NotificationsController extends BaseController {
replyIntent.putExtra("max_id", maxId);
replyIntent.putExtra("topic_id", topicId);
replyIntent.putExtra("currentAccount", currentAccount);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, replyIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
RemoteInput remoteInputWear = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(LocaleController.getString("Reply", R.string.Reply)).build();
String replyToString;
if (DialogObject.isChatDialog(dialogId)) {
@ -4510,7 +4547,7 @@ public class NotificationsController extends BaseController {
intent.putExtra("topicId", topicId);
}
intent.putExtra("currentAccount", currentAccount);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
if (wearReplyAction != null) {
@ -4522,7 +4559,7 @@ public class NotificationsController extends BaseController {
msgHeardIntent.putExtra("dialog_id", dialogId);
msgHeardIntent.putExtra("max_id", maxId);
msgHeardIntent.putExtra("currentAccount", currentAccount);
PendingIntent readPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, msgHeardIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent readPendingIntent = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, msgHeardIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action readAction = new NotificationCompat.Action.Builder(R.drawable.baseline_done_all_24, LocaleController.getString("MarkAsRead", R.string.MarkAsRead), readPendingIntent)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
.setShowsUserInterface(false)
@ -4571,7 +4608,7 @@ public class NotificationsController extends BaseController {
dismissIntent.putExtra("messageDate", maxDate);
dismissIntent.putExtra("dialogId", dialogId);
dismissIntent.putExtra("currentAccount", currentAccount);
builder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE));
builder.setDeleteIntent(PendingIntent.getBroadcast(ApplicationLoader.applicationContext, internalId, dismissIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
if (useSummaryNotification) {
builder.setGroup(notificationGroup);
@ -4608,7 +4645,7 @@ public class NotificationsController extends BaseController {
callbackIntent.putExtra("data", button.data);
}
callbackIntent.putExtra("mid", rowsMid);
builder.addAction(0, button.text, PendingIntent.getBroadcast(ApplicationLoader.applicationContext, lastButtonId++, callbackIntent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.addAction(0, button.text, PendingIntent.getBroadcast(ApplicationLoader.applicationContext, lastButtonId++, callbackIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
}
}

View File

@ -3605,7 +3605,7 @@ public boolean retriedToSend;
newMsg.via_bot_name = "";
}
} else {
newMsg.via_bot_id = Utilities.parseInt(params.get("bot"));
newMsg.via_bot_id = Utilities.parseLong(params.get("bot"));
}
newMsg.flags |= TLRPC.MESSAGE_FLAG_HAS_BOT_ID;
}
@ -8053,7 +8053,7 @@ public boolean retriedToSend;
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
} catch (Throwable ex) {
// Ignore failures while cleaning up.
}
}

View File

@ -1222,7 +1222,7 @@ public class SharedConfig {
if (updateVersionString == null) {
updateVersionString = BuildVars.BUILD_VERSION_STRING;
}
if (pendingAppUpdateBuildVersion != updateVersion || pendingAppUpdate.version == null || updateVersionString.compareTo(pendingAppUpdate.version) >= 0) {
if (pendingAppUpdateBuildVersion != updateVersion || pendingAppUpdate.version == null || updateVersionString.compareTo(pendingAppUpdate.version) >= 0 || BuildVars.DEBUG_PRIVATE_VERSION) {
pendingAppUpdate = null;
AndroidUtilities.runOnUIThread(SharedConfig::saveConfig);
}

View File

@ -42,6 +42,7 @@ import android.os.Build;
import android.util.SparseArray;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.DrawingInBackgroundThreadDrawable;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
@ -108,10 +109,10 @@ public class SvgHelper {
protected int height;
private static int[] parentPosition = new int[2];
private Bitmap[] backgroundBitmap = new Bitmap[2];
private Canvas[] backgroundCanvas = new Canvas[2];
private LinearGradient[] placeholderGradient = new LinearGradient[2];
private Matrix[] placeholderMatrix = new Matrix[2];
private Bitmap[] backgroundBitmap = new Bitmap[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Canvas[] backgroundCanvas = new Canvas[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private LinearGradient[] placeholderGradient = new LinearGradient[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Matrix[] placeholderMatrix = new Matrix[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private static float totalTranslation;
private static float gradientWidth;
private static long lastUpdateTime;
@ -154,10 +155,10 @@ public class SvgHelper {
@Override
public void draw(Canvas canvas) {
drawInternal(canvas, false, System.currentTimeMillis(), getBounds().left, getBounds().top, getBounds().width(), getBounds().height());
drawInternal(canvas, false, 0, System.currentTimeMillis(), getBounds().left, getBounds().top, getBounds().width(), getBounds().height());
}
public void drawInternal(Canvas canvas, boolean drawInBackground, long time, float x, float y, float w, float h) {
public void drawInternal(Canvas canvas, boolean drawInBackground, int threadIndex, long time, float x, float y, float w, float h) {
if (currentColorKey != null) {
setupGradient(currentColorKey, currentResourcesProvider, colorAlpha, drawInBackground);
}
@ -205,7 +206,7 @@ public class SvgHelper {
offset = 0;
}
int index = drawInBackground ? 1 : 0;
int index = drawInBackground ? 1 + threadIndex : 0;
if (placeholderMatrix[index] != null) {
placeholderMatrix[index].reset();
if (drawInBackground) {
@ -365,6 +366,11 @@ public class SvgHelper {
currentColorKey = colorKey;
}
public void setColorKey(String colorKey, Theme.ResourcesProvider resourcesProvider) {
currentColorKey = colorKey;
currentResourcesProvider = resourcesProvider;
}
public void setColor(int color) {
overrideColor = color;
}

View File

@ -14,6 +14,8 @@ import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Components.Forum.ForumUtilities;
import java.util.ArrayList;
@ -56,12 +58,11 @@ public class TopicsController extends BaseController {
loadTopics(chatId, true, LOAD_TYPE_PRELOAD);
}
public void loadTopics(long chatId) {
loadTopics(chatId, false, LOAD_TYPE_LOAD_NEXT);
}
private void loadTopics(long chatId, boolean fromCache, int loadType) {
public void loadTopics(long chatId, boolean fromCache, int loadType) {
if (topicsIsLoading.get(chatId, 0) != 0) {
return;
}
@ -69,6 +70,8 @@ public class TopicsController extends BaseController {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
FileLog.d("load topics " + chatId + " fromCache=" + fromCache + " loadType=" + loadType);
}
topicsIsLoading.put(chatId, 1);
if (fromCache) {
getMessagesStorage().loadTopics(-chatId, topics -> {
AndroidUtilities.runOnUIThread(() -> {
@ -78,12 +81,12 @@ public class TopicsController extends BaseController {
topicsIsLoading.put(chatId, 0);
processTopics(chatId, topics, null, fromCache, loadType, -1);
sortTopics(chatId);
});
});
return;
}
topicsIsLoading.put(chatId, 1);
TLRPC.TL_channels_getForumTopics getForumTopics = new TLRPC.TL_channels_getForumTopics();
getForumTopics.channel = getMessagesController().getInputChannel(chatId);
if (loadType == LOAD_TYPE_PRELOAD) {
@ -108,19 +111,20 @@ public class TopicsController extends BaseController {
messagesMap.put(topics.messages.get(i).id, topics.messages.get(i));
}
AndroidUtilities.runOnUIThread(() -> {
getMessagesStorage().putUsersAndChats(((TLRPC.TL_messages_forumTopics) response).users, ((TLRPC.TL_messages_forumTopics) response).chats, true, false);
getMessagesController().putUsers(((TLRPC.TL_messages_forumTopics) response).users, false);
getMessagesController().putChats(((TLRPC.TL_messages_forumTopics) response).chats, false);
topicsIsLoading.put(chatId, 0);
processTopics(chatId, topics.topics, messagesMap, false, loadType, ((TLRPC.TL_messages_forumTopics) response).count);
getMessagesStorage().putMessages(topics.messages, false, true, false, 0, false, 0);
sortTopics(chatId);
getMessagesStorage().saveTopics(-chatId, topicsByChatId.get(chatId), true, true);
if (!topics.topics.isEmpty() && loadType == LOAD_TYPE_LOAD_NEXT) {
TLRPC.TL_forumTopic lastTopic = topics.topics.get(topics.topics.size() - 1);
TLRPC.Message lastTopicMessage = messagesMap.get(lastTopic.top_message);
saveLoadOffset(chatId, lastTopic.top_message, lastTopicMessage.date, lastTopic.id);
saveLoadOffset(chatId, lastTopic.top_message, lastTopicMessage == null ? 0 : lastTopicMessage.date, lastTopic.id);
} else if (getTopics(chatId) == null || getTopics(chatId).size() < topics.count) {
clearLoadingOffset(chatId);
loadTopics(chatId);
@ -144,58 +148,77 @@ public class TopicsController extends BaseController {
if (topics == null) {
topics = new ArrayList<>();
topicsByChatId.put(chatId, topics);
}
if (topicsMap == null) {
topicsMap = new LongSparseArray<>();
topicsMapByChatId.put(chatId, topicsMap);
}
boolean changed = false;
if (newTopics != null) {
for (int i = 0; i < newTopics.size(); i++) {
TLRPC.TL_forumTopic newTopic = newTopics.get(i);
if (newTopic instanceof TLRPC.TL_forumTopicDeleted) {
continue;
}
if (!topicsMap.containsKey(newTopic.id)) {
if (messagesMap != null) {
newTopic.topMessage = messagesMap.get(newTopic.top_message);
newTopic.topicStartMessage = messagesMap.get(newTopic.id);
}
if (newTopic.topMessage == null) {
if (newTopic.topMessage == null && !newTopic.isShort) {
if (topicsToReload == null) {
topicsToReload = new ArrayList<>();
}
topicsToReload.add(newTopic);
} else {
if (newTopic.topicStartMessage == null) {
newTopic.topicStartMessage = new TLRPC.TL_message();
newTopic.topicStartMessage.message = "";
newTopic.topicStartMessage.id = newTopic.id;
newTopic.topicStartMessage.peer_id = getMessagesController().getPeer(-chatId);
newTopic.topicStartMessage.action = new TLRPC.TL_messageActionTopicCreate();
newTopic.topicStartMessage.action.title = newTopic.title;
}
topics.add(newTopic);
topicsMap.put(newTopic.id, newTopic);
topicsByTopMsgId.put(messageHash(newTopic.top_message, chatId), newTopic);
changed = true;
}
if (newTopic.topicStartMessage == null) {
newTopic.topicStartMessage = new TLRPC.TL_message();
newTopic.topicStartMessage.message = "";
newTopic.topicStartMessage.id = newTopic.id;
newTopic.topicStartMessage.peer_id = getMessagesController().getPeer(-chatId);
newTopic.topicStartMessage.action = new TLRPC.TL_messageActionTopicCreate();
newTopic.topicStartMessage.action.title = newTopic.title;
}
topics.add(newTopic);
topicsMap.put(newTopic.id, newTopic);
topicsByTopMsgId.put(messageHash(newTopic.top_message, chatId), newTopic);
changed = true;
}
}
}
int pinnedTopics = 0;
for (int i = 0; i < topics.size(); ++i) {
TLRPC.TL_forumTopic topic = topics.get(i);
if (topic != null && topic.pinned) {
int newPinnedOrder = pinnedTopics++;
if (topic.pinnedOrder != newPinnedOrder) {
topic.pinnedOrder = newPinnedOrder;
changed = true;
}
}
}
if (topicsToReload != null && loadType != LOAD_TYPE_LOAD_UNKNOWN) {
reloadTopics(chatId, topicsToReload);
} else if (loadType == LOAD_TYPE_LOAD_NEXT && topics.size() >= totalCount && totalCount >= 0) {
endIsReached.put(chatId, 1);
getUserConfig().getPreferences().edit().putBoolean("topics_end_reached_" + chatId, true).apply();
}
if (changed) {
sortTopics(chatId);
}
if (topicsToReload != null) {
reloadTopics(chatId, topicsToReload);
} else if (loadType == LOAD_TYPE_LOAD_NEXT && topics.size() >= totalCount && totalCount >= 0) {
endIsReached.put(chatId, 1);
}
getNotificationCenter().postNotificationName(NotificationCenter.topicsDidLoaded, chatId, true);
if ((loadType == LOAD_TYPE_PRELOAD || (loadType == LOAD_TYPE_PRELOAD && !fromCache)) && fromCache && topicsByChatId.get(chatId).isEmpty()) {
loadTopics(chatId, false, LOAD_TYPE_PRELOAD);
AndroidUtilities.runOnUIThread(() -> {
loadTopics(chatId, false, LOAD_TYPE_PRELOAD);
});
}
}
@ -212,11 +235,11 @@ public class TopicsController extends BaseController {
sortTopics(chatId, true);
}
private void sortTopics(long chatId, boolean notify) {
public void sortTopics(long chatId, boolean notify) {
ArrayList<TLRPC.TL_forumTopic> topics = topicsByChatId.get(chatId);
if (topics != null) {
if (openedTopicsBuChatId.get(chatId, 0) > 0) {
Collections.sort(topics, Comparator.comparingInt(o -> o.pinned ? -1 : -o.topMessage.date));
Collections.sort(topics, Comparator.comparingInt(o -> o.topMessage == null ? Integer.MAX_VALUE : -(o.pinned ? Integer.MAX_VALUE - o.pinnedOrder : o.topMessage.date)));
}
if (notify) {
getNotificationCenter().postNotificationName(NotificationCenter.topicsDidLoaded, chatId, true);
@ -344,11 +367,14 @@ public class TopicsController extends BaseController {
}));
}
public void updateMaxReadId(long chatId, int topicId, int readMaxId, int unreadCount) {
public void updateMaxReadId(long chatId, int topicId, int readMaxId, int unreadCount, int mentionsUnread) {
TLRPC.TL_forumTopic topic = findTopic(chatId, topicId);
if (topic != null) {
topic.read_inbox_max_id = readMaxId;
topic.unread_count = unreadCount;
if (mentionsUnread >= 0) {
topic.unread_mentions_count = mentionsUnread;
}
sortTopics(chatId);
}
}
@ -510,33 +536,106 @@ public class TopicsController extends BaseController {
});
}
public void pinTopic(long chatId, int topicId, boolean pin) {
public ArrayList<Integer> getCurrentPinnedOrder(long chatId) {
ArrayList<TLRPC.TL_forumTopic> topics = getTopics(chatId);
ArrayList<Integer> newOrder = new ArrayList<>();
if (topics != null) {
for (int i = 0; i < topics.size(); ++i) {
TLRPC.TL_forumTopic topic = topics.get(i);
if (topic == null) {
continue;
}
if (topic.pinned) {
newOrder.add(topic.id);
}
}
}
return newOrder;
}
public void applyPinnedOrder(long chatId, ArrayList<Integer> order) {
applyPinnedOrder(chatId, order, true);
}
public void applyPinnedOrder(long chatId, ArrayList<Integer> order, boolean notify) {
if (order == null) {
return;
}
ArrayList<TLRPC.TL_forumTopic> topics = getTopics(chatId);
boolean updated = false;
if (topics != null) {
for (int i = 0; i < topics.size(); ++i) {
TLRPC.TL_forumTopic topic = topics.get(i);
if (topic == null) {
continue;
}
int newPinnedOrder = order.indexOf(topic.id);
boolean newPinned = newPinnedOrder >= 0;
if (topic.pinned != newPinned || newPinned && topic.pinnedOrder != newPinnedOrder) {
updated = true;
topic.pinned = newPinned;
topic.pinnedOrder = newPinnedOrder;
getMessagesStorage().updateTopicData(chatId, topic, TopicsController.TOPIC_FLAG_PIN);
}
}
} else {
updated = true;
}
if (notify && updated) {
AndroidUtilities.runOnUIThread(() -> {
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_SELECT_DIALOG);
});
}
}
public void pinTopic(long chatId, int topicId, boolean pin, BaseFragment fragment) {
TLRPC.TL_channels_updatePinnedForumTopic req = new TLRPC.TL_channels_updatePinnedForumTopic();
req.channel = getMessagesController().getInputChannel(chatId);
req.topic_id = topicId;
req.pinned = pin;
ArrayList<TLRPC.TL_forumTopic> topics = topicsByChatId.get(chatId);
if (topics != null) {
for (int i = 0; i < topics.size(); ++i) {
TLRPC.TL_forumTopic topic = topics.get(i);
if (topic != null && (topicId == topic.id && pin) != topic.pinned) {
topic.pinned = topicId == topic.id && pin;
// topic.flags = topic.pinned ? (topic.flags | 8) : (topic.flags &~ 8);
getMessagesStorage().updateTopicData(-chatId, topic, TOPIC_FLAG_PIN);
}
}
ArrayList<Integer> prevOrder = getCurrentPinnedOrder(chatId);
ArrayList<Integer> newOrder = new ArrayList<>(prevOrder);
newOrder.remove((Integer) topicId);
if (pin) {
newOrder.add(0, topicId);
}
sortTopics(chatId);
applyPinnedOrder(chatId, newOrder);
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> {
if (response instanceof TLRPC.Updates) {
// getMessagesController().processUpdates((TLRPC.Updates) response, false);
if (error != null) {
if ("PINNED_TOO_MUCH".equals(error.text)) {
if (fragment == null) {
return;
}
applyPinnedOrder(chatId, prevOrder);
fragment.showDialog(
new AlertDialog.Builder(fragment.getContext())
.setTitle(LocaleController.getString("LimitReached", R.string.LimitReached))
.setMessage(LocaleController.formatString("LimitReachedPinnedTopics", R.string.LimitReachedPinnedTopics, MessagesController.getInstance(currentAccount).topicsPinnedLimit))
.setPositiveButton(LocaleController.getString("OK", R.string.OK), null)
.create()
);
} else if ("PINNED_TOPIC_NOT_MODIFIED".equals(error.text)) {
reloadTopics(chatId, false);
}
}
});
}
public void reorderPinnedTopics(long chatId, ArrayList<Integer> topics) {
TLRPC.TL_channels_reorderPinnedForumTopics req = new TLRPC.TL_channels_reorderPinnedForumTopics();
req.channel = getMessagesController().getInputChannel(chatId);
if (topics != null) {
req.order.addAll(topics);
}
req.force = true;
applyPinnedOrder(chatId, topics, false);
ConnectionsManager.getInstance(currentAccount).sendRequest(req, null);
}
public void updateMentionsUnread(long dialogId, int topicId, int topicMentionsCount) {
AndroidUtilities.runOnUIThread(() -> {
TLRPC.TL_forumTopic topic = findTopic(-dialogId, topicId);
@ -573,14 +672,6 @@ public class TopicsController extends BaseController {
}
}
public TLRPC.Message getLastMessage(long id) {
ArrayList<TLRPC.TL_forumTopic> topics = topicsByChatId.get(id);
if (!topics.isEmpty()) {
return topics.get(0).topMessage;
}
return null;
}
LongSparseArray<TopicsLoadOffset> offsets = new LongSparseArray<>();
public TopicsLoadOffset getLoadOffset(long chatId) {
@ -713,7 +804,12 @@ public class TopicsController extends BaseController {
}
public void reloadTopics(long chatId) {
reloadTopics(chatId, true);
}
public void reloadTopics(long chatId, boolean fromCache) {
AndroidUtilities.runOnUIThread(() -> {
getUserConfig().getPreferences().edit().remove("topics_end_reached_" + chatId).apply();
topicsByChatId.remove(chatId);
topicsMapByChatId.remove(chatId);
endIsReached.delete(chatId);
@ -722,7 +818,11 @@ public class TopicsController extends BaseController {
TLRPC.Chat chat = getMessagesController().getChat(chatId);
if (chat != null && chat.forum) {
preloadTopics(chatId);
if (fromCache) {
preloadTopics(chatId);
} else {
loadTopics(chatId, false, LOAD_TYPE_PRELOAD);
}
}
sortTopics(chatId);
});
@ -745,13 +845,15 @@ public class TopicsController extends BaseController {
if (key.startsWith("topics_load_offset_topic_id_")) {
editor.remove(key);
}
if (key.startsWith("topics_end_reached_")) {
editor.remove(key);
}
}
editor.apply();
});
}
public void updateReadOutbox(HashMap<MessagesStorage.TopicKey, Integer> topicsReadOutbox) {
AndroidUtilities.runOnUIThread(() -> {
HashSet<Long> updatedChats = new HashSet<>();
for (MessagesStorage.TopicKey topicKey : topicsReadOutbox.keySet()) {
@ -760,7 +862,7 @@ public class TopicsController extends BaseController {
if (topic != null) {
topic.read_outbox_max_id = Math.max(topic.read_outbox_max_id, value);
updatedChats.add(-topicKey.dialogId);
if ( topic.read_outbox_max_id >= topic.topMessage.id) {
if (topic.topMessage != null && topic.read_outbox_max_id >= topic.topMessage.id) {
topic.topMessage.unread = false;
}
}

View File

@ -113,12 +113,13 @@ public class Utilities {
if (value == null) {
return 0;
}
if (BuildConfig.BUILD_HOST_IS_WINDOWS) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return Integer.valueOf(matcher.group());
}
} else {
// if (BuildConfig.BUILD_HOST_IS_WINDOWS) {
// Matcher matcher = pattern.matcher(value);
// if (matcher.find()) {
// return Integer.valueOf(matcher.group());
// }
// } else {
{
int val = 0;
try {
int start = -1, end;
@ -140,7 +141,7 @@ public class Utilities {
} catch (Exception ignore) {}
return val;
}
return 0;
// return 0;
}
private static int parseInt(final String s) {

View File

@ -180,7 +180,7 @@ public class Browser {
if (equals) {
return url.equals("telegra.ph") || url.equals("te.legra.ph") || url.equals("graph.org");
}
return url.matches("^(https" + (forceHttps ? "" : "?") + "://)?(te\\.?legra\\.ph|graph\\.org).*"); // telegra.ph, te.legra.ph, graph.org
return url.matches("^(https" + (forceHttps ? "" : "?") + "://)?(te\\.?legra\\.ph|graph\\.org)(/.*|$)"); // telegra.ph, te.legra.ph, graph.org
}
public static String extractUsername(String link) {
@ -209,9 +209,9 @@ public class Browser {
public static boolean urlMustNotHaveConfirmation(String url) {
return (
isTelegraphUrl(url, false, true) ||
url.matches("^(https://)?t\\.me/iv\\??.*") || // t.me/iv?
url.matches("^(https://)?telegram\\.org/(blog|tour)/?.*") || // telegram.org/blog, telegram.org/tour
url.matches("^(https://)?fragment\\.com/?.*") // fragment.com
url.matches("^(https://)?t\\.me/iv\\??(/.*|$)") || // t.me/iv?
url.matches("^(https://)?telegram\\.org/(blog|tour)(/.*|$)") || // telegram.org/blog, telegram.org/tour
url.matches("^(https://)?fragment\\.com(/.*|$)") // fragment.com
);
}
@ -348,7 +348,7 @@ public class Browser {
Intent share = new Intent(ApplicationLoader.applicationContext, ShareBroadcastReceiver.class);
share.setAction(Intent.ACTION_SEND);
PendingIntent copy = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, CustomTabsCopyReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent copy = PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, CustomTabsCopyReceiver.class), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(getSession());
builder.addMenuItem(LocaleController.getString("CopyLink", R.string.CopyLink), copy);
@ -365,7 +365,7 @@ public class Browser {
.build();
builder.setDefaultColorSchemeParams(params);
builder.setShowTitle(true);
builder.setActionButton(BitmapFactory.decodeResource(context.getResources(), R.drawable.msg_filled_shareout), LocaleController.getString("ShareFile", R.string.ShareFile), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, share, PendingIntent.FLAG_IMMUTABLE), true);
builder.setActionButton(BitmapFactory.decodeResource(context.getResources(), R.drawable.msg_filled_shareout), LocaleController.getString("ShareFile", R.string.ShareFile), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 0, share, PendingIntent.FLAG_MUTABLE ), true);
CustomTabsIntent intent = builder.build();
intent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.launchUrl(context, uri);

View File

@ -6,19 +6,24 @@ import android.os.Build;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.DispatchQueuePoolBackground;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Components.RLottieDrawable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
@ -37,6 +42,10 @@ public class BitmapsCache {
ArrayList<FrameOffset> frameOffsets = new ArrayList<>();
final boolean useSharedBuffers;
static ConcurrentHashMap<Thread, byte[]> sharedBuffers = new ConcurrentHashMap();
static volatile boolean cleanupScheduled;
byte[] bufferTmp;
private final static int N = Utilities.clamp(Runtime.getRuntime().availableProcessors() - 2, 8, 1);
@ -44,11 +53,29 @@ public class BitmapsCache {
private final Object mutex = new Object();
private int frameIndex;
boolean error;
volatile boolean fileExist;
int compressQuality;
final File file;
private int tryCount;
public AtomicBoolean cancelled = new AtomicBoolean(false);
private Runnable cleanupSharedBuffers = new Runnable() {
@Override
public void run() {
for (Thread thread : sharedBuffers.keySet()) {
if (!thread.isAlive()) {
sharedBuffers.remove(thread);
}
}
if (!sharedBuffers.isEmpty()) {
AndroidUtilities.runOnUIThread(cleanupSharedBuffers, 5000);
} else {
cleanupScheduled = false;
}
}
};
public BitmapsCache(File sourceFile, Cacheable source, CacheOptions options, int w, int h, boolean noLimit) {
this.source = source;
@ -62,6 +89,49 @@ public class BitmapsCache {
File fileTmo = new File(FileLoader.checkDirectory(FileLoader.MEDIA_DIR_CACHE), "acache");
file = new File(fileTmo, fileName + "_" + w + "_" + h + (noLimit ? "_nolimit" : " ") + ".pcache2");
useSharedBuffers = w < AndroidUtilities.dp(60) && h < AndroidUtilities.dp(60);
// check cache created in file load queue only for high devices
if (SharedConfig.getDevicePerformanceClass() >= SharedConfig.PERFORMANCE_CLASS_HIGH) {
fileExist = file.exists();
if (fileExist) {
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "r");
cacheCreated = randomAccessFile.readBoolean();
if (cacheCreated && frameOffsets.isEmpty()) {
randomAccessFile.seek(randomAccessFile.readInt());
int count = randomAccessFile.readInt();
if (count > 10_000) {
count = 0;
}
fillFrames(randomAccessFile, count);
if (frameOffsets.size() == 0) {
cacheCreated = false;
fileExist = false;
file.delete();
} else {
cachedFile = randomAccessFile;
}
}
} catch (Throwable e) {
e.printStackTrace();
file.delete();
fileExist = false;
} finally {
try {
if (cachedFile != randomAccessFile && randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
fileExist = false;
cacheCreated = false;
}
}
volatile boolean checkCache;
@ -71,22 +141,53 @@ public class BitmapsCache {
RandomAccessFile cachedFile;
BitmapFactory.Options options;
private static int taskCounter;
private static CacheGeneratorSharedTools sharedTools;
public static void incrementTaskCounter() {
taskCounter++;
}
public static void decrementTaskCounter() {
taskCounter--;
if (taskCounter <= 0) {
taskCounter = 0;
RLottieDrawable.lottieCacheGenerateQueue.postRunnable(() -> {
if (sharedTools != null) {
sharedTools.release();
sharedTools = null;
}
});
}
}
public void createCache() {
try {
long time = System.currentTimeMillis();
if (file.exists()) {
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "r");
cacheCreated = randomAccessFile.readBoolean();
int framesCount = randomAccessFile.readInt();
if (framesCount == 0) {
cacheCreated = false;
}
if (cacheCreated) {
randomAccessFile.close();
return;
} else {
frameOffsets.clear();
randomAccessFile.seek(randomAccessFile.readInt());
int count = randomAccessFile.readInt();
if (count > 10_000) {
count = 0;
}
if (count > 0) {
fillFrames(randomAccessFile, count);
randomAccessFile.seek(0);
cachedFile = randomAccessFile;
fileExist = true;
return;
} else {
fileExist = false;
cacheCreated = false;
}
}
if (!cacheCreated) {
file.delete();
}
} catch (Throwable e) {
@ -96,7 +197,7 @@ public class BitmapsCache {
}
} finally {
if (randomAccessFile != null) {
if (cachedFile != randomAccessFile && randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (Throwable e2) {
@ -108,29 +209,26 @@ public class BitmapsCache {
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
Bitmap[] bitmap = new Bitmap[N];
ByteArrayOutputStream[] byteArrayOutputStream = new ByteArrayOutputStream[N];
CountDownLatch[] countDownLatch = new CountDownLatch[N];
for (int i = 0; i < N; i++) {
bitmap[i] = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
byteArrayOutputStream[i] = new ByteArrayOutputStream(w * h * 2);
if (sharedTools == null) {
sharedTools = new CacheGeneratorSharedTools();
}
sharedTools.allocate(h, w);
Bitmap[] bitmap = sharedTools.bitmap;
ByteArrayOutputStream[] byteArrayOutputStream = sharedTools.byteArrayOutputStream;
CountDownLatch[] countDownLatch = new CountDownLatch[N];
ArrayList<FrameOffset> frameOffsets = new ArrayList<>();
RandomAccessFile finalRandomAccessFile = randomAccessFile;
finalRandomAccessFile.writeBoolean(false);
finalRandomAccessFile.writeInt(0);
int index = 0;
long bitmapFrameTime = 0;
long compressTime = 0;
long writeFileTime = 0;
int framePosition = 0;
AtomicBoolean closed = new AtomicBoolean(false);
source.prepareForGenerateCache();
while (true) {
if (countDownLatch[index] != null) {
try {
@ -166,11 +264,9 @@ public class BitmapsCache {
return;
}
long time2 = System.currentTimeMillis();
if (source.getNextFrame(bitmap[index]) != 1) {
break;
}
bitmapFrameTime += System.currentTimeMillis() - time2;
countDownLatch[index] = new CountDownLatch(1);
@ -204,7 +300,8 @@ public class BitmapsCache {
e.printStackTrace();
try {
finalRandomAccessFile1.close();
} catch (Exception e2) {} finally {
} catch (Exception e2) {
} finally {
closed.set(true);
}
}
@ -226,35 +323,31 @@ public class BitmapsCache {
e.printStackTrace();
}
}
if (bitmap[i] != null) {
try {
bitmap[i].recycle();
} catch (Exception e) {
}
}
if (byteArrayOutputStream[i] != null) {
byteArrayOutputStream[i].buf = null;
}
}
int arrayOffset = (int) randomAccessFile.length();
Collections.sort(frameOffsets, Comparator.comparingInt(o -> o.index));
randomAccessFile.writeInt(frameOffsets.size());
byteArrayOutputStream[0].reset();
int count = frameOffsets.size();
byteArrayOutputStream[0].writeInt(count);
for (int i = 0; i < frameOffsets.size(); i++) {
randomAccessFile.writeInt(frameOffsets.get(i).frameOffset);
randomAccessFile.writeInt(frameOffsets.get(i).frameSize);
byteArrayOutputStream[0].writeInt(frameOffsets.get(i).frameOffset);
byteArrayOutputStream[0].writeInt(frameOffsets.get(i).frameSize);
}
randomAccessFile.write(byteArrayOutputStream[0].buf, 0, 4 + 4 * 2 * count);
byteArrayOutputStream[0].reset();
randomAccessFile.seek(0);
randomAccessFile.writeBoolean(true);
randomAccessFile.writeInt(arrayOffset);
closed.set(true);
randomAccessFile.close();
if (BuildVars.DEBUG_VERSION) {
FileLog.d("generate cache for time = " + (System.currentTimeMillis() - time) + " drawFrameTime = " + bitmapFrameTime + " comressQuality = " + compressQuality + " fileSize = " + AndroidUtilities.formatFileSize(file.length()) + " " + fileName);
}
this.frameOffsets.clear();
this.frameOffsets.addAll(frameOffsets);
cachedFile = new RandomAccessFile(file, "r");
cacheCreated = true;
fileExist = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
@ -264,6 +357,21 @@ public class BitmapsCache {
}
}
private void fillFrames(RandomAccessFile randomAccessFile, int count) throws Throwable {
if (count == 0) {
return;
}
byte[] bytes = new byte[4 * 2 * count];
randomAccessFile.read(bytes);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
for (int i = 0; i < count; i++) {
FrameOffset frameOffset = new FrameOffset(i);
frameOffset.frameOffset = byteBuffer.getInt();
frameOffset.frameSize = byteBuffer.getInt();
frameOffsets.add(frameOffset);
}
}
public void cancelCreate() {
// cancelled.set(true);
}
@ -290,6 +398,7 @@ public class BitmapsCache {
synchronized (mutex) {
randomAccessFile = new RandomAccessFile(file, "r");
cacheCreated = randomAccessFile.readBoolean();
randomAccessFile.seek(randomAccessFile.readInt());
framesCount = randomAccessFile.readInt();
if (framesCount <= 0) {
cacheCreated = false;
@ -317,49 +426,46 @@ public class BitmapsCache {
RandomAccessFile randomAccessFile = null;
try {
FrameOffset selectedFrame;
synchronized (mutex) {
if (!cacheCreated || cachedFile == null) {
randomAccessFile = new RandomAccessFile(file, "r");
cacheCreated = randomAccessFile.readBoolean();
if (cacheCreated && frameOffsets.isEmpty()) {
randomAccessFile.seek(randomAccessFile.readInt());
int count = randomAccessFile.readInt();
for (int i = 0; i < count; i++) {
FrameOffset frameOffset = new FrameOffset(i);
frameOffset.frameOffset = randomAccessFile.readInt();
frameOffset.frameSize = randomAccessFile.readInt();
frameOffsets.add(frameOffset);
}
}
if (!cacheCreated) {
randomAccessFile.close();
randomAccessFile = null;
source.getFirstFrame(bitmap);
return FRAME_RESULT_OK;
} else if (frameOffsets.isEmpty()) {
randomAccessFile.close();
randomAccessFile = null;
return FRAME_RESULT_NO_FRAME;
}
} else {
randomAccessFile = cachedFile;
}
index = Utilities.clamp(index, frameOffsets.size() - 1, 0);
selectedFrame = frameOffsets.get(index);
randomAccessFile.seek(selectedFrame.frameOffset);
if (bufferTmp == null || bufferTmp.length < selectedFrame.frameSize) {
bufferTmp = new byte[(int) (selectedFrame.frameSize * 1.3f)];
}
randomAccessFile.readFully(bufferTmp, 0, selectedFrame.frameSize);
if (!recycled) {
cachedFile = randomAccessFile;
} else {
cachedFile = null;
randomAccessFile.close();
}
if (!cacheCreated && !fileExist) {
return FRAME_RESULT_NO_FRAME;
}
byte[] bufferTmp;
if (!cacheCreated || cachedFile == null) {
randomAccessFile = new RandomAccessFile(file, "r");
cacheCreated = randomAccessFile.readBoolean();
if (cacheCreated && frameOffsets.isEmpty()) {
randomAccessFile.seek(randomAccessFile.readInt());
int count = randomAccessFile.readInt();
fillFrames(randomAccessFile, count);
}
if (frameOffsets.size() == 0) {
cacheCreated = false;
}
if (!cacheCreated) {
randomAccessFile.close();
randomAccessFile = null;
return FRAME_RESULT_NO_FRAME;
}
} else {
randomAccessFile = cachedFile;
}
if (frameOffsets.size() == 0) {
return FRAME_RESULT_NO_FRAME;
}
index = Utilities.clamp(index, frameOffsets.size() - 1, 0);
selectedFrame = frameOffsets.get(index);
randomAccessFile.seek(selectedFrame.frameOffset);
bufferTmp = getBuffer(selectedFrame);
randomAccessFile.readFully(bufferTmp, 0, selectedFrame.frameSize);
if (!recycled) {
cachedFile = randomAccessFile;
} else {
cachedFile = null;
randomAccessFile.close();
}
if (options == null) {
options = new BitmapFactory.Options();
}
@ -370,9 +476,13 @@ public class BitmapsCache {
} catch (Throwable e) {
FileLog.e(e, false);
tryCount++;
if (tryCount > 10) {
error = true;
}
}
if (randomAccessFile != null) {
if (error && randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
@ -380,12 +490,36 @@ public class BitmapsCache {
}
}
// source.getFirstFrame(bitmap);
// source.getFirstFrame(bitmap);
return FRAME_RESULT_NO_FRAME;
}
private byte[] getBuffer(FrameOffset selectedFrame) {
boolean useSharedBuffers = this.useSharedBuffers && Thread.currentThread().getName().startsWith(DispatchQueuePoolBackground.THREAD_PREFIX);
byte[] bufferTmp;
if (useSharedBuffers) {
bufferTmp = sharedBuffers.get(Thread.currentThread());
} else {
bufferTmp = this.bufferTmp;
}
if (bufferTmp == null || bufferTmp.length < selectedFrame.frameSize) {
bufferTmp = new byte[(int) (selectedFrame.frameSize * 1.3f)];
if (useSharedBuffers) {
sharedBuffers.put(Thread.currentThread(), bufferTmp);
if (!cleanupScheduled) {
cleanupScheduled = true;
AndroidUtilities.runOnUIThread(cleanupSharedBuffers, 5000);
}
} else {
this.bufferTmp = bufferTmp;
}
}
return bufferTmp;
}
public boolean needGenCache() {
return !cacheCreated;
return !cacheCreated || !fileExist;
}
public void recycle() {
@ -416,7 +550,9 @@ public class BitmapsCache {
public interface Cacheable {
void prepareForGenerateCache();
int getNextFrame(Bitmap bitmap);
void releaseForGenerateCache();
Bitmap getFirstFrame(Bitmap bitmap);
@ -437,8 +573,9 @@ public class BitmapsCache {
}
private void ensureCapacity(int minCapacity) {
if (minCapacity - buf.length > 0)
if (minCapacity - buf.length > 0) {
grow(minCapacity);
}
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
@ -467,6 +604,15 @@ public class BitmapsCache {
count += 1;
}
public void writeInt(int value) {
ensureCapacity(count + 4);
buf[count] = (byte) (value >>> 24);
buf[count + 1] = (byte) (value >>> 16);
buf[count + 2] = (byte) (value >>> 8);
buf[count + 3] = (byte) (value);
count += 4;
}
public synchronized void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) - b.length > 0)) {
@ -484,6 +630,8 @@ public class BitmapsCache {
public synchronized void reset() {
count = 0;
}
}
public static class Metadata {
@ -494,4 +642,61 @@ public class BitmapsCache {
public int compressQuality = 100;
public boolean fallback = false;
}
private static class CacheGeneratorSharedTools {
ByteArrayOutputStream[] byteArrayOutputStream = new ByteArrayOutputStream[N];
private Bitmap[] bitmap = new Bitmap[N];
private int lastSize;
void allocate(int h, int w) {
int size = (w << 16) + h;
boolean recreateBitmaps = false;
if (lastSize != size) {
recreateBitmaps = true;
}
lastSize = size;
for (int i = 0; i < N; i++) {
if (recreateBitmaps || bitmap[i] == null) {
if (bitmap[i] != null) {
Bitmap bitmapToRecycle = bitmap[i];
Utilities.globalQueue.postRunnable(() -> {
try {
bitmapToRecycle.recycle();
} catch (Exception e) {
}
});
}
bitmap[i] = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
}
if (byteArrayOutputStream[i] == null) {
byteArrayOutputStream[i] = new ByteArrayOutputStream(w * h * 2);
}
}
}
void release() {
ArrayList<Bitmap> bitmapsToRecycle = null;
for (int i = 0; i < N; i++) {
if (bitmap[i] != null) {
if (bitmapsToRecycle == null) {
bitmapsToRecycle = new ArrayList<>();
}
bitmapsToRecycle.add(bitmap[i]);
}
bitmap[i] = null;
byteArrayOutputStream[i] = null;
}
if (!bitmapsToRecycle.isEmpty()) {
ArrayList<Bitmap> finalBitmapsToRecycle = bitmapsToRecycle;
Utilities.globalQueue.postRunnable(() -> {
for (Bitmap bitmap : finalBitmapsToRecycle) {
bitmap.recycle();
}
});
}
}
}
}

View File

@ -78,7 +78,6 @@ import android.widget.RemoteViews;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import org.json.JSONObject;
import org.telegram.messenger.AccountInstance;
@ -2875,9 +2874,9 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
Intent endIntent = new Intent(this, VoIPActionsReceiver.class);
endIntent.setAction(getPackageName() + ".END_CALL");
if (groupCall != null) {
builder.addAction(R.drawable.ic_call_end_white_24dp, ChatObject.isChannelOrGiga(chat) ? LocaleController.getString("VoipChannelLeaveAlertTitle", R.string.VoipChannelLeaveAlertTitle) : LocaleController.getString("VoipGroupLeaveAlertTitle", R.string.VoipGroupLeaveAlertTitle), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.addAction(R.drawable.ic_call_end_white_24dp, ChatObject.isChannelOrGiga(chat) ? LocaleController.getString("VoipChannelLeaveAlertTitle", R.string.VoipChannelLeaveAlertTitle) : LocaleController.getString("VoipGroupLeaveAlertTitle", R.string.VoipGroupLeaveAlertTitle), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
} else {
builder.addAction(R.drawable.ic_call_end_white_24dp, LocaleController.getString("VoipEndCall", R.string.VoipEndCall), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.addAction(R.drawable.ic_call_end_white_24dp, LocaleController.getString("VoipEndCall", R.string.VoipEndCall), PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
}
builder.setPriority(Notification.PRIORITY_MAX);
builder.setShowWhen(false);
@ -3315,7 +3314,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
FileLog.d("Starting incall activity for incoming call");
}
try {
PendingIntent.getActivity(VoIPService.this, 12345, new Intent(VoIPService.this, LaunchActivity.class).setAction("voip"), 0).send();
PendingIntent.getActivity(VoIPService.this, 12345, new Intent(VoIPService.this, LaunchActivity.class).setAction("voip"), PendingIntent.FLAG_MUTABLE).send();
} catch (Exception x) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error starting incall activity", x);
@ -3923,7 +3922,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
.setContentText(name)
.setSmallIcon(R.drawable.notification)
.setSubText(subText)
.setContentIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE));
.setContentIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE));
Uri soundProviderUri = Uri.parse("content://" + ApplicationLoader.getApplicationId() + ".call_sound_provider/start_ringing");
if (Build.VERSION.SDK_INT >= 26) {
SharedPreferences nprefs = MessagesController.getGlobalNotificationsSettings();
@ -3978,7 +3977,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
endTitle = new SpannableString(endTitle);
((SpannableString) endTitle).setSpan(new ForegroundColorSpan(0xFFF44336), 0, endTitle.length(), 0);
}
PendingIntent endPendingIntent = PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent endPendingIntent = PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
builder.addAction(R.drawable.ic_call_end_white_24dp, endTitle, endPendingIntent);
Intent answerIntent = new Intent(this, VoIPActionsReceiver.class);
answerIntent.setAction(getPackageName() + ".ANSWER_CALL");
@ -3988,7 +3987,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
answerTitle = new SpannableString(answerTitle);
((SpannableString) answerTitle).setSpan(new ForegroundColorSpan(0xFF00AA00), 0, answerTitle.length(), 0);
}
PendingIntent answerPendingIntent = PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
PendingIntent answerPendingIntent = PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
builder.addAction(R.drawable.ic_call, answerTitle, answerPendingIntent);
builder.setPriority(Notification.PRIORITY_MAX);
builder.setShowWhen(false);
@ -3996,7 +3995,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
builder.setColor(0xff2ca5e0);
builder.setVibrate(new long[0]);
builder.setCategory(Notification.CATEGORY_CALL);
builder.setFullScreenIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE), true);
builder.setFullScreenIntent(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE), true);
if (userOrChat instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) userOrChat;
if (!TextUtils.isEmpty(user.phone)) {
@ -4034,7 +4033,13 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
customView.setOnClickPendingIntent(R.id.decline_btn, endPendingIntent);
builder.setLargeIcon(avatar);
incomingNotification.headsUpContentView = incomingNotification.bigContentView = customView;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setColor(0xFF282e31);
builder.setColorized(true);
builder.setCustomBigContentView(customView);
} else {
incomingNotification.headsUpContentView = incomingNotification.bigContentView = customView;
}
}
startForeground(ID_INCOMING_CALL_NOTIFICATION, incomingNotification);
startRingtoneAndVibration();
@ -4276,7 +4281,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.R && (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || privateCall.video && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
try {
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPPermissionActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE).send();
PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, VoIPPermissionActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_ONE_SHOT).send();
} catch (Exception x) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error starting permission activity", x);
@ -4286,7 +4291,7 @@ public class VoIPService extends Service implements SensorEventListener, AudioMa
}
acceptIncomingCall();
try {
PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, getUIActivityClass()).setAction("voip"), PendingIntent.FLAG_IMMUTABLE).send();
PendingIntent.getActivity(VoIPService.this, 0, new Intent(VoIPService.this, getUIActivityClass()).setAction("voip"), PendingIntent.FLAG_MUTABLE).send();
} catch (Exception x) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Error starting incall activity", x);

View File

@ -19,6 +19,7 @@ import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.Utilities;
@ -73,11 +74,10 @@ public class TLRPC {
public static final int MESSAGE_FLAG_HAS_BOT_ID = 0x00000800;
public static final int MESSAGE_FLAG_EDITED = 0x00008000;
public static final int LAYER = 148;
public static final int LAYER = 149;
public static class TL_stats_megagroupStats extends TLObject {
public static int constructor = 0xef7ff916;
public TL_statsDateRangeDays period;
public TL_statsAbsValueAndPrev members;
public TL_statsAbsValueAndPrev messages;
@ -3119,6 +3119,7 @@ public class TLRPC {
public ArrayList<Message> messages = new ArrayList<>();
public ArrayList<Chat> chats = new ArrayList<>();
public ArrayList<User> users = new ArrayList<>();
public ArrayList<TL_forumTopic> topics = new ArrayList<>();
public int flags;
public boolean inexact;
public int pts;
@ -3136,7 +3137,7 @@ public class TLRPC {
case 0x8c718e87:
result = new TL_messages_messages();
break;
case 0x64479808:
case 0xc776ba4e:
result = new TL_messages_channelMessages();
break;
case 0x74535f21:
@ -3322,8 +3323,7 @@ public class TLRPC {
}
public static class TL_messages_channelMessages extends messages_Messages {
public static int constructor = 0x64479808;
public static int constructor = 0xc776ba4e;
public void readParams(AbstractSerializedData stream, boolean exception) {
flags = stream.readInt32(exception);
@ -3356,6 +3356,21 @@ public class TLRPC {
return;
}
count = stream.readInt32(exception);
for (int a = 0; a < count; a++) {
TL_forumTopic object = TL_forumTopic.TLdeserialize(stream, stream.readInt32(exception), exception);
if (object == null) {
return;
}
topics.add(object);
}
magic = stream.readInt32(exception);
if (magic != 0x1cb5c415) {
if (exception) {
throw new RuntimeException(String.format("wrong Vector magic, got %x", magic));
}
return;
}
count = stream.readInt32(exception);
for (int a = 0; a < count; a++) {
Chat object = Chat.TLdeserialize(stream, stream.readInt32(exception), exception);
if (object == null) {
@ -3396,6 +3411,12 @@ public class TLRPC {
messages.get(a).serializeToStream(stream);
}
stream.writeInt32(0x1cb5c415);
count = topics.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
topics.get(a).serializeToStream(stream);
}
stream.writeInt32(0x1cb5c415);
count = chats.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
@ -30953,7 +30974,10 @@ public class TLRPC {
case 0x14b85813:
result = new TL_updateBotMenuButton();
break;
case 0xf694b0ae:
case 0xfe198602:
result = new TL_updateChannelPinnedTopics();
break;
case 0x192efbe3:
result = new TL_updateChannelPinnedTopic();
break;
}
@ -33166,18 +33190,28 @@ public class TLRPC {
}
}
public static class TL_updateChannelPinnedTopic extends Update {
public static int constructor = 0xf694b0ae;
public static class TL_updateChannelPinnedTopics extends Update {
public static int constructor = 0xfe198602;
public int flags;
public long channel_id;
public int topic_id;
public ArrayList<Integer> order = new ArrayList<>();
public void readParams(AbstractSerializedData stream, boolean exception) {
flags = stream.readInt32(exception);
channel_id = stream.readInt64(exception);
if ((flags & 1) != 0) {
topic_id = stream.readInt32(exception);
int magic = stream.readInt32(exception);
if (magic != 0x1cb5c415) {
if (exception) {
throw new RuntimeException(String.format("wrong Vector magic, got %x", magic));
}
return;
}
int count = stream.readInt32(exception);
for (int a = 0; a < count; a++) {
order.add(stream.readInt32(exception));
}
}
}
@ -33186,11 +33220,40 @@ public class TLRPC {
stream.writeInt32(flags);
stream.writeInt64(channel_id);
if ((flags & 1) != 0) {
stream.writeInt32(topic_id);
stream.writeInt32(0x1cb5c415);
int count = order.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
stream.writeInt32(order.get(a));
}
}
}
}
public static class TL_updateChannelPinnedTopic extends Update {
public static int constructor = 0x192efbe3;
public int flags;
public boolean pinned;
public long channel_id;
public int topic_id;
public void readParams(AbstractSerializedData stream, boolean exception) {
flags = stream.readInt32(exception);
pinned = (flags & 1) != 0;
channel_id = stream.readInt64(exception);
topic_id = stream.readInt32(exception);
}
public void serializeToStream(AbstractSerializedData stream) {
stream.writeInt32(constructor);
flags = pinned ? (flags | 1) : (flags &~ 1);
stream.writeInt32(flags);
stream.writeInt64(channel_id);
stream.writeInt32(topic_id);
}
}
public static class TL_receivedNotifyMessage extends TLObject {
public static int constructor = 0xa384b779;
@ -61624,6 +61687,7 @@ public class TLRPC {
public static class TL_dialog extends Dialog {
public static int constructor = 0xa8edd0f5;
public int stableId = MessagesController.stableIdPointer++;
public void readParams(AbstractSerializedData stream, boolean exception) {
flags = stream.readInt32(exception);
@ -64086,11 +64150,9 @@ public class TLRPC {
}
}
public static class TL_forumTopicDeleted extends ForumTopic {
public static class TL_forumTopicDeleted extends TL_forumTopic {
public static int constructor = 0x23f109b;
public int id;
public void readParams(AbstractSerializedData stream, boolean exception) {
id = stream.readInt32(exception);
}
@ -64157,6 +64219,7 @@ public class TLRPC {
public boolean my;
public boolean closed;
public boolean pinned;
public boolean isShort;
public int id;
public int date;
public String title;
@ -64175,10 +64238,14 @@ public class TLRPC {
public ArrayList<MessageObject> groupedMessages; // custom
public Message topMessage; // custom
public String searchQuery; //custom
public int pinnedOrder; // custom
public static TL_forumTopic TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) {
TL_forumTopic result = null;
switch (constructor) {
case 0x23f109b:
result = new TL_forumTopicDeleted();
break;
case 0x5920d6dc:
result = new TL_forumTopic_layer147();
break;
@ -64200,6 +64267,7 @@ public class TLRPC {
my = (flags & 2) != 0;
closed = (flags & 4) != 0;
pinned = (flags & 8) != 0;
isShort = (flags & 32) != 0;
id = stream.readInt32(exception);
date = stream.readInt32(exception);
title = stream.readString(exception);
@ -64225,6 +64293,7 @@ public class TLRPC {
flags = my ? (flags | 2) : (flags &~ 2);
flags = closed ? (flags | 4) : (flags &~ 4);
flags = pinned ? (flags | 8) : (flags &~ 8);
flags = isShort ? (flags | 32) : (flags &~ 32);
stream.writeInt32(flags);
stream.writeInt32(id);
stream.writeInt32(date);
@ -64668,6 +64737,32 @@ public class TLRPC {
channel.serializeToStream(stream);
}
}
public static class TL_channels_reorderPinnedForumTopics extends TLObject {
public static int constructor = 0x2950a18f;
public int flags;
public boolean force;
public InputChannel channel;
public ArrayList<Integer> order = new ArrayList<>();
public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) {
return Updates.TLdeserialize(stream, constructor, exception);
}
public void serializeToStream(AbstractSerializedData stream) {
stream.writeInt32(constructor);
flags = force ? (flags | 1) : (flags &~ 1);
stream.writeInt32(flags);
channel.serializeToStream(stream);
stream.writeInt32(0x1cb5c415);
int count = order.size();
stream.writeInt32(count);
for (int a = 0; a < count; a++) {
stream.writeInt32(order.get(a));
}
}
}
//functions
public static class Vector extends TLObject {

View File

@ -74,6 +74,7 @@ public class ActionBar extends FrameLayout {
}
}
private INavigationLayout.BackButtonState backButtonState;
private UnreadImageView backButtonImageView;
private Drawable backButtonDrawable;
private SimpleTextView[] titleTextView = new SimpleTextView[2];
@ -83,7 +84,7 @@ public class ActionBar extends FrameLayout {
private int actionModeColor;
private int actionBarColor;
private boolean isMenuOffsetSuppressed;
private ActionBarMenu menu;
public ActionBarMenu menu;
private ActionBarMenu actionMode;
private String actionModeTag;
private boolean ignoreLayoutRequest;
@ -162,6 +163,10 @@ public class ActionBar extends FrameLayout {
});
}
public INavigationLayout.BackButtonState getBackButtonState() {
return backButtonState;
}
private void createBackButtonImage() {
if (backButtonImageView != null) {
return;
@ -252,6 +257,10 @@ public class ActionBar extends FrameLayout {
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (parentFragment != null && parentFragment.getParentLayout().isActionBarInCrossfade()) {
return false;
}
boolean clip = shouldClipChild(child);
if (clip) {
canvas.save();
@ -325,6 +334,9 @@ public class ActionBar extends FrameLayout {
}
backButtonImageView.setVisibility(resource == 0 ? GONE : VISIBLE);
backButtonImageView.setImageResource(resource);
if (resource == R.drawable.ic_ab_back) {
backButtonState = INavigationLayout.BackButtonState.BACK;
}
}
private void createSubtitleTextView() {
@ -608,6 +620,45 @@ public class ActionBar extends FrameLayout {
return actionMode;
}
public void onDrawCrossfadeBackground(Canvas canvas) {
if (blurredBackground && actionBarColor != Color.TRANSPARENT) {
rectTmp.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
blurScrimPaint.setColor(actionBarColor);
contentView.drawBlurRect(canvas, getY(), rectTmp, blurScrimPaint, true);
} else {
Drawable drawable = getBackground();
if (drawable != null) {
drawable.setBounds(0, 0, getWidth(), getHeight());
drawable.draw(canvas);
}
}
}
public void onDrawCrossfadeContent(Canvas canvas, boolean front, boolean hideBackDrawable, float progress) {
for (int i = 0; i < getChildCount(); i++) {
View ch = getChildAt(i);
if ((!hideBackDrawable || ch != backButtonImageView) && ch.getVisibility() == View.VISIBLE && ch instanceof ActionBarMenu) {
canvas.save();
canvas.translate(ch.getX(), ch.getY());
ch.draw(canvas);
canvas.restore();
}
}
canvas.save();
canvas.translate(front ? getWidth() * progress * 0.5f : -getWidth() * 0.4f * (1f - progress), 0);
for (int i = 0; i < getChildCount(); i++) {
View ch = getChildAt(i);
if ((!hideBackDrawable || ch != backButtonImageView) && ch.getVisibility() == View.VISIBLE && !(ch instanceof ActionBarMenu)) {
canvas.save();
canvas.translate(ch.getX(), ch.getY());
ch.draw(canvas);
canvas.restore();
}
}
canvas.restore();
}
public void showActionMode() {
showActionMode(true, null, null, null, null, null, 0);
}

View File

@ -300,33 +300,6 @@ public class ActionBarLayout extends FrameLayout implements INavigationLayout, F
}
}
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);
}
}
public static Drawable headerShadowDrawable;
private static Drawable layerShadowDrawable;
private static Paint scrimPaint;
@ -2222,7 +2195,9 @@ public class ActionBarLayout extends FrameLayout implements INavigationLayout, F
private void onCloseAnimationEnd() {
if (transitionAnimationInProgress && onCloseAnimationEndRunnable != null) {
if (currentAnimation != null) {
currentAnimation.cancel();
AnimatorSet animatorSet = currentAnimation;
currentAnimation = null;
animatorSet.cancel();
}
transitionAnimationInProgress = false;
layoutToIgnore = null;

View File

@ -87,6 +87,8 @@ public class ActionBarMenuItem extends FrameLayout {
}
public static class ActionBarMenuItemSearchListener {
public void onPreToggleSearch() {}
public void onSearchExpand() {
}
@ -145,6 +147,8 @@ public class ActionBarMenuItem extends FrameLayout {
private LinearLayout searchFilterLayout;
private ArrayList<SearchFilterView> searchFilterViews = new ArrayList<>();
private TextView searchFieldCaption;
private CharSequence searchFieldHint;
private CharSequence searchFieldText;
private ImageView clearButton;
private AnimatorSet clearButtonAnimator;
private View searchAdditionalButton;
@ -152,6 +156,7 @@ public class ActionBarMenuItem extends FrameLayout {
protected TextView textView;
private FrameLayout searchContainer;
private boolean isSearchField;
private boolean wrapSearchInScrollView;
protected ActionBarMenuItemSearchListener listener;
private Rect rect;
private int[] location;
@ -777,6 +782,7 @@ public class ActionBarMenuItem extends FrameLayout {
}
public void openSearch(boolean openKeyboard) {
checkCreateSearchField();
if (searchContainer == null || searchContainer.getVisibility() == VISIBLE || parentMenu == null) {
return;
}
@ -793,6 +799,10 @@ public class ActionBarMenuItem extends FrameLayout {
public boolean toggleSearch(boolean openKeyboard) {
checkCreateSearchField();
if (listener != null) {
listener.onPreToggleSearch();
}
if (searchContainer == null || (listener != null && !listener.canToggleSearch())) {
return false;
}
@ -1059,6 +1069,7 @@ public class ActionBarMenuItem extends FrameLayout {
}
public void setSearchFieldHint(CharSequence hint) {
searchFieldHint = hint;
if (searchFieldCaption == null) {
return;
}
@ -1067,6 +1078,7 @@ public class ActionBarMenuItem extends FrameLayout {
}
public void setSearchFieldText(CharSequence text, boolean animated) {
searchFieldText = text;
if (searchFieldCaption == null) {
return;
}
@ -1084,6 +1096,7 @@ public class ActionBarMenuItem extends FrameLayout {
}
public EditTextBoldCursor getSearchField() {
checkCreateSearchField();
return searchField;
}
@ -1104,7 +1117,13 @@ public class ActionBarMenuItem extends FrameLayout {
if (parentMenu == null) {
return this;
}
if (value && searchContainer == null) {
isSearchField = value;
wrapSearchInScrollView = wrapInScrollView;
return this;
}
private void checkCreateSearchField() {
if (searchContainer == null && isSearchField) {
searchContainer = new FrameLayout(getContext()) {
private boolean ignoreRequestLayout;
@ -1135,7 +1154,7 @@ public class ActionBarMenuItem extends FrameLayout {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!wrapInScrollView) {
if (!wrapSearchInScrollView) {
measureChildWithMargins(clearButton, widthMeasureSpec, 0, heightMeasureSpec, 0);
if (searchAdditionalButton != null) {
measureChildWithMargins(searchAdditionalButton, widthMeasureSpec, 0, heightMeasureSpec, 0);
@ -1202,7 +1221,7 @@ public class ActionBarMenuItem extends FrameLayout {
};
searchContainer.setClipChildren(searchItemPaddingStart != 0);
wrappedSearchFrameLayout = null;
if (wrapInScrollView) {
if (wrapSearchInScrollView) {
wrappedSearchFrameLayout = new FrameLayout(getContext());
HorizontalScrollView horizontalScrollView = new HorizontalScrollView(getContext()) {
@ -1371,16 +1390,24 @@ public class ActionBarMenuItem extends FrameLayout {
searchField.setHighlightColor(getThemedColor(Theme.key_chat_inTextSelectionHighlight));
searchField.setHandlesColor(getThemedColor(Theme.key_chat_TextSelectionCursor));
if (searchFieldHint != null) {
searchField.setHint(searchFieldHint);
setContentDescription(searchFieldHint);
}
if (searchFieldText != null) {
searchField.setText(searchFieldText);
}
searchFilterLayout = new LinearLayout(getContext());
searchFilterLayout.setOrientation(LinearLayout.HORIZONTAL);
searchFilterLayout.setVisibility(View.VISIBLE);
if (!LocaleController.isRTL) {
searchContainer.addView(searchFieldCaption, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.CENTER_VERTICAL | Gravity.LEFT, 0, 5.5f, 0, 0));
searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 6, 0, wrapInScrollView ? 0 : 48, 0));
searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 6, 0, wrapSearchInScrollView ? 0 : 48, 0));
searchContainer.addView(searchFilterLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 32, Gravity.CENTER_VERTICAL, 0, 0, 48, 0));
} else {
searchContainer.addView(searchFilterLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 32, Gravity.CENTER_VERTICAL, 0, 0, 48, 0));
searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 0, 0, wrapInScrollView ? 0 : 48, 0));
searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 0, 0, wrapSearchInScrollView ? 0 : 48, 0));
searchContainer.addView(searchFieldCaption, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.CENTER_VERTICAL | Gravity.RIGHT, 0, 5.5f, 48, 0));
}
searchFilterLayout.setClipChildren(false);
@ -1443,14 +1470,12 @@ public class ActionBarMenuItem extends FrameLayout {
AndroidUtilities.showKeyboard(searchField);
});
clearButton.setContentDescription(LocaleController.getString("ClearButton", R.string.ClearButton));
if (wrapInScrollView) {
if (wrapSearchInScrollView) {
wrappedSearchFrameLayout.addView(clearButton, LayoutHelper.createFrame(48, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
} else {
searchContainer.addView(clearButton, LayoutHelper.createFrame(48, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
}
}
isSearchField = value;
return this;
}
public OnClickListener getOnClickListener() {
@ -1601,6 +1626,7 @@ public class ActionBarMenuItem extends FrameLayout {
}
public void clearSearchText() {
searchFieldText = null;
if (searchField == null) {
return;
}

View File

@ -157,6 +157,14 @@ public abstract class BaseFragment {
return parentLayout != null && parentLayout.isInPassivePreviewMode();
}
public boolean isActionBarCrossfadeEnabled() {
return actionBar != null;
}
public INavigationLayout.BackButtonState getBackButtonState() {
return actionBar != null ? actionBar.getBackButtonState() : null;
}
public void setInPreviewMode(boolean value) {
inPreviewMode = value;
if (actionBar != null) {

View File

@ -78,6 +78,10 @@ public interface INavigationLayout {
return SharedConfig.useLNavigation ? new LNavigation(context) : new ActionBarLayout(context);
}
default boolean isActionBarInCrossfade() {
return false;
}
default boolean hasIntegratedBlurInPreview() {
return false;
}
@ -376,4 +380,9 @@ public interface INavigationLayout {
}
}
}
enum BackButtonState {
BACK,
MENU
}
}

View File

@ -181,7 +181,7 @@ public class MenuDrawable extends Drawable {
startXDiff += (paint.getStrokeWidth() / 2f) * (1f - currentRotation);
endYDiff += AndroidUtilities.dp(.5f) * currentRotation;
endXDiff -= AndroidUtilities.dp(.5f) * currentRotation + (paint.getStrokeWidth() / 2f) * (1f - currentRotation);
startYDiff -= AndroidUtilities.dp(.25f) * currentRotation;
startYDiff -= AndroidUtilities.dp(.75f) * currentRotation;
endYDiff += AndroidUtilities.dp(.25f) * currentRotation;
}
} else {

View File

@ -2969,6 +2969,7 @@ public class Theme {
public static Drawable dialogs_mentionDrawable;
public static Drawable dialogs_reactionsMentionDrawable;
public static Drawable dialogs_holidayDrawable;
public static Drawable dialogs_forum_arrowDrawable;
public static RLottieDrawable dialogs_archiveAvatarDrawable;
public static RLottieDrawable dialogs_archiveDrawable;
public static RLottieDrawable dialogs_unarchiveDrawable;
@ -3051,6 +3052,7 @@ public class Theme {
public static TextPaint chat_forwardNamePaint;
public static TextPaint chat_replyNamePaint;
public static TextPaint chat_replyTextPaint;
public static TextPaint chat_topicTextPaint;
public static TextPaint chat_commentTextPaint;
public static TextPaint chat_contextResult_titleTextPaint;
public static TextPaint chat_contextResult_descriptionTextPaint;
@ -3127,6 +3129,8 @@ public class Theme {
public static Drawable chat_commentDrawable;
public static Drawable chat_commentStickerDrawable;
public static Drawable chat_commentArrowDrawable;
public static Drawable chat_gradientLeftDrawable;
public static Drawable chat_gradientRightDrawable;
public static Drawable[] chat_msgInCallDrawable = new Drawable[2];
public static Drawable[] chat_msgInCallSelectedDrawable = new Drawable[2];
public static Drawable[] chat_msgOutCallDrawable = new Drawable[2];
@ -3241,6 +3245,7 @@ public class Theme {
public static final String key_windowBackgroundWhiteRedText4 = "windowBackgroundWhiteRedText4";
public static final String key_windowBackgroundWhiteRedText5 = "windowBackgroundWhiteRedText5";
public static final String key_windowBackgroundWhiteRedText6 = "windowBackgroundWhiteRedText6";
public static final String key_windowBackgroundWhiteYellowText = "windowBackgroundWhiteYellowText";
public static final String key_windowBackgroundWhiteGrayText = "windowBackgroundWhiteGrayText";
public static final String key_windowBackgroundWhiteGrayText2 = "windowBackgroundWhiteGrayText2";
public static final String key_windowBackgroundWhiteGrayText3 = "windowBackgroundWhiteGrayText3";
@ -3306,6 +3311,7 @@ public class Theme {
public static final String key_avatar_text = "avatar_text";
public static final String key_avatar_backgroundSaved = "avatar_backgroundSaved";
public static final String key_avatar_background2Saved = "avatar_background2Saved";
public static final String key_avatar_backgroundArchived = "avatar_backgroundArchived";
public static final String key_avatar_backgroundArchivedHidden = "avatar_backgroundArchivedHidden";
public static final String key_avatar_backgroundRed = "avatar_backgroundRed";
@ -3315,6 +3321,13 @@ public class Theme {
public static final String key_avatar_backgroundCyan = "avatar_backgroundCyan";
public static final String key_avatar_backgroundBlue = "avatar_backgroundBlue";
public static final String key_avatar_backgroundPink = "avatar_backgroundPink";
public static final String key_avatar_background2Red = "avatar_background2Red";
public static final String key_avatar_background2Orange = "avatar_background2Orange";
public static final String key_avatar_background2Violet = "avatar_background2Violet";
public static final String key_avatar_background2Green = "avatar_background2Green";
public static final String key_avatar_background2Cyan = "avatar_background2Cyan";
public static final String key_avatar_background2Blue = "avatar_background2Blue";
public static final String key_avatar_background2Pink = "avatar_background2Pink";
public static final String key_avatar_backgroundInProfileBlue = "avatar_backgroundInProfileBlue";
public static final String key_avatar_backgroundActionBarBlue = "avatar_backgroundActionBarBlue";
@ -3331,6 +3344,7 @@ public class Theme {
public static final String key_avatar_nameInMessagePink = "avatar_nameInMessagePink";
public static String[] keys_avatar_background = {key_avatar_backgroundRed, key_avatar_backgroundOrange, key_avatar_backgroundViolet, key_avatar_backgroundGreen, key_avatar_backgroundCyan, key_avatar_backgroundBlue, key_avatar_backgroundPink};
public static String[] keys_avatar_background2 = {key_avatar_background2Red, key_avatar_background2Orange, key_avatar_background2Violet, key_avatar_background2Green, key_avatar_background2Cyan, key_avatar_background2Blue, key_avatar_background2Pink};
public static String[] keys_avatar_nameInMessage = {key_avatar_nameInMessageRed, key_avatar_nameInMessageOrange, key_avatar_nameInMessageViolet, key_avatar_nameInMessageGreen, key_avatar_nameInMessageCyan, key_avatar_nameInMessageBlue, key_avatar_nameInMessagePink};
public static final String key_actionBarDefault = "actionBarDefault";
@ -3986,6 +4000,8 @@ public class Theme {
public static final String key_premiumGradientBottomSheet1 = "premiumGradientBottomSheet1";
public static final String key_premiumGradientBottomSheet2 = "premiumGradientBottomSheet2";
public static final String key_premiumGradientBottomSheet3 = "premiumGradientBottomSheet3";
public static final String key_topics_unreadCounter = "topics_unreadCounter";
public static final String key_topics_unreadCounterMuted = "topics_unreadCounterMuted";
public static final String key_drawable_botInline = "drawableBotInline";
public static final String key_drawable_botLink = "drawableBotLink";
@ -4037,7 +4053,6 @@ public class Theme {
public static final String key_drawable_chat_pollHintDrawableOut = "drawable_chat_pollHintDrawableOut";
public static final String key_drawable_chat_pollHintDrawableIn = "drawable_chat_pollHintDrawableIn";
private static final HashMap<String, Drawable> defaultChatDrawables = new HashMap<>();
private static final HashMap<String, String> defaultChatDrawableColorKeys = new HashMap<>();
@ -4150,6 +4165,7 @@ public class Theme {
defaultColors.put(key_windowBackgroundWhiteRedText4, 0xffcf3030);
defaultColors.put(key_windowBackgroundWhiteRedText5, 0xffed3939);
defaultColors.put(key_windowBackgroundWhiteRedText6, 0xffff6666);
defaultColors.put(key_windowBackgroundWhiteYellowText, 0xffD87B29);
defaultColors.put(key_windowBackgroundWhiteGrayText, 0xff838c96);
defaultColors.put(key_windowBackgroundWhiteGrayText2, 0xff82868a);
defaultColors.put(key_windowBackgroundWhiteGrayText3, 0xff999999);
@ -4204,16 +4220,25 @@ public class Theme {
defaultColors.put(key_avatar_text, 0xffffffff);
defaultColors.put(key_avatar_backgroundSaved, 0xff66bffa);
defaultColors.put(key_avatar_backgroundArchived, 0xffa9b6c1);
defaultColors.put(key_avatar_backgroundSaved, 0xff69BFFA);
defaultColors.put(key_avatar_background2Saved, 0xff3D9DE0);
defaultColors.put(key_avatar_backgroundArchived, 0xffB8C2CC);
defaultColors.put(key_avatar_backgroundArchivedHidden, 0xff66bffa);
defaultColors.put(key_avatar_backgroundRed, 0xffe56555);
defaultColors.put(key_avatar_backgroundOrange, 0xfff28c48);
defaultColors.put(key_avatar_backgroundViolet, 0xff8e85ee);
defaultColors.put(key_avatar_backgroundGreen, 0xff76c84d);
defaultColors.put(key_avatar_backgroundCyan, 0xff5fbed5);
defaultColors.put(key_avatar_backgroundBlue, 0xff549cdd);
defaultColors.put(key_avatar_backgroundPink, 0xfff2749a);
defaultColors.put(key_avatar_backgroundRed, 0xffFF845E);
defaultColors.put(key_avatar_backgroundOrange, 0xffFEBB5B);
defaultColors.put(key_avatar_backgroundViolet, 0xffB694F9);
defaultColors.put(key_avatar_backgroundGreen, 0xff9AD164);
defaultColors.put(key_avatar_backgroundCyan, 0xff5BCBE3);
defaultColors.put(key_avatar_backgroundBlue, 0xff5CAFFA);
defaultColors.put(key_avatar_backgroundPink, 0xffFF8AAC);
defaultColors.put(key_avatar_background2Red, 0xffD45246);
defaultColors.put(key_avatar_background2Orange, 0xffF68136);
defaultColors.put(key_avatar_background2Violet, 0xff6C61DF);
defaultColors.put(key_avatar_background2Green, 0xff46BA43);
defaultColors.put(key_avatar_background2Cyan, 0xff359AD4);
defaultColors.put(key_avatar_background2Blue, 0xff408ACF);
defaultColors.put(key_avatar_background2Pink, 0xffD95574);
defaultColors.put(key_avatar_backgroundInProfileBlue, 0xff5085b1);
defaultColors.put(key_avatar_backgroundActionBarBlue, 0xff598fba);
@ -4223,11 +4248,11 @@ public class Theme {
defaultColors.put(key_avatar_nameInMessageRed, 0xffca5650);
defaultColors.put(key_avatar_nameInMessageOrange, 0xffd87b29);
defaultColors.put(key_avatar_nameInMessageViolet, 0xff4e92cc);
defaultColors.put(key_avatar_nameInMessageViolet, 0xff9B66DC);
defaultColors.put(key_avatar_nameInMessageGreen, 0xff50b232);
defaultColors.put(key_avatar_nameInMessageCyan, 0xff379eb8);
defaultColors.put(key_avatar_nameInMessageBlue, 0xff4e92cc);
defaultColors.put(key_avatar_nameInMessagePink, 0xff4e92cc);
defaultColors.put(key_avatar_nameInMessagePink, 0xffCF5C95);
defaultColors.put(key_actionBarDefault, 0xff527da3);
defaultColors.put(key_actionBarDefaultIcon, 0xffffffff);
@ -4879,6 +4904,8 @@ public class Theme {
defaultColors.put(key_premiumGradientBottomSheet1, 0xff5B9DE7);
defaultColors.put(key_premiumGradientBottomSheet2, 0xffAB87DD);
defaultColors.put(key_premiumGradientBottomSheet3, 0xffE794BE);
defaultColors.put(key_topics_unreadCounter, 0xff4ecc5e);
defaultColors.put(key_topics_unreadCounterMuted, 0xff8b8d8f);
fallbackKeys.put(key_chat_inAdminText, key_chat_inTimeText);
fallbackKeys.put(key_chat_inAdminSelectedText, key_chat_inTimeSelectedText);
@ -4996,6 +5023,7 @@ public class Theme {
fallbackKeys.put(key_chat_outPollCorrectAnswer, key_chat_attachLocationBackground);
fallbackKeys.put(key_chat_inPollWrongAnswer, key_chat_attachAudioBackground);
fallbackKeys.put(key_chat_outPollWrongAnswer, key_chat_attachAudioBackground);
fallbackKeys.put(key_windowBackgroundWhiteYellowText, key_avatar_nameInMessageOrange);
fallbackKeys.put(key_profile_tabText, key_windowBackgroundWhiteGrayText);
fallbackKeys.put(key_profile_tabSelectedText, key_windowBackgroundWhiteBlueHeader);
@ -5026,8 +5054,20 @@ public class Theme {
fallbackKeys.put(key_chat_inReactionButtonTextSelected, key_windowBackgroundWhite);
fallbackKeys.put(key_chat_outReactionButtonTextSelected, key_windowBackgroundWhite);
fallbackKeys.put(key_dialogReactionMentionBackground, key_voipgroup_mutedByAdminGradient2);
fallbackKeys.put(key_topics_unreadCounter, key_chats_unreadCounter);
fallbackKeys.put(key_topics_unreadCounterMuted, key_chats_message);
fallbackKeys.put(key_avatar_background2Saved, key_avatar_backgroundSaved);
fallbackKeys.put(key_avatar_background2Red, key_avatar_backgroundRed);
fallbackKeys.put(key_avatar_background2Orange, key_avatar_backgroundOrange);
fallbackKeys.put(key_avatar_background2Violet, key_avatar_backgroundViolet);
fallbackKeys.put(key_avatar_background2Green, key_avatar_backgroundGreen);
fallbackKeys.put(key_avatar_background2Cyan, key_avatar_backgroundCyan);
fallbackKeys.put(key_avatar_background2Blue, key_avatar_backgroundBlue);
fallbackKeys.put(key_avatar_background2Pink, key_avatar_backgroundPink);
themeAccentExclusionKeys.addAll(Arrays.asList(keys_avatar_background));
themeAccentExclusionKeys.addAll(Arrays.asList(keys_avatar_background2));
themeAccentExclusionKeys.addAll(Arrays.asList(keys_avatar_nameInMessage));
themeAccentExclusionKeys.add(key_chat_attachFileBackground);
themeAccentExclusionKeys.add(key_chat_attachGalleryBackground);
@ -8990,6 +9030,7 @@ public class Theme {
dialogs_mentionDrawable = resources.getDrawable(R.drawable.mentionchatslist);
dialogs_reactionsMentionDrawable = resources.getDrawable(R.drawable.reactionchatslist);
dialogs_pinnedDrawable = resources.getDrawable(R.drawable.list_pin);
dialogs_forum_arrowDrawable = resources.getDrawable(R.drawable.msg_mini_forumarrow);
moveUpDrawable = resources.getDrawable(R.drawable.preview_arrow);
RectF rect = new RectF();
@ -9063,6 +9104,7 @@ public class Theme {
setDrawableColorByKey(dialogs_muteDrawable, key_chats_muteIcon);
setDrawableColorByKey(dialogs_unmuteDrawable, key_chats_muteIcon);
setDrawableColorByKey(dialogs_mentionDrawable, key_chats_mentionIcon);
setDrawableColorByKey(dialogs_forum_arrowDrawable, key_chats_message);
setDrawableColorByKey(dialogs_reactionsMentionDrawable, key_chats_mentionIcon);
setDrawableColorByKey(dialogs_verifiedDrawable, key_chats_verifiedBackground);
setDrawableColorByKey(dialogs_verifiedCheckDrawable, key_chats_verifiedCheck);
@ -9108,6 +9150,8 @@ public class Theme {
chat_replyNamePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_replyNamePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
chat_replyTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_topicTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_topicTextPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
chat_forwardNamePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_adminPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
@ -9128,6 +9172,7 @@ public class Theme {
chat_namePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_replyNamePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_replyTextPaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_topicTextPaint.setTextSize(AndroidUtilities.dp(smallerDp - 1));
chat_forwardNamePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_adminPaint.setTextSize(AndroidUtilities.dp(smallerDp - 1));
// float timeDp = 2 * (SharedConfig.fontSize - 16) / 3f + 12;
@ -9188,6 +9233,8 @@ public class Theme {
chat_replyNamePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_replyNamePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
chat_replyTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_topicTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_topicTextPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
chat_commentTextPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
chat_instantViewPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
chat_instantViewPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
@ -9338,6 +9385,8 @@ public class Theme {
chat_commentDrawable = resources.getDrawable(R.drawable.msg_msgbubble);
chat_commentStickerDrawable = resources.getDrawable(R.drawable.msg_msgbubble2);
chat_commentArrowDrawable = resources.getDrawable(R.drawable.msg_arrowright);
chat_gradientLeftDrawable = resources.getDrawable(R.drawable.gradient_left);
chat_gradientRightDrawable = resources.getDrawable(R.drawable.gradient_right);
chat_contextResult_shadowUnderSwitchDrawable = resources.getDrawable(R.drawable.header_shadow).mutate();
@ -9528,6 +9577,7 @@ public class Theme {
chat_namePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_replyNamePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_replyTextPaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_topicTextPaint.setTextSize(AndroidUtilities.dp(smallerDp - 1));
chat_forwardNamePaint.setTextSize(AndroidUtilities.dp(smallerDp));
chat_adminPaint.setTextSize(AndroidUtilities.dp(smallerDp - 1));
float timeDp = 2 * (SharedConfig.fontSize - 16) / 3f + 12;
@ -9662,6 +9712,8 @@ public class Theme {
setDrawableColorByKey(chat_commentDrawable, key_chat_inInstant);
setDrawableColorByKey(chat_commentStickerDrawable, key_chat_serviceIcon);
setDrawableColorByKey(chat_commentArrowDrawable, key_chat_inInstant);
setDrawableColorByKey(chat_gradientLeftDrawable, key_chat_stickersHintPanel);
setDrawableColorByKey(chat_gradientRightDrawable, key_chat_stickersHintPanel);
for (int a = 0; a < 2; a++) {
setDrawableColorByKey(chat_msgInCallDrawable[a], key_chat_inInstant);

View File

@ -17,7 +17,6 @@ import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
@ -66,7 +65,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
public class DialogsAdapter extends RecyclerListView.SelectionAdapter implements DialogCell.DialogCellDelegate {
public final static int VIEW_TYPE_DIALOG = 0,
VIEW_TYPE_FLICKER = 1,
VIEW_TYPE_RECENTLY_VIEWED = 2,
@ -413,6 +412,7 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
DialogCell dialogCell = new DialogCell(parentFragment, mContext, true, false, currentAccount, null);
dialogCell.setArchivedPullAnimation(pullForegroundDrawable);
dialogCell.setPreloader(preloader);
dialogCell.setDialogCellDelegate(this);
view = dialogCell;
}
break;
@ -887,6 +887,21 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
}
}
@Override
public void onButtonClicked(DialogCell dialogCell) {
}
@Override
public void onButtonLongPress(DialogCell dialogCell) {
}
@Override
public boolean canClickButtonInside() {
return selectedDialogs.isEmpty();
}
public static class DialogsPreloader {
private final int MAX_REQUEST_COUNT = 4;
@ -1063,6 +1078,5 @@ public class DialogsAdapter extends RecyclerListView.SelectionAdapter {
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height);
}
}
}

View File

@ -1039,7 +1039,12 @@ public class DialogsSearchAdapter extends RecyclerListView.SelectionAdapter {
view = new GraySectionCell(mContext);
break;
case VIEW_TYPE_DIALOG_CELL:
view = new DialogCell(null, mContext, false, true);
view = new DialogCell(null, mContext, false, true) {
@Override
protected boolean isForumCell() {
return false;
}
};
break;
case VIEW_TYPE_LOADING:
FlickerLoadingView flickerLoadingView = new FlickerLoadingView(mContext);

View File

@ -10614,7 +10614,7 @@ public class ArticleViewer implements NotificationCenter.NotificationCenterDeleg
progressView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(39), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(39), MeasureSpec.EXACTLY));
imageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(39), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(39), MeasureSpec.EXACTLY));
if (currentBlock != null) {
textLayout = createLayoutForText(this, currentBlock.channel.title, null, width - AndroidUtilities.dp(36 + 16) - buttonWidth, textY, currentBlock, StaticLayoutEx.ALIGN_LEFT(), parentAdapter);
textLayout = createLayoutForText(this, currentBlock.channel.title, null, width - AndroidUtilities.dp(36 + 16) - buttonWidth, textY, currentBlock, StaticLayoutEx.ALIGN_LEFT(), 1, parentAdapter);
if (parentAdapter.isRtl) {
textX2 = textX;
} else {

View File

@ -75,6 +75,7 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.AccountInstance;
@ -112,6 +113,7 @@ import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.AnimatedColor;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AnimatedEmojiSpan;
import org.telegram.ui.Components.AnimatedFileDrawable;
@ -127,10 +129,10 @@ import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EmptyStubSpan;
import org.telegram.ui.Components.FloatSeekBarAccessibilityDelegate;
import org.telegram.ui.Components.Forum.ForumUtilities;
import org.telegram.ui.Components.Forum.MessageTopicButton;
import org.telegram.ui.Components.InfiniteProgress;
import org.telegram.ui.Components.LinkPath;
import org.telegram.ui.Components.LinkSpanDrawable;
import org.telegram.ui.Components.LocationMessageLoadingDrawable;
import org.telegram.ui.Components.MediaActionDrawable;
import org.telegram.ui.Components.MessageBackgroundDrawable;
import org.telegram.ui.Components.MotionBackgroundDrawable;
@ -527,6 +529,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
default boolean didPressAnimatedEmoji(AnimatedEmojiSpan span) {
return false;
}
default void didPressTopicButton(ChatMessageCell cell) {}
}
private final static int DOCUMENT_ATTACH_TYPE_NONE = 0;
@ -965,6 +969,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
private float replyTouchX, replyTouchY;
private TLRPC.PhotoSize currentReplyPhoto;
private boolean drawTopic;
private MessageTopicButton topicButton;
private int drawSideButton;
private boolean sideButtonPressed;
private float sideStartX;
@ -1248,7 +1255,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
pollAvatarImages[a] = new ImageReceiver(this);
pollAvatarImages[a].setRoundRadius(AndroidUtilities.dp(8));
pollAvatarDrawables[a] = new AvatarDrawable();
pollAvatarDrawables[a].setTextSize(AndroidUtilities.dp(6));
pollAvatarDrawables[a].setTextSize(AndroidUtilities.dp(22));
}
pollCheckBox = new CheckBoxBase[10];
for (int a = 0; a < pollCheckBox.length; a++) {
@ -2656,6 +2663,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (!result) {
result = checkTextSelection(event);
}
if (!result && topicButton != null) {
result = topicButton.checkTouchEvent(event);
}
if (!result) {
result = checkOtherButtonMotionEvent(event);
}
@ -3690,6 +3700,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
unregisterFlagSecure.run();
unregisterFlagSecure = null;
}
if (topicButton != null) {
topicButton.onDetached(this);
}
}
@Override
@ -3761,6 +3775,10 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (currentMessageObject != null && currentMessageObject.type == MessageObject.TYPE_EXTENDED_MEDIA_PREVIEW && unlockLayout != null) {
invalidate();
}
if (topicButton != null) {
topicButton.onAttached(this);
}
}
boolean imageReceiversAttachState;
@ -4506,6 +4524,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
int maxChildWidth = Math.max(backgroundWidth, nameWidth);
maxChildWidth = Math.max(maxChildWidth, forwardedNameWidth);
maxChildWidth = Math.max(maxChildWidth, replyNameWidth);
if (topicButton != null) {
maxChildWidth = Math.max(maxChildWidth, topicButton.width());
}
maxChildWidth = Math.max(maxChildWidth, replyTextWidth);
if (commentLayout != null && drawSideButton != 3) {
maxChildWidth = Math.max(maxChildWidth, totalCommentWidth);
@ -4568,7 +4589,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
"telegram_user".equals(type) || "telegram_channel".equals(type) ||
"telegram_megagroup".equals(type) || "telegram_voicechat".equals(type) ||
"telegram_livestream".equals(type);
smallImage = !slideshow && (!drawInstantView || drawInstantViewType == 1 || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13) && document == null && isSmallImageType;
smallImage = !slideshow && (!drawInstantView || drawInstantViewType == 1 || drawInstantViewType == 2 || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13) && document == null && isSmallImageType;
isSmallImage = smallImage && type != null && currentMessageObject.photoThumbs != null;
} else if (hasInvoicePreview) {
TLRPC.TL_messageMediaInvoice invoice = (TLRPC.TL_messageMediaInvoice) MessageObject.getMedia(messageObject.messageOwner);
@ -6148,13 +6169,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
if (locationLoadingThumb == null) {
SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(R.raw.map_placeholder, Theme.key_windowBackgroundWhiteGrayIcon, 1f);
SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(R.raw.map_placeholder, Theme.key_chat_outLocationIcon, (Theme.isCurrentThemeDark() ? 3 : 6) * .12f);
svgThumb.setAspectCenter(true);
locationLoadingThumb = new ClipRoundedDrawable(svgThumb);
}
if (locationLoadingThumb instanceof ClipRoundedDrawable && ((ClipRoundedDrawable) locationLoadingThumb).getDrawable() instanceof SvgHelper.SvgDrawable) {
SvgHelper.SvgDrawable drawable = (SvgHelper.SvgDrawable) ((ClipRoundedDrawable) locationLoadingThumb).getDrawable();
drawable.setColorKey(messageObject.isOutOwner() ? Theme.key_chat_outBubbleLocationPlaceholder : Theme.key_chat_inBubbleLocationPlaceholder);
drawable.setColorKey(messageObject.isOutOwner() ? Theme.key_chat_outLocationIcon : Theme.key_chat_inLocationIcon, resourcesProvider);
}
photoImage.setCrossfadeDuration(2 * ImageReceiver.DEFAULT_CROSSFADE_DURATION);
photoImage.setCrossfadeByScale(.05f);
@ -6210,7 +6231,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
additionHeight += reactionsLayoutInBubble.totalHeight + AndroidUtilities.dp(8);
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(8);
}
additionHeight -= AndroidUtilities.dp(17);
if (!(drawTopic && (currentMessageObject != null && currentMessageObject.replyMessageObject != null || forwardedNameLayout != null && forwardedNameLayout[0] != null))) {
additionHeight -= AndroidUtilities.dp(17);
}
} else if (messageObject.isAnyKindOfSticker()) {
drawBackground = false;
@ -7009,13 +7032,23 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
photoHeight += AndroidUtilities.dp(1);
}
} else if (currentPosition != null && currentMessageObject.isDocument()) {
if ((currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0 && (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0 && !messageObject.isOutOwner()) {
totalHeight -= AndroidUtilities.dp(2);
}
}
int y = 0;
if (currentMessageObject.type != MessageObject.TYPE_EMOJIS) {
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
namesOffset -= AndroidUtilities.dp(documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT ? 2 : 1);
}
if (drawPinnedTop && !messageObject.isOutOwner()) {
totalHeight += AndroidUtilities.dp(documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT ? 2 : 0);
}
// if (drawPinnedBottom && !messageObject.isOutOwner()) {
// totalHeight += AndroidUtilities.dp(documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT ? 1 : 0);
// }
if (namesOffset > 0) {
y = AndroidUtilities.dp(7);
totalHeight -= AndroidUtilities.dp(2);
@ -7604,6 +7637,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (replySelector != null) {
replySelector.setState(new int[]{});
}
if (topicButton != null) {
topicButton.resetClick();
}
if (pressedEmoji != null) {
// hadLongPress = true;
// if (delegate.didPressAnimatedEmoji(pressedEmoji)) {
@ -7744,6 +7780,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
);
}
public void invalidateOutbounds() {
if (delegate == null || !delegate.canDrawOutboundsContent()) {
if (getParent() instanceof View) {
((View) getParent()).invalidate();
}
} else {
super.invalidate();
}
}
@Override
public void invalidate() {
if (currentMessageObject == null) {
@ -8569,9 +8615,6 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
timeX -= getExtraTimeX();
// if (transitionParams != null && !transitionParams.shouldAnimateTimeX) {
// transitionParams.lastTimeX = timeX;
// }
if ((currentMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
viewsLayout = new StaticLayout(currentViewsString, Theme.chat_timePaint, viewsTextWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
@ -9762,13 +9805,13 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
reactionsLayoutInBubble.y = getBackgroundDrawableBottom() - AndroidUtilities.dp(10) - reactionsLayoutInBubble.height;
reactionsLayoutInBubble.y -= (drawCommentButton ? AndroidUtilities.dp(43) : 0);
if (hasNewLineForTime) {
if (hasNewLineForTime && !(drawForwardedName && hasLinkPreview && documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO)) {
reactionsLayoutInBubble.y -= AndroidUtilities.dp(16);
}
if (captionLayout != null && ((currentMessageObject.type != MessageObject.TYPE_VOICE && !(currentMessageObject.isOut() && drawForwardedName && !drawPhotoImage) && !(currentMessageObject.type == MessageObject.TYPE_FILE && drawPhotoImage)) || (currentPosition != null && currentMessagesGroup != null))) {
reactionsLayoutInBubble.y -= AndroidUtilities.dp(14);
}
reactionsLayoutInBubble.y = reactionsLayoutInBubble.y + reactionsLayoutInBubble.positionOffsetY;
reactionsLayoutInBubble.y += reactionsLayoutInBubble.positionOffsetY;
}
if (reactionsLayoutInBubble.isSmall && !reactionsLayoutInBubble.isEmpty) {
int timeYOffset;
@ -9849,7 +9892,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
linkPreviewY += currentMessageObject.textHeight + AndroidUtilities.dp(4);
}
if (drawPhotoImage && drawInstantView && drawInstantViewType != 9 && drawInstantViewType != 13 && drawInstantViewType != 11 && drawInstantViewType != 1 || drawInstantViewType == 6 && imageBackgroundColor != 0) {
if (drawPhotoImage && drawInstantView && drawInstantViewType != 9 && drawInstantViewType != 2 && drawInstantViewType != 13 && drawInstantViewType != 11 && drawInstantViewType != 1 || drawInstantViewType == 6 && imageBackgroundColor != 0) {
if (linkPreviewY != startY) {
linkPreviewY += AndroidUtilities.dp(2);
}
@ -9982,7 +10025,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
linkPreviewY += descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1);
}
if (drawPhotoImage && (!drawInstantView || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 1)) {
if (drawPhotoImage && (!drawInstantView || drawInstantViewType == 9 || drawInstantViewType == 2 || drawInstantViewType == 11 || drawInstantViewType == 13 || drawInstantViewType == 1)) {
if (linkPreviewY != startY) {
linkPreviewY += AndroidUtilities.dp(2);
}
@ -10407,7 +10450,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (currentMessageObject == null || currentMessageObject != null && currentMessageObject.hasExtendedMedia()) {
return MediaActionDrawable.ICON_NONE;
}
if (documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND && currentMessageObject.isVoiceTranscriptionOpen() && (currentMessageObject != null && currentMessageObject.attachPathExists && !TextUtils.isEmpty(currentMessageObject.messageOwner.attachPath) || currentMessageObject.mediaExists)) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND && currentMessageObject.isVoiceTranscriptionOpen() && canStreamVideo) {
if (buttonState == 1 || buttonState == 4) {
return MediaActionDrawable.ICON_PAUSE;
}
@ -10592,7 +10635,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
boolean fromBot = currentMessageObject.messageOwner.params != null && currentMessageObject.messageOwner.params.containsKey("query_id");
if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC || documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND && currentMessageObject != null && currentMessageObject.isVoiceTranscriptionOpen() && fileExists) {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO || documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC || documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND && currentMessageObject != null && currentMessageObject.isVoiceTranscriptionOpen() && canStreamVideo) {
if (currentMessageObject.isOut() && (currentMessageObject.isSending() && !currentMessageObject.isForwarded() || currentMessageObject.isEditing() && currentMessageObject.isEditingMedia()) || currentMessageObject.isSendError() && fromBot) {
if (!TextUtils.isEmpty(currentMessageObject.messageOwner.attachPath)) {
DownloadController.getInstance(currentAccount).addLoadingFileObserver(currentMessageObject.messageOwner.attachPath, currentMessageObject, this);
@ -11968,6 +12011,42 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
drawTopic = false;
if (!isThreadChat && !pinnedTop && (MessageObject.getTopicId(messageObject.messageOwner) != 0 || messageObject.replyToForumTopic != null)) {
if (currentPosition == null || currentPosition.minY == 0) {
int topicId = MessageObject.getTopicId(messageObject.messageOwner);
TLRPC.TL_forumTopic topic = messageObject.replyToForumTopic == null ? MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-messageObject.getDialogId(), topicId) : messageObject.replyToForumTopic;
if (topic != null) {
drawTopic = true;
int maxWidth = getMaxNameWidth();
if (!messageObject.shouldDrawWithoutBackground()) {
maxWidth -= AndroidUtilities.dp(10);
} else if (messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
maxWidth += AndroidUtilities.dp(13 + 35);
} else if (messageObject.isAnyKindOfSticker()) {
maxWidth += AndroidUtilities.dp(25);
}
if (topicButton == null) {
topicButton = new MessageTopicButton(getContext(), resourcesProvider) {
@Override
protected void onClick() {
if (delegate != null) {
delegate.didPressTopicButton(ChatMessageCell.this);
}
}
};
}
namesOffset += topicButton.set(this, messageObject, topic, maxWidth);
}
}
}
if (!drawTopic && topicButton != null) {
topicButton.onDetached(this);
topicButton = null;
}
if ((!isThreadChat || messageObject.getReplyTopMsgId() != 0) && messageObject.hasValidReplyMessageObject() || messageObject.messageOwner.fwd_from != null && messageObject.isDice()) {
if (currentPosition == null || currentPosition.minY == 0) {
if (!messageObject.isAnyKindOfSticker() && messageObject.type != MessageObject.TYPE_ROUND_VIDEO) {
@ -12087,16 +12166,12 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
mess = mess.replace('\n', ' ');
stringFinalText = Emoji.replaceEmoji(mess, Theme.chat_replyTextPaint.getFontMetricsInt(), AndroidUtilities.dp(14), false);
if (messageObject.replyMessageObject.messageOwner != null) {
stringFinalText = MessageObject.replaceAnimatedEmoji(stringFinalText, messageObject.replyMessageObject.messageOwner.entities, Theme.chat_replyTextPaint.getFontMetricsInt());
stringFinalText = MessageObject.replaceAnimatedEmoji(stringFinalText, messageObject.replyMessageObject.messageOwner.entities, Theme.chat_replyTextPaint.getFontMetricsInt(), true);
}
stringFinalText = TextUtils.ellipsize(stringFinalText, Theme.chat_replyTextPaint, maxWidth, TextUtils.TruncateAt.END);
if (stringFinalText instanceof Spannable && messageObject.replyMessageObject.messageOwner != null) {
MediaDataController.addTextStyleRuns(messageObject.replyMessageObject.messageOwner.entities, messageObject.replyMessageObject.caption, (Spannable) stringFinalText);
}
} else if (messageObject.replyMessageObject != null && messageObject.replyMessageObject.messageOwner != null && messageObject.replyMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate) {
TLRPC.TL_messageActionTopicCreate topicCreate = (TLRPC.TL_messageActionTopicCreate) messageObject.replyMessageObject.messageOwner.action;
TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(-messageObject.getDialogId(), messageObject.replyMessageObject.messageOwner.id);
stringFinalText = ForumUtilities.getTopicSpannedName(topic, Theme.chat_replyTextPaint);
} else if (messageObject.replyMessageObject != null && messageObject.replyMessageObject.messageText != null && messageObject.replyMessageObject.messageText.length() > 0) {
String mess = messageObject.replyMessageObject.messageText.toString();
if (mess.length() > 150) {
@ -12105,7 +12180,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
mess = mess.replace('\n', ' ');
stringFinalText = Emoji.replaceEmoji(mess, Theme.chat_replyTextPaint.getFontMetricsInt(), AndroidUtilities.dp(14), false);
if (messageObject.replyMessageObject.messageOwner != null) {
stringFinalText = MessageObject.replaceAnimatedEmoji(stringFinalText, messageObject.replyMessageObject.messageOwner.entities, Theme.chat_replyTextPaint.getFontMetricsInt());
stringFinalText = MessageObject.replaceAnimatedEmoji(stringFinalText, messageObject.replyMessageObject.messageOwner.entities, Theme.chat_replyTextPaint.getFontMetricsInt(), true);
}
stringFinalText = TextUtils.ellipsize(stringFinalText, Theme.chat_replyTextPaint, maxWidth, TextUtils.TruncateAt.END);
if (stringFinalText instanceof Spannable) {
@ -12189,8 +12264,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
replyTextOffset = (int) replyTextLayout.getLineLeft(0);
}
replySpoilers.clear();
if (getMessageObject().replyMessageObject != null && !getMessageObject().replyMessageObject.isSpoilersRevealed)
if (getMessageObject().replyMessageObject != null && !getMessageObject().replyMessageObject.isSpoilersRevealed) {
SpoilerEffect.addSpoilers(this, replyTextLayout, replySpoilersPool, replySpoilers);
}
animatedEmojiReplyStack = AnimatedEmojiSpan.update(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, this, false, animatedEmojiReplyStack, replyTextLayout);
}
} catch (Exception e) {
@ -12198,7 +12274,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
} else if (!isThreadChat && messageObject.getReplyMsgId() != 0) {
if (!(messageObject.replyMessageObject != null && messageObject.replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty)) {
if (!(messageObject.replyMessageObject != null && (messageObject.replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty || messageObject.replyMessageObject.messageOwner != null && messageObject.replyMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionTopicCreate))) {
if (!messageObject.isAnyKindOfSticker() && messageObject.type != MessageObject.TYPE_ROUND_VIDEO) {
namesOffset += AndroidUtilities.dp(14) + (Theme.chat_replyTextPaint.getTextSize() + Theme.chat_replyNamePaint.getTextSize());
if (messageObject.type != MessageObject.TYPE_TEXT) {
@ -12533,6 +12609,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
replyStartY = forwardNameY + forwardHeight + AndroidUtilities.dp(6);
} else {
replyStartY = AndroidUtilities.dp(12);
if (drawTopic && topicButton != null) {
replyStartY += topicButton.height() + AndroidUtilities.dp(10);
}
}
} else {
if (currentMessageObject.isOutOwner()) {
@ -12546,6 +12625,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
forwardHeight = AndroidUtilities.dp(4) + (int) Theme.chat_forwardNamePaint.getTextSize() * 2;
replyStartY = AndroidUtilities.dp(12) + (drawNameLayout && nameLayout != null ? AndroidUtilities.dp(6) + (int) Theme.chat_namePaint.getTextSize() : 0) + (drawForwardedName && forwardedNameLayout[0] != null ? AndroidUtilities.dp(4) + forwardHeight : 0);
if (drawTopic && topicButton != null) {
replyStartY += topicButton.height() + AndroidUtilities.dp(5);
}
}
}
if (currentPosition == null && !transitionParams.animateBackgroundBoundsInner && !(enterTransitionInProgress && !currentMessageObject.isVoice())) {
@ -13086,6 +13168,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
drawSideButton != 0 ||
drawNameLayout && nameLayout != null && currentNameStatusDrawable != null && currentNameStatusDrawable.getDrawable() != null ||
animatedEmojiStack != null && !animatedEmojiStack.holders.isEmpty() ||
drawTopic && topicButton != null && (currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0) ||
currentMessagesGroup == null &&
(transitionParams.animateReplaceCaptionLayout && transitionParams.animateChangeProgress != 1f || transitionParams.animateChangeProgress != 1.0f && transitionParams.animateMessageText) &&
transitionParams.animateOutAnimateEmoji != null && !transitionParams.animateOutAnimateEmoji.holders.isEmpty()
@ -13161,6 +13244,31 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
currentNameStatusDrawable.draw(canvas);
}
if (drawTopic && topicButton != null && (currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0)) {
float replyForwardAlpha = 1f;
if (isRoundVideo && !hasLinkPreview) {
replyForwardAlpha *= 1f - getVideoTranscriptionProgress();
if (transitionParams.animatePlayingRound) {
if (isPlayingRound) {
replyForwardAlpha *= (1f - transitionParams.animateChangeProgress);
} else {
replyForwardAlpha *= transitionParams.animateChangeProgress;
}
} else if (isPlayingRound) {
replyForwardAlpha = 0;
}
}
float animatingAlpha = 1f;
if (transitionParams.animateForwardedLayout) {
if (!currentMessageObject.needDrawForwarded()) {
animatingAlpha = 1f - transitionParams.animateChangeProgress;
} else {
animatingAlpha = transitionParams.animateChangeProgress;
}
}
topicButton.drawOutbounds(canvas, animatingAlpha * replyForwardAlpha);
}
if (!transitionParams.transitionBotButtons.isEmpty() && transitionParams.animateBotButtonsChanged) {
drawBotButtons(canvas, transitionParams.transitionBotButtons, 1f - transitionParams.animateChangeProgress);
}
@ -13515,13 +13623,21 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
public boolean hasNameLayout() {
return drawNameLayout && nameLayout != null ||
drawForwardedName && forwardedNameLayout[0] != null && forwardedNameLayout[1] != null && (currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0) ||
replyNameLayout != null;
replyNameLayout != null || drawTopic;
}
public boolean isDrawNameLayout() {
return drawNameLayout && nameLayout != null;
}
public boolean isDrawTopic() {
return drawTopic;
}
public float getDrawTopicHeight() {
return topicButton != null ? topicButton.height() : 0;
}
public boolean isAdminLayoutChanged() {
return !TextUtils.equals(lastPostAuthor, currentMessageObject.messageOwner.post_author);
}
@ -13739,7 +13855,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
if (!currentMessageObject.isVoiceTranscriptionOpen() && (currentMessageObject.isOutOwner() && currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO && transitionParams.animatePlayingRound || isPlayingRound)) {
forwardNameXLocal -= AndroidUtilities.dp(78) * (isPlayingRound ? transitionParams.animateChangeProgress : (1f - transitionParams.animateChangeProgress));
}
forwardNameY = AndroidUtilities.dp(12);
forwardNameY = AndroidUtilities.dp(12) + (drawTopic && topicButton != null ? topicButton.height() + AndroidUtilities.dp(14) : 0);
forwardHeight = AndroidUtilities.dp(4) + (int) Theme.chat_forwardNamePaint.getTextSize() * 2;
int backWidth = forwardedNameWidthLocal + AndroidUtilities.dp(14);
@ -13771,7 +13887,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2);
}
} else {
forwardNameY = AndroidUtilities.dp(10) + (drawNameLayout ? AndroidUtilities.dp(5) + (int) Theme.chat_namePaint.getTextSize() : 0);
forwardNameY = AndroidUtilities.dp(10) + (drawNameLayout ? AndroidUtilities.dp(5) + (int) Theme.chat_namePaint.getTextSize() : 0) + (drawTopic && topicButton != null ? topicButton.height() + AndroidUtilities.dp(7 + (currentMessageObject.type != MessageObject.TYPE_TEXT ? 3 : 0)) : 0);
forwardHeight = AndroidUtilities.dp(4) + (int) Theme.chat_forwardNamePaint.getTextSize() * 2;
if (currentMessageObject.isOutOwner()) {
if (hasPsaHint) {
@ -13875,6 +13991,37 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
}
if (drawTopic && topicButton != null && (animatingAlpha > 0 && replyForwardAlpha > 0) && (currentPosition == null || currentPosition.minY == 0 && currentPosition.minX == 0)) {
float x, y;
if (currentMessageObject.shouldDrawWithoutBackground()) {
if (currentMessageObject.isOutOwner()) {
x = AndroidUtilities.dp(23);
if (isPlayingRound) {
x -= (AndroidUtilities.roundPlayingMessageSize - AndroidUtilities.roundMessageSize);
}
} else if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
x = backgroundDrawableLeft + backgroundDrawableRight + AndroidUtilities.dp(4);
} else {
x = backgroundDrawableLeft + backgroundDrawableRight + AndroidUtilities.dp(17);
}
y = AndroidUtilities.dp(12);
x -= AndroidUtilities.dp(8);
} else {
if (currentMessageObject.isOutOwner()) {
x = backgroundDrawableLeft + AndroidUtilities.dp(12) + getExtraTextX();
} else {
if (mediaBackground) {
x = backgroundDrawableLeft + AndroidUtilities.dp(12) + getExtraTextX();
} else {
x = backgroundDrawableLeft + AndroidUtilities.dp(drawPinnedBottom ? 12 : 18) + getExtraTextX();
}
}
x -= AndroidUtilities.dp(2.33f);
y = AndroidUtilities.dp(12) + (drawNameLayout && nameLayout != null ? AndroidUtilities.dp(6) + (int) Theme.chat_namePaint.getTextSize() : 0);
}
topicButton.draw(canvas, x, y, animatingAlpha * replyForwardAlpha);
}
if (hasReply) {
float replyStartX = this.replyStartX;
float replyStartY = this.replyStartY;
@ -13961,14 +14108,14 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
(int) (replyStartY + replyHeight + AndroidUtilities.dp(7))
);
} else {
if (drawNameLayout || (drawForwardedName && forwardedNameLayout[0] != null)) {
if (drawTopic || drawNameLayout || (drawForwardedName && forwardedNameLayout[0] != null)) {
leftRad = bottomRad;
} else if (currentMessageObject.isOutOwner() || !drawPinnedTop) {
leftRad = AndroidUtilities.dp(SharedConfig.bubbleRadius / 3f);
} else {
leftRad = AndroidUtilities.dp(Math.min(6, SharedConfig.bubbleRadius) / 3f);
}
if (drawNameLayout || (drawForwardedName && forwardedNameLayout[0] != null)) {
if (drawTopic || drawNameLayout || (drawForwardedName && forwardedNameLayout[0] != null)) {
rightRad = bottomRad;
} else if (!currentMessageObject.isOutOwner() || !drawPinnedTop) {
rightRad = AndroidUtilities.dp(SharedConfig.bubbleRadius / 3f);
@ -14691,8 +14838,16 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
paint = getThemedPaint(Theme.key_paint_chatTimeBackground);
}
int oldAlpha = paint.getAlpha();
paint.setAlpha((int) (oldAlpha * timeAlpha * alpha));
float oldAlpha3 = alpha;
Theme.chat_timePaint.setAlpha((int) (255 * timeAlpha * alpha));
if (currentMessageObject != null && currentMessageObject.type == MessageObject.TYPE_GEO) {
float progress = photoImage.isCrossfadingWithOldImage() ? 1 : photoImage.getCurrentAlpha();
if (!photoImage.hasNotThumb()) {
progress = 0;
}
alpha = AndroidUtilities.lerp(0.35f, 1f, progress);
}
paint.setAlpha((int) (oldAlpha * timeAlpha * alpha));
int r;
if (documentAttachType != DOCUMENT_ATTACH_TYPE_ROUND && documentAttachType != DOCUMENT_ATTACH_TYPE_STICKER && currentMessageObject.type != MessageObject.TYPE_EMOJIS) {
@ -14723,6 +14878,8 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
paint.setAlpha(oldAlpha);
alpha = oldAlpha3;
float additionalX = -timeLayout.getLineLeft(0);
if (reactionsLayoutInBubble.isSmall) {
updateReactionLayoutPosition();
@ -14800,7 +14957,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
reactionsLayoutInBubble.draw(canvas, transitionParams.animateChangeProgress, null);
}
if (ChatObject.isChannel(currentChat) && !currentChat.megagroup || (currentMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0 || (repliesLayout != null || transitionParams.animateReplies) || (isPinned || transitionParams.animatePinned)) {
additionalX += this.timeWidth - timeLayout.getLineWidth(0);
additionalX += timeWidth - timeLayout.getLineWidth(0);
if (reactionsLayoutInBubble.isSmall && !reactionsLayoutInBubble.isEmpty) {
additionalX -= reactionsLayoutInBubble.width;
}
@ -15787,9 +15944,9 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
float progress = photoImage.isCrossfadingWithOldImage() ? 1 : photoImage.getCurrentAlpha();
if (progress > 0 && photoImage.hasNotThumb()) {
if (progress > 0 && (photoImage.hasNotThumb() || photoImage.isCrossfadingWithOldImage())) {
int cx = (int) (photoImage.getImageX() + photoImage.getImageWidth() / 2 - AndroidUtilities.dp(31));
cy = (int) (photoImage.getImageY() + photoImage.getImageHeight() / 2 - AndroidUtilities.dp(38) - AndroidUtilities.dp(16) * (1f - CubicBezierInterpolator.EASE_OUT_BACK.getInterpolation(photoImage.getCurrentAlpha())));
cy = (int) (photoImage.getImageY() + photoImage.getImageHeight() / 2 - AndroidUtilities.dp(38) - AndroidUtilities.dp(16) * (1f - CubicBezierInterpolator.EASE_OUT_BACK.getInterpolation(progress)));
setDrawableBounds(Theme.chat_msgAvatarLiveLocationDrawable, cx, cy);
Theme.chat_msgAvatarLiveLocationDrawable.setAlpha((int) (255 * Math.min(1, progress * 5)));
@ -16260,7 +16417,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
}
boolean restore = false;
boolean on = false;
if (currentMessageObject != null && currentMessageObject.isRoundVideo() && (getVideoTranscriptionProgress() <= 0 && !currentMessageObject.mediaExists)) {
if (currentMessageObject != null && currentMessageObject.isRoundVideo() && !currentMessageObject.mediaExists) {
radialProgress.setProgressRect(
photoImage.getImageX() + (photoImage.getImageWidth() - radialProgress.getRadius()) / 2f,
photoImage.getImageY() + (photoImage.getImageHeight() - radialProgress.getRadius()) / 2f,
@ -18092,7 +18249,7 @@ public class ChatMessageCell extends BaseCell implements SeekBar.SeekBarDelegate
animateTimeWidth = lastTimeWidth;
changed = true;
} else if (timeDrawablesIsChanged || Math.abs(timeX - lastTimeX) > 1) {
shouldAnimateTimeX = true ;
shouldAnimateTimeX = true;
animateTimeWidth = lastTimeWidth;
animateFromTimeX = lastTimeX;
animateFromTimeXViews = lastTimeXViews;

View File

@ -63,6 +63,7 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.browser.Browser;
import org.telegram.messenger.UserConfig;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
@ -83,7 +84,9 @@ import org.telegram.ui.Components.CircularProgressDrawable;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.LinkSpanDrawable;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.Components.TypefaceSpan;
import java.util.ArrayList;
import java.util.List;
@ -588,19 +591,19 @@ public class ChangeUsernameActivity extends BaseFragment {
}
private UsernameHelpCell helpCell;
private TextView statusTextView;
private LinkSpanDrawable.LinksTextView statusTextView;
private class UsernameHelpCell extends FrameLayout {
private TextView text1View;
private TextView text2View;
private LinkSpanDrawable.LinksTextView text2View;
public UsernameHelpCell(Context context) {
super(context);
helpCell = this;
setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(10), AndroidUtilities.dp(21), AndroidUtilities.dp(17));
setPadding(AndroidUtilities.dp(18), AndroidUtilities.dp(10), AndroidUtilities.dp(18), AndroidUtilities.dp(17));
setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
setClipChildren(false);
@ -610,13 +613,50 @@ public class ChangeUsernameActivity extends BaseFragment {
text1View.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
text1View.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText));
text1View.setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkSelection));
text1View.setPadding(AndroidUtilities.dp(3), 0, AndroidUtilities.dp(3), 0);
text2View = statusTextView = new TextView(context);
text2View = statusTextView = new LinkSpanDrawable.LinksTextView(context) {
@Override
public void setText(CharSequence text, BufferType type) {
if (text != null) {
SpannableStringBuilder tagsString = AndroidUtilities.replaceTags(text.toString());
int index = tagsString.toString().indexOf('\n');
if (index >= 0) {
tagsString.replace(index, index + 1, " ");
tagsString.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TypefaceSpan[] spans = tagsString.getSpans(0, tagsString.length(), TypefaceSpan.class);
for (int i = 0; i < spans.length; ++i) {
tagsString.setSpan(
new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
Browser.openUrl(getContext(), "https://fragment.com/username/" + username);
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
},
tagsString.getSpanStart(spans[i]),
tagsString.getSpanEnd(spans[i]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
tagsString.removeSpan(spans[i]);
}
text = tagsString;
}
super.setText(text, type);
}
};
text2View.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
text2View.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8));
text2View.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
text2View.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText));
text2View.setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkSelection));
text2View.setPadding(AndroidUtilities.dp(3), 0, AndroidUtilities.dp(3), 0);
addView(text1View, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP));
addView(text2View, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP));
@ -1123,7 +1163,7 @@ public class ChangeUsernameActivity extends BaseFragment {
}
}
}
if (name == null || name.length() < 5) {
if (name == null || name.length() < 4) {
if (alert) {
AlertsCreator.showSimpleAlert(this, LocaleController.getString("UsernameInvalidShort", R.string.UsernameInvalidShort));
} else {
@ -1199,9 +1239,23 @@ public class ChangeUsernameActivity extends BaseFragment {
lastNameAvailable = true;
} else {
if (statusTextView != null) {
statusTextView.setText(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
statusTextView.setTag(Theme.key_windowBackgroundWhiteRedText4);
statusTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
if (error != null && "USERNAME_INVALID".equals(error.text) && req.username.length() == 4) {
statusTextView.setText(LocaleController.getString("UsernameInvalidShort", R.string.UsernameInvalidShort));
statusTextView.setTag(Theme.key_windowBackgroundWhiteRedText4);
statusTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
} else if (error != null && "USERNAME_PURCHASE_AVAILABLE".equals(error.text)) {
if (req.username.length() == 4) {
statusTextView.setText(LocaleController.getString("UsernameInvalidShortPurchase", R.string.UsernameInvalidShortPurchase));
} else {
statusTextView.setText(LocaleController.getString("UsernameInUsePurchase", R.string.UsernameInUsePurchase));
}
statusTextView.setTag(Theme.key_windowBackgroundWhiteGrayText8);
statusTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8));
} else {
statusTextView.setText(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
statusTextView.setTag(Theme.key_windowBackgroundWhiteRedText4);
statusTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
}
if (helpCell != null) {
helpCell.update();
}
@ -1268,6 +1322,15 @@ public class ChangeUsernameActivity extends BaseFragment {
}
finishFragment();
});
} else if ("USERNAME_PURCHASE_AVAILABLE".equals(error.text) || "USERNAME_INVALID".equals(error.text)) {
AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e(e);
}
shakeIfOff();
});
} else {
AndroidUtilities.runOnUIThread(() -> {
try {

View File

@ -25,8 +25,13 @@ import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
@ -37,7 +42,8 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewAnimator;
import androidx.annotation.NonNull;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
@ -47,6 +53,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.browser.Browser;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
@ -63,20 +70,26 @@ import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TextBlockCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CircularProgressDrawable;
import org.telegram.ui.Components.CrossfadeDrawable;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.EditTextEmoji;
import org.telegram.ui.Components.ImageUpdater;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.EditTextEmoji;
import org.telegram.ui.Components.ImageUpdater;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.LinkActionView;
import org.telegram.ui.Components.LinkSpanDrawable;
import org.telegram.ui.Components.Premium.LimitReachedBottomSheet;
import org.telegram.ui.Components.RLottieDrawable;
import org.telegram.ui.Components.RLottieImageView;
import org.telegram.ui.Components.RadialProgressView;
import org.telegram.ui.Components.SizeNotifierFrameLayout;
import org.telegram.ui.Components.TypefaceSpan;
import java.util.ArrayList;
@ -787,11 +800,50 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC
permanentLinkView.setUsers(0, null);
privateContainer.addView(permanentLinkView);
checkTextView = new TextView(context);
checkTextView = new LinkSpanDrawable.LinksTextView(context) {
@Override
public void setText(CharSequence text, BufferType type) {
if (text != null) {
SpannableStringBuilder tagsString = AndroidUtilities.replaceTags(text.toString());
int index = tagsString.toString().indexOf('\n');
if (index >= 0) {
tagsString.replace(index, index + 1, " ");
tagsString.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TypefaceSpan[] spans = tagsString.getSpans(0, tagsString.length(), TypefaceSpan.class);
final String username = descriptionTextView == null || descriptionTextView.getText() == null ? "" : descriptionTextView.getText().toString();
for (int i = 0; i < spans.length; ++i) {
tagsString.setSpan(
new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
Browser.openUrl(getContext(), "https://fragment.com/username/" + username);
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
},
tagsString.getSpanStart(spans[i]),
tagsString.getSpanEnd(spans[i]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
tagsString.removeSpan(spans[i]);
}
text = tagsString;
}
super.setText(text, type);
}
};
checkTextView.setLinkTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkText));
checkTextView.setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteLinkSelection));
checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
checkTextView.setVisibility(View.GONE);
linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7));
checkTextView.setPadding(AndroidUtilities.dp(3), 0, AndroidUtilities.dp(3), 0);
linkContainer.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 18, 3, 18, 7));
typeInfoCell = new TextInfoPrivacyCell(context);
typeInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
@ -1176,7 +1228,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC
}
}
}
if (name == null || name.length() < 5) {
if (name == null || name.length() < 4) {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
checkTextView.setTag(Theme.key_windowBackgroundWhiteRedText4);
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
@ -1206,14 +1258,24 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGreenText));
lastNameAvailable = true;
} else {
if (error != null && error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) {
if (error != null && "USERNAME_INVALID".equals(error.text) && req.username.length() == 4) {
checkTextView.setText(LocaleController.getString("UsernameInvalidShort", R.string.UsernameInvalidShort));
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
} else if (error != null && "USERNAME_PURCHASE_AVAILABLE".equals(error.text)) {
if (req.username.length() == 4) {
checkTextView.setText(LocaleController.getString("UsernameInvalidShortPurchase", R.string.UsernameInvalidShortPurchase));
} else {
checkTextView.setText(LocaleController.getString("UsernameInUsePurchase", R.string.UsernameInUsePurchase));
}
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8));
} else if (error != null && "CHANNELS_ADMIN_PUBLIC_TOO_MUCH".equals(error.text)) {
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
canCreatePublic = false;
showPremiumIncreaseLimitDialog();
} else {
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
checkTextView.setText(LocaleController.getString("LinkInUse", R.string.LinkInUse));
}
checkTextView.setTag(Theme.key_windowBackgroundWhiteRedText4);
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
lastNameAvailable = false;
}
}

View File

@ -67,6 +67,7 @@ import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.util.Pair;
import android.util.Property;
import android.util.SparseArray;
import android.util.SparseIntArray;
@ -206,6 +207,7 @@ import org.telegram.ui.Components.Bulletin;
import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.ChatActivityEnterTopView;
import org.telegram.ui.Components.ChatActivityEnterView;
import org.telegram.ui.Components.ChatActivityInterface;
import org.telegram.ui.Components.ChatAttachAlert;
import org.telegram.ui.Components.ChatAttachAlertDocumentLayout;
import org.telegram.ui.Components.ChatAvatarContainer;
@ -332,11 +334,14 @@ import tw.nekomimi.nekogram.utils.ProxyUtil;
import tw.nekomimi.nekogram.utils.TelegramUtil;
@SuppressWarnings("unchecked")
public class ChatActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate, LocationActivity.LocationActivityDelegate, ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate, FragmentContextView.ChatActivityInterface, FloatingDebugProvider {
public class ChatActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate, LocationActivity.LocationActivityDelegate, ChatAttachAlertDocumentLayout.DocumentSelectActivityDelegate, ChatActivityInterface, FloatingDebugProvider {
private final static boolean PULL_DOWN_BACK_FRAGMENT = false;
private final static boolean DISABLE_PROGRESS_VIEW = true;
private final static int SKELETON_DISAPPEAR_MS = 200;
private static int SKELETON_LIGHT_OVERLAY_ALPHA = 22;
private static float SKELETON_SATURATION = 1.4f;
public final static int DEBUG_SHARE_ALERT_MODE_NORMAL = 0,
DEBUG_SHARE_ALERT_MODE_LESS = 1,
DEBUG_SHARE_ALERT_MODE_MORE = 2;
@ -415,6 +420,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private ActionBarMenuSubItem clearHistoryItem;
private ActionBarMenuSubItem viewAsTopics;
private ActionBarMenuSubItem closeTopicItem;
private ActionBarMenuSubItem openForumItem;
private ClippingImageView animatingImageView;
public RecyclerListView chatListView;
private ChatListItemAnimator chatListItemAnimator;
@ -572,6 +578,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private int reportType = -1;
private MessageObject threadMessageObject;
private MessageObject topicStarterMessageObject;
private boolean threadMessageVisible = true;
private ArrayList<MessageObject> threadMessageObjects;
private MessageObject replyMessageHeaderObject;
@ -743,6 +750,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private int lastSkeletonCount;
private int lastSkeletonMessageCount;
private Paint skeletonPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint skeletonServicePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ColorMatrix skeletonColorMatrix = new ColorMatrix();
private Theme.MessageDrawable.PathDrawParams skeletonBackgroundCacheParams = new Theme.MessageDrawable.PathDrawParams();
private Theme.MessageDrawable skeletonBackgroundDrawable = new Theme.MessageDrawable(Theme.MessageDrawable.TYPE_TEXT, false, false, this::getThemedColor);
private long skeletonLastUpdateTime;
@ -753,6 +762,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private int skeletonColor0;
private int skeletonColor1;
private Paint skeletonOutlinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Matrix skeletonOutlineMatrix = new Matrix();
private LinearGradient skeletonOutlineGradient;
{
skeletonOutlinePaint.setStyle(Paint.Style.STROKE);
skeletonOutlinePaint.setStrokeWidth(AndroidUtilities.dp(1));
}
private boolean premiumInvoiceBot;
private boolean showScrollToMessageError;
private int startLoadFromMessageId;
@ -1103,7 +1121,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override
public List<FloatingDebugController.DebugItem> onGetDebugItems() {
List<FloatingDebugController.DebugItem> items = new ArrayList<>();
if (currentChat != null && ChatObject.isChannel(currentChat)) {
if (ChatObject.isChannel(currentChat)) {
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugShareAlert)));
String mode;
switch (shareAlertDebugMode) {
default:
@ -1123,6 +1142,33 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugShareAlertTopicsSlowMotion), ()-> shareAlertDebugTopicsSlowMotion = !shareAlertDebugTopicsSlowMotion));
}
if (currentUser == null) {
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugMessageSkeletons)));
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugMessageSkeletonsLightOverlayAlpha), 0, 255, new AnimationProperties.FloatProperty("") {
@Override
public void setValue(Object object, float value) {
SKELETON_LIGHT_OVERLAY_ALPHA = (int) value;
}
@Override
public Object get(Object object) {
return (float) SKELETON_LIGHT_OVERLAY_ALPHA;
}
}));
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugMessageSkeletonsSaturation), 1f, 10f, new AnimationProperties.FloatProperty("") {
@Override
public void setValue(Object object, float value) {
SKELETON_SATURATION = value;
skeletonColorMatrix.setSaturation(value);
skeletonServicePaint.setColorFilter(new ColorMatrixColorFilter(skeletonColorMatrix));
}
@Override
public Object get(Object object) {
return SKELETON_SATURATION;
}
}));
}
return items;
}
@ -1253,6 +1299,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private final static int search = 40;
private final static int topic_close = 60;
private final static int open_forum = 61;
private ActionBarMenuItem actionModeOtherItem; // NekoX
@ -1771,7 +1818,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else if (!forceHistoryEmpty) {
loading = true;
}
if (isThreadChat()) {
if (isThreadChat() && !isTopic) {
if (highlightMessageId == startLoadFromMessageId) {
needSelectFromMessageId = true;
}
@ -1785,11 +1832,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (startLoadFromMessageId == 0) {
SharedPreferences sharedPreferences = MessagesController.getNotificationsSettings(currentAccount);
int messageId = sharedPreferences.getInt("diditem" + dialog_id, 0);
int messageId = sharedPreferences.getInt("diditem" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()), 0);
if (messageId != 0) {
wasManualScroll = true;
loadingFromOldPosition = true;
startLoadFromMessageOffset = sharedPreferences.getInt("diditemo" + dialog_id, 0);
startLoadFromMessageOffset = sharedPreferences.getInt("diditemo" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()), 0);
startLoadFromMessageId = messageId;
}
} else {
@ -1833,7 +1880,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
waitingForLoad.add(lastLoadIndex);
if (startLoadFromDate != 0) {
getMessagesController().loadMessages(dialog_id, mergeDialogId, false, 30, 0, startLoadFromDate, true, 0, classGuid, 4, 0, chatMode, threadMessageId, replyMaxReadId, lastLoadIndex++, isTopic);
} else if (startLoadFromMessageId != 0 && (!isThreadChat() || startLoadFromMessageId == highlightMessageId)) {
} else if (startLoadFromMessageId != 0 && (!isThreadChat() || startLoadFromMessageId == highlightMessageId || isTopic)) {
startLoadFromMessageIdSaved = startLoadFromMessageId;
if (migrated_to != 0) {
mergeDialogId = migrated_to;
@ -2506,45 +2553,52 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
updateTopicButtons();
updateBottomOverlay();
updateTopPanel(true);
} else if (id == open_forum) {
TopicsFragment.prepareToSwitchAnimation(ChatActivity.this);
// Bundle bundle = new Bundle();
// bundle.putLong("chat_id", -dialog_id);
// presentFragment(new TopicsFragment(bundle));
} else {
nkbtn_onclick_actionbar(id);
}
}
});
View backButton = actionBar.getBackButton();
backButton.setOnLongClickListener(e -> {
scrimPopupWindow = BackButtonMenu.show(this, backButton, dialog_id, themeDelegate);
if (scrimPopupWindow != null) {
scrimPopupWindow.setOnDismissListener(() -> {
scrimPopupWindow = null;
menuDeleteItem = null;
scrimPopupWindowItems = null;
chatLayoutManager.setCanScrollVertically(true);
if (scrimPopupWindowHideDimOnDismiss) {
dimBehindView(false);
} else {
scrimPopupWindowHideDimOnDismiss = true;
backButton.setOnTouchListener(new LongPressListenerWithMovingGesture() {
@Override
public void onLongPress() {
scrimPopupWindow = BackButtonMenu.show(ChatActivity.this, backButton, dialog_id, getTopicId(), themeDelegate);
if (scrimPopupWindow != null) {
setSubmenu(scrimPopupWindow);
scrimPopupWindow.setOnDismissListener(() -> {
setSubmenu(null);
scrimPopupWindow = null;
menuDeleteItem = null;
scrimPopupWindowItems = null;
chatLayoutManager.setCanScrollVertically(true);
if (scrimPopupWindowHideDimOnDismiss) {
dimBehindView(false);
} else {
scrimPopupWindowHideDimOnDismiss = true;
}
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setAllowDrawCursor(true);
}
});
chatListView.stopScroll();
chatLayoutManager.setCanScrollVertically(false);
dimBehindView(backButton, 0.3f);
hideHints(false);
if (topUndoView != null) {
topUndoView.hide(true, 1);
}
if (undoView != null) {
undoView.hide(true, 1);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setAllowDrawCursor(true);
chatActivityEnterView.getEditField().setAllowDrawCursor(false);
}
});
chatListView.stopScroll();
chatLayoutManager.setCanScrollVertically(false);
dimBehindView(backButton, 0.3f);
hideHints(false);
if (topUndoView != null) {
topUndoView.hide(true, 1);
}
if (undoView != null) {
undoView.hide(true, 1);
}
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setAllowDrawCursor(false);
}
return true;
} else {
return false;
}
});
actionBar.setInterceptTouchEventListener((view, motionEvent) -> {
@ -3034,6 +3088,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
updateBotButtons();
}
}
if (ChatObject.isForum(currentChat) && isTopic) {
if (getParentLayout() != null && getParentLayout().getFragmentStack() != null) {
boolean hasMyForum = false;
for (int i = 0; i < getParentLayout().getFragmentStack().size(); ++i) {
BaseFragment fragment = getParentLayout().getFragmentStack().get(i);
if (fragment instanceof TopicsFragment && ((TopicsFragment) fragment).getDialogId() == dialog_id) {
hasMyForum = true;
break;
}
}
if (!hasMyForum) {
openForumItem = headerItem.addSubItem(open_forum, R.drawable.msg_discussion, LocaleController.getString("OpenAllTopics", R.string.OpenAllTopics), themeDelegate);
}
}
}
if (currentChat != null && forumTopic != null) {
closeTopicItem = headerItem.addSubItem(topic_close, R.drawable.msg_topic_close, LocaleController.getString("CloseTopic", R.string.CloseTopic), themeDelegate);
closeTopicItem.setVisibility(currentChat != null && ChatObject.canManageTopic(currentAccount, currentChat, forumTopic) && forumTopic != null && !forumTopic.closed ? View.VISIBLE : View.GONE);
@ -3213,6 +3283,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (mentionContainer != null) {
mentionContainer.onPanTransitionEnd();
}
if (voiceHintTextView != null && voiceHintTextView.getVisibility() == View.VISIBLE) {
voiceHintTextView.showForView(chatActivityEnterView.getAudioVideoButtonContainer(), false);
}
}
@Override
@ -3250,6 +3323,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
((DialogsActivity)mainFragment).setPanTranslationOffset(y);
}
}
if (voiceHintTextView != null && voiceHintTextView.getVisibility() == View.VISIBLE) {
voiceHintTextView.showForView(chatActivityEnterView.getAudioVideoButtonContainer(), false);
}
}
@Override
@ -3321,7 +3397,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else {
expandY = chatActivityEnterView.getY();
}
if (scrimView != null || chatActivityEnterView != null && chatActivityEnterView.isStickersExpanded() && ev.getY() < expandY) {
if ((scrimView != null && scrimView != actionBar.getBackButton()) || chatActivityEnterView != null && chatActivityEnterView.isStickersExpanded() && ev.getY() < expandY) {
return false;
}
@ -4537,6 +4613,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (textSelectionHelper != null && textSelectionHelper.isSelectionMode()) {
textSelectionHelper.invalidate();
}
isSkeletonVisible();
}
private void setGroupTranslationX(ChatMessageCell view, float dx) {
@ -5029,7 +5106,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
private boolean isSkeletonVisible() {
if (justCreatedTopic) {
if (justCreatedTopic || currentUser != null || !SharedConfig.animationsEnabled()) {
return false;
}
int childHeight = 0;
@ -5041,14 +5118,30 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
maxTop = top;
}
}
if (maxTop <= 0) {
checkDispatchHideSkeletons(true);
if (maxTop <= chatListViewPaddingTop) {
checkDispatchHideSkeletons(fragmentBeginToShow);
}
boolean visible = (!endReached[0] || mergeDialogId != 0 && !endReached[1] || messages.isEmpty()) && loading && maxTop > 0 && (messages.isEmpty() ? animateProgressViewTo : childHeight != 0);
boolean visible = (!endReached[0] || mergeDialogId != 0 && !endReached[1] || messages.isEmpty()) && loading && maxTop > chatListViewPaddingTop && (messages.isEmpty() ? animateProgressViewTo : childHeight != 0);
if (!visible && startMessageAppearTransitionMs == 0) {
checkDispatchHideSkeletons(fragmentBeginToShow);
}
if (SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_LOW && !fromPullingDownTransition && !fragmentBeginToShow) {
Drawable wallpaper = themeDelegate.getWallpaperDrawable();
if (fragmentView != null) {
wallpaper = ((SizeNotifierFrameLayout) fragmentView).getBackgroundImage();
}
if (wallpaper instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motion = (MotionBackgroundDrawable) wallpaper;
if (((MotionBackgroundDrawable) wallpaper).isIndeterminateAnimation() != visible) {
motion.setIndeterminateAnimation(visible);
motion.setIndeterminateSpeedScale(visible ? 1.5f : 1f);
motion.updateAnimation(true);
} else if (visible) {
motion.updateAnimation(false);
}
}
}
return visible || startMessageAppearTransitionMs != 0 && System.currentTimeMillis() - startMessageAppearTransitionMs <= SKELETON_DISAPPEAR_MS;
}
@ -5078,6 +5171,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
Paint servicePaint = getThemedPaint(Theme.key_paint_chatActionBackground);
if (skeletonServicePaint.getColor() != servicePaint.getColor()) {
skeletonServicePaint.setColor(servicePaint.getColor());
}
if (skeletonServicePaint.getShader() != servicePaint.getShader()) {
skeletonServicePaint.setShader(servicePaint.getShader());
skeletonColorMatrix.setSaturation(SKELETON_SATURATION);
skeletonServicePaint.setColorFilter(new ColorMatrixColorFilter(skeletonColorMatrix));
}
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
@ -5135,12 +5236,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
MessageObject.GroupedMessages group = ((ChatMessageCell) v).getCurrentMessagesGroup();
Rect bounds = ((ChatMessageCell) v).getCurrentBackgroundDrawable(true).getBounds();
int newTop = (int) (v.getTop() + bounds.top + (group != null ? group.transitionParams.top + group.transitionParams.offsetTop : 0));
int top = messages.size() <= 2 && isSkeletonVisible() ? AndroidUtilities.lerp(lastTop, newTop, v.getAlpha()) : v.getAlpha() == 1f ? newTop : lastTop;
int top = startMessageAppearTransitionMs == 0 && isSkeletonVisible() ? AndroidUtilities.lerp(lastTop, newTop, v.getAlpha()) : v.getAlpha() == 1f ? newTop : lastTop;
if (top < lastTop) {
lastTop = top;
}
} else if (v instanceof ChatActionCell) {
int top = messages.size() <= 2 && isSkeletonVisible() ? AndroidUtilities.lerp(lastTop, v.getTop(), v.getAlpha()) : v.getAlpha() == 1f ? v.getTop() : lastTop;
int top = startMessageAppearTransitionMs == 0 && isSkeletonVisible() ? AndroidUtilities.lerp(lastTop, v.getTop(), v.getAlpha()) : v.getAlpha() == 1f ? v.getTop() : lastTop;
if (top < lastTop) {
lastTop = top;
}
@ -5148,10 +5249,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
if (isSkeletonVisible()) {
boolean drawService = SharedConfig.getDevicePerformanceClass() != SharedConfig.PERFORMANCE_CLASS_LOW && Theme.hasGradientService();
boolean darkOverlay = ColorUtils.calculateLuminance(getThemedColor(Theme.key_windowBackgroundWhite)) <= 0.7f && Theme.hasGradientService();
boolean blackOverlay = ColorUtils.calculateLuminance(getThemedColor(Theme.key_windowBackgroundWhite)) <= 0.01f && Theme.hasGradientService();
if (drawService) {
Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() - contentPanTranslation);
}
int wasDarkenAlpha = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha();
if (blackOverlay) {
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (wasDarkenAlpha * 4f));
}
float topSkeletonAlpha = startMessageAppearTransitionMs != 0 ? 1f - (System.currentTimeMillis() - startMessageAppearTransitionMs) / (float) SKELETON_DISAPPEAR_MS : 1f;
int alpha = skeletonPaint.getAlpha();
int wasServiceAlpha = servicePaint.getAlpha();
servicePaint.setAlpha((int) (wasServiceAlpha * 0.4f * topSkeletonAlpha));
int wasServiceAlpha = skeletonServicePaint.getAlpha();
int wasOutlineAlpha = skeletonOutlinePaint.getAlpha();
skeletonServicePaint.setAlpha((int) (0xFF * topSkeletonAlpha));
skeletonPaint.setAlpha((int) (topSkeletonAlpha * alpha));
while (lastTop > blurredViewTopOffset) {
lastTop -= AndroidUtilities.dp(3f);
@ -5178,21 +5291,34 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
int bottom = skeleton.lastBottom;
skeletonBackgroundDrawable.setBounds(noAvatar ? AndroidUtilities.dp(3f) : AndroidUtilities.dp(51), bottom - skeleton.height, skeleton.width, bottom);
Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() + skeletonBackgroundDrawable.getBounds().top);
skeletonBackgroundDrawable.drawCached(canvas, skeletonBackgroundCacheParams, servicePaint);
if (drawService) {
skeletonBackgroundDrawable.drawCached(canvas, skeletonBackgroundCacheParams, skeletonServicePaint);
}
skeletonBackgroundDrawable.drawCached(canvas, skeletonBackgroundCacheParams, skeletonPaint);
if (darkOverlay) {
skeletonBackgroundDrawable.drawCached(canvas, skeletonBackgroundCacheParams, Theme.chat_actionBackgroundGradientDarkenPaint);
}
skeletonBackgroundDrawable.drawCached(canvas, skeletonBackgroundCacheParams, skeletonOutlinePaint);
if (!noAvatar) {
Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() + bottom - AndroidUtilities.dp(42));
canvas.drawCircle(AndroidUtilities.dp(48 - 21), bottom - AndroidUtilities.dp(21), AndroidUtilities.dp(21), servicePaint);
if (drawService) {
canvas.drawCircle(AndroidUtilities.dp(48 - 21), bottom - AndroidUtilities.dp(21), AndroidUtilities.dp(21), skeletonServicePaint);
}
canvas.drawCircle(AndroidUtilities.dp(48 - 21), bottom - AndroidUtilities.dp(21), AndroidUtilities.dp(21), skeletonPaint);
if (darkOverlay) {
canvas.drawCircle(AndroidUtilities.dp(48 - 21), bottom - AndroidUtilities.dp(21), AndroidUtilities.dp(21), Theme.chat_actionBackgroundGradientDarkenPaint);
}
canvas.drawCircle(AndroidUtilities.dp(48 - 21), bottom - AndroidUtilities.dp(21), AndroidUtilities.dp(21), skeletonOutlinePaint);
}
lastTop -= skeleton.height;
}
servicePaint.setAlpha(wasServiceAlpha);
skeletonServicePaint.setAlpha(wasServiceAlpha);
skeletonPaint.setAlpha(alpha);
skeletonOutlinePaint.setAlpha(wasOutlineAlpha);
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(wasDarkenAlpha);
invalidated = false;
invalidate();
} else if (System.currentTimeMillis() - startMessageAppearTransitionMs > SKELETON_DISAPPEAR_MS) {
messageSkeletons.clear();
@ -5207,13 +5333,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
private void updateSkeletonColors() {
int color0 = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_listSelector), 30);
int color1 = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_listSelector), 20);
boolean dark = ColorUtils.calculateLuminance(getThemedColor(Theme.key_windowBackgroundWhite)) <= 0.7f;
int color0 = ColorUtils.blendARGB(getThemedColor(Theme.key_listSelector), Color.argb(dark ? 0x21 : 0x03, 0xFF, 0xFF, 0xFF), dark ? 0.9f : 0.5f);
int color1 = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_listSelector), dark ? 24 : SKELETON_LIGHT_OVERLAY_ALPHA);
if (skeletonColor1 != color1 || skeletonColor0 != color0) {
skeletonColor0 = color0;
skeletonColor1 = color1;
skeletonGradient = new LinearGradient(0, 0, skeletonGradientWidth = AndroidUtilities.dp(200), 0, new int[]{color1, color0, color0, color1}, new float[]{0.0f, 0.4f, 0.6f, 1f}, Shader.TileMode.CLAMP);
skeletonPaint.setShader(skeletonGradient);
int outlineColor = Color.argb(dark ? 0x2B : 0x60, 0xFF, 0xFF, 0xFF);
skeletonOutlineGradient = new LinearGradient(0, 0, skeletonGradientWidth, 0, new int[]{Color.TRANSPARENT, outlineColor, outlineColor, Color.TRANSPARENT}, new float[]{0.0f, 0.4f, 0.6f, 1f}, Shader.TileMode.CLAMP);
skeletonOutlinePaint.setShader(skeletonOutlineGradient);
}
}
@ -5236,6 +5367,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (skeletonGradient != null) {
skeletonGradient.setLocalMatrix(skeletonMatrix);
}
skeletonOutlineMatrix.setTranslate(skeletonTotalTranslation, 0);
if (skeletonOutlineGradient != null) {
skeletonOutlineGradient.setLocalMatrix(skeletonOutlineMatrix);
}
}
@Override
@ -5596,6 +5731,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override
public boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (isSkeletonVisible()) {
invalidated = false;
invalidate();
}
@ -6097,7 +6233,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override
public int getStarForFixGap() {
int padding = (int) chatListViewPaddingTop;
if (isThreadChat() && !isTopic && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
if (isThreadChat() && (!isTopic || topicStarterMessageObject != null) && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
}
return padding;
@ -6242,7 +6378,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
for (int i = 0; i < n; i++) {
View child = chatListView.getChildAt(i);
float padding = chatListViewPaddingTop;
if (isThreadChat() && !isTopic && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
if (isThreadChat() && (!isTopic || topicStarterMessageObject != null) && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
}
if (chatListView.getChildAdapterPosition(child) == chatAdapter.getItemCount() - 1) {
@ -7968,6 +8104,13 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
topUndoView.showWithAction(0, UndoView.ACTION_HINT_SWIPE_TO_REPLY, null, null);
}
}
if (ChatObject.isForum(currentChat) && !isTopic && replyingMessageObject != null) {
int topicId = replyingMessageObject.replyToForumTopic != null ? replyingMessageObject.replyToForumTopic.id : MessageObject.getTopicId(replyingMessageObject.messageOwner);
if (topicId != 0) {
getMediaDataController().cleanDraft(dialog_id, topicId, false);
}
}
hideFieldPanel(notify, scheduleDate, true);
if (chatActivityEnterView != null && chatActivityEnterView.getEmojiView() != null) {
chatActivityEnterView.getEmojiView().onMessageSend();
@ -8504,6 +8647,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
chatActivityEnterTopView.addView(replyCloseImageView, LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
replyCloseImageView.setOnClickListener(v -> {
if (forwardingMessages == null || forwardingMessages.messages.isEmpty()) {
if (ChatObject.isForum(currentChat) && !isTopic && replyingMessageObject != null) {
int topicId = MessageObject.getTopicId(replyingMessageObject.messageOwner);
if (topicId != 0) {
getMediaDataController().cleanDraft(dialog_id, topicId, false);
}
}
showFieldPanel(false, null, null, null, foundWebPage, true, 0, true, true);
} else {
openAnotherForward();
@ -9231,6 +9380,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return fragmentView;
}
@Override
public INavigationLayout.BackButtonState getBackButtonState() {
return INavigationLayout.BackButtonState.BACK;
}
public void onPageDownClicked() {
wasManualScroll = true;
textSelectionHelper.cancelTextSelectionRunnable();
@ -9771,6 +9925,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
if (object != null) {
fragment.pinnedMessageObjects.put(id, object);
fragment.updatePinnedTopicStarterMessage();
}
}
fragment.loadedPinnedMessagesCount = loadedPinnedMessagesCount;
@ -10083,7 +10238,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
int adapterPosition = chatListView.getChildAdapterPosition(child);
if (adapterPosition == chatAdapter.getItemCount() - 1) {
float padding = chatListViewPaddingTop;
if (isThreadChat() && !isTopic && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
if (isThreadChat() && (!isTopic || topicStarterMessageObject != null) && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
}
if (child.getTop() > padding) {
@ -12331,6 +12486,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
replyObjectText = messageObjectToReply.messageTextShort;
}
AnimatedEmojiSpan.applyFontMetricsForString(replyObjectText, replyObjectTextView.getPaint());
} else if (messageObjectToReply.replyToForumTopic != null) {
replyObjectText = ForumUtilities.getTopicSpannedName(messageObjectToReply.replyToForumTopic, replyObjectTextView.getPaint());
} else if (messageObjectToReply.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
replyObjectText = Emoji.replaceEmoji(messageObjectToReply.messageOwner.media.game.title, replyObjectTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false);
sourceText = messageObjectToReply.messageOwner.media.game.title;
@ -12780,7 +12937,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
position++;
}
}
if (top && messages != null && messages.get(position) != null) {
if (top && messages != null && messages.size() > 0 && messages.get(position) != null) {
long groupId = messages.get(position).getGroupId();
while (groupId != 0 && position + 1 < messages.size()) {
if (groupId != messages.get(position + 1).getGroupId()) {
@ -12789,7 +12946,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
position++;
}
}
if (messages != null) {
if (messages != null && messages.size() > 0) {
position = Math.min(position, messages.size() - 1);
}
chatScrollHelper.scrollToPosition(chatScrollHelperCallback.position = position, chatScrollHelperCallback.offset = 0, chatScrollHelperCallback.bottom = !top, true);
@ -12992,6 +13149,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
boolean blurEnabled = SharedConfig.chatBlurEnabled() && Color.alpha(Theme.getColor(Theme.key_chat_BlurAlpha)) != 255;
MessageObject messageStarter = isTopic ? topicStarterMessageObject : threadMessageObject;
for (int a = 0; a < count; a++) {
View view = chatListView.getChildAt(a);
MessageObject messageObject = null;
@ -13048,7 +13207,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
messageCell.setParentBounds(chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4), chatListView.getMeasuredHeight() - blurredViewBottomOffset);
messageCell.setVisiblePart(viewTop, viewBottom - viewTop, recyclerChatViewHeight, keyboardOffset, view.getY() + (isKeyboardVisible() ? chatListView.getTop() : actionBar.getMeasuredHeight()) - contentView.getBackgroundTranslationY(), contentView.getMeasuredWidth(), contentView.getBackgroundSizeY(), blurredViewTopOffset, blurredViewBottomOffset);
markSponsoredAsRead(messageObject);
if (!threadMessageVisible && threadMessageObject != null && messageObject == threadMessageObject && messageCell.getBottom() > chatListViewPaddingTop) {
if (!threadMessageVisible && messageStarter != null && (messageObject == messageStarter || isTopic && messageObject != null && messageObject.getId() == messageStarter.getId()) && messageCell.getBottom() > chatListViewPaddingTop) {
threadMessageVisible = true;
}
if (videoPlayerContainer != null && (messageObject.isVideo() || messageObject.isRoundVideo()) && !messageObject.isVoiceTranscriptionOpen() && MediaController.getInstance().isPlayingMessage(messageObject)) {
@ -13307,7 +13466,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
hideFloatingDateView(true);
floatingDateViewOffset = 0;
}
if (isThreadChat() && !isTopic) {
if (isThreadChat()) {
if (previousThreadMessageVisible != threadMessageVisible) {
updatePinnedMessageView(openAnimationStartTime != 0 && SystemClock.elapsedRealtime() >= openAnimationStartTime + 150);
}
@ -13453,6 +13612,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
private int getHeightForMessage(MessageObject object) {
if (getParentActivity() == null) {
return 0;
}
if (dummyMessageCell == null) {
dummyMessageCell = new ChatMessageCell(getParentActivity(), true, themeDelegate);
}
@ -16064,6 +16226,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (!postponedScroll) {
chatAdapter.notifyDataSetChanged(true);
}
if (isTopic && startLoadFromMessageId == getTopicId() && messArr.size() > 0 && messages.size() > 0) {
scrollToMessage = messages.get(messArr.size() - 1);
}
if (scrollToMessage != null) {
addSponsoredMessages(!isFirstLoading);
int yOffset;
@ -17722,6 +17887,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
}
updatePinnedTopicStarterMessage();
} else if (id == NotificationCenter.didReceivedWebpages) {
ArrayList<TLRPC.Message> arrayList = (ArrayList<TLRPC.Message>) args[0];
boolean updated = false;
@ -17919,12 +18085,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
SparseArray<TLRPC.MessageReplies> array = channelReplies.get(dialog_id);
boolean hasChatInBack = false;
if (threadMessageObject != null && parentLayout != null) {
if (threadMessageObject != null && !isTopic && parentLayout != null) {
for (int a = 0, N = parentLayout.getFragmentStack().size() - 1; a < N; a++) {
BaseFragment fragment = parentLayout.getFragmentStack().get(a);
if (fragment != this && fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getChatMode() == getChatMode()) {
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getTopicId() == getTopicId() && chatActivity.getChatMode() == getChatMode()) {
hasChatInBack = true;
break;
}
@ -19364,12 +19530,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
boolean hasChatInBack = false;
boolean updatedReplies = false;
if (threadMessageObject != null && parentLayout != null) {
if (threadMessageObject != null && !isTopic && parentLayout != null) {
for (int a = 0, N = parentLayout.getFragmentStack().size() - 1; a < N; a++) {
BaseFragment fragment = parentLayout.getFragmentStack().get(a);
if (fragment != this && fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getChatMode() == getChatMode()) {
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && getTopicId() == getTopicId() && chatActivity.getChatMode() == getChatMode()) {
hasChatInBack = true;
break;
}
@ -19731,6 +19897,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
}
updatePinnedTopicStarterMessage();
}
private void migrateToNewChat(MessageObject obj) {
@ -20012,7 +20179,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
BaseFragment fragment = parentLayout.getFragmentStack().get(a);
if (fragment != this && fragment instanceof ChatActivity) {
ChatActivity chatActivity = (ChatActivity) fragment;
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getChatMode() == getChatMode() && chatActivity.threadMessageId == threadMessageId && chatActivity.reportType == reportType) {
if (chatActivity.needRemovePreviousSameChatActivity && chatActivity.dialog_id == dialog_id && chatActivity.getTopicId() == getTopicId() && chatActivity.getChatMode() == getChatMode() && chatActivity.threadMessageId == threadMessageId && chatActivity.reportType == reportType) {
fragment.removeSelfFromStack();
break;
}
@ -20556,9 +20723,6 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private void updateTopicHeader() {
avatarContainer.setTitle(forumTopic.title);
if (currentChat != null) {
avatarContainer.setSubtitle(LocaleController.formatString("TopicProfileStatus", R.string.TopicProfileStatus, currentChat.title));
}
updateTopicTitleIcon();
}
@ -20715,6 +20879,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if ((isThreadChat() && !isTopic) || pinnedListButton == null) {
return;
}
if (!fragmentOpened) {
animated = false;
}
boolean show = pinnedMessageIds.size() > 1 && !pinnedMessageButtonShown;
boolean visible = pinnedListButton.getTag() != null;
boolean progressIsVisible = pinnedProgress.getTag() != null;
@ -20814,7 +20981,10 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
int pinned_msg_id;
boolean changed = false;
MessageObject pinnedMessageObject;
if (isThreadChat() && !isTopic) {
if (isThreadChat() && threadMessageVisible) {
pinnedMessageObject = null;
pinned_msg_id = 0;
} else if (isThreadChat() && !isTopic) {
if (!threadMessageVisible) {
pinnedMessageObject = threadMessageObject;
pinned_msg_id = threadMessageId;
@ -22126,10 +22296,20 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (chatMode == 0) {
CharSequence[] message = new CharSequence[]{draftMessage};
ArrayList<TLRPC.MessageEntity> entities = getMediaDataController().getEntities(message, currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 101);
getMediaDataController().saveDraft(dialog_id, threadMessageId, message[0], entities, (replyMessage != null && !replyMessage.isTopicMainMessage) ? replyMessage.messageOwner : null, !searchWebpage);
int draftThreadId;
if (ChatObject.isForum(currentChat) && !isTopic && replyMessage != null) {
if (replyMessage.replyToForumTopic != null) {
draftThreadId = replyMessage.replyToForumTopic.id;
} else {
draftThreadId = MessageObject.getTopicId(replyMessage.messageOwner);
}
} else {
draftThreadId = threadMessageId;
}
getMediaDataController().saveDraft(dialog_id, draftThreadId, message[0], entities, (replyMessage != null && !replyMessage.isTopicMainMessage && replyMessage.replyToForumTopic == null) ? replyMessage.messageOwner : null, !searchWebpage);
getMessagesController().cancelTyping(0, dialog_id, threadMessageId);
if (!pausedOnLastMessage && !firstLoading) {
if (!pausedOnLastMessage && !firstLoading && (!isThreadChat() || isTopic)) {
SharedPreferences.Editor editor = MessagesController.getNotificationsSettings(currentAccount).edit();
int messageId = 0;
int offset = 0;
@ -22193,12 +22373,12 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
if (messageId != 0) {
editor.putInt("diditem" + dialog_id, messageId);
editor.putInt("diditemo" + dialog_id, offset);
editor.putInt("diditem" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()), messageId);
editor.putInt("diditemo" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()), offset);
} else {
pausedOnLastMessage = true;
editor.remove("diditem" + dialog_id);
editor.remove("diditemo" + dialog_id);
editor.remove("diditem" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()));
editor.remove("diditemo" + NotificationsController.getSharedPrefKey(dialog_id, getTopicId()));
}
editor.apply();
}
@ -22225,8 +22405,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (chatActivityEnterView == null || chatMode != 0) {
return;
}
TLRPC.DraftMessage draftMessage = getMediaDataController().getDraft(dialog_id, threadMessageId);
TLRPC.Message draftReplyMessage = draftMessage != null && draftMessage.reply_to_msg_id != 0 ? getMediaDataController().getDraftMessage(dialog_id, threadMessageId) : null;
TLRPC.DraftMessage draftMessage = null;
Integer topicId = null;
if (ChatObject.isForum(currentChat) && !isTopic) {
Pair<Integer, TLRPC.DraftMessage> pair = getMediaDataController().getOneThreadDraft(dialog_id);;
if (pair != null) {
topicId = pair.first;
draftMessage = pair.second;
}
} else {
draftMessage = getMediaDataController().getDraft(dialog_id, threadMessageId);
}
TLRPC.Message draftReplyMessage = draftMessage != null && draftMessage.reply_to_msg_id != 0 ? getMediaDataController().getDraftMessage(dialog_id, topicId != null ? topicId : threadMessageId) : null;
if (chatActivityEnterView.getFieldText() == null) {
if (draftMessage != null) {
chatActivityEnterView.setWebPage(null, !draftMessage.no_webpage);
@ -22314,6 +22504,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
replyingMessageObject = new MessageObject(currentAccount, draftReplyMessage, getMessagesController().getUsers(), false, false);
showFieldPanelForReply(replyingMessageObject);
updateBottomOverlay();
} else if (topicId != null && topicId != 0 && currentChat != null) {
TLRPC.TL_forumTopic topic = getMessagesController().getTopicsController().findTopic(currentChat.id, topicId);
if (topic != null && topic.topicStartMessage != null) {
replyingMessageObject = new MessageObject(currentAccount, topic.topicStartMessage, getMessagesController().getUsers(), false, false);
replyingMessageObject.replyToForumTopic = topic;
showFieldPanelForReply(replyingMessageObject);
updateBottomOverlay();
}
}
}
@ -22756,7 +22954,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
final ArrayList<Integer> options = new ArrayList<>();
View optionsView = null;
if (!getUserConfig().isPremium() && !getMessagesController().premiumLocked && message.getDocument() != null && message.getDocument().size >= 500 * 1024 * 1024 && FileLoader.getInstance(currentAccount).isLoadingFile(FileLoader.getAttachFileName(message.getDocument()))) {
if (!getUserConfig().isPremium() && !getMessagesController().premiumLocked && message.getDocument() != null && message.getDocument().size >= 150 * 1024 * 1024 && FileLoader.getInstance(currentAccount).isLoadingFile(FileLoader.getAttachFileName(message.getDocument()))) {
items.add(LocaleController.getString(R.string.PremiumSpeedPromo));
options.add(OPTION_SPEED_PROMO);
icons.add(R.drawable.msg_speed);
@ -22773,7 +22971,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
}
}
if (index != -1) {
FileLoader.getInstance(currentAccount).loadFile(premiumPromo.videos.get(index), null, FileLoader.PRIORITY_HIGH, 0);
FileLoader.getInstance(currentAccount).loadFile(premiumPromo.videos.get(index), premiumPromo, FileLoader.PRIORITY_HIGH, 0);
}
}
}
@ -25598,7 +25796,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else {
MessagesStorage.TopicKey topicKey = dids.get(0);
long did = topicKey.dialogId;
if (did != dialog_id || chatMode == MODE_PINNED) {
if (did != dialog_id || getTopicId() != topicKey.topicId || chatMode == MODE_PINNED) {
Bundle args = new Bundle();
if (noForwardQuote) {
args.putBoolean("forward_noquote", true);
@ -25630,7 +25828,21 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
fragment.finishFragment();
}
} else {
fragment.finishFragment();
List<BaseFragment> fragments = new ArrayList<>(getParentLayout().getFragmentStack());
if (!fragments.isEmpty() && fragments.get(fragments.size() - 1) == fragment) {
fragment.finishFragment();
} else {
int fragmentIndex = fragments.indexOf(fragment);
if (fragmentIndex > 0) {
for (int i = fragmentIndex; i < fragments.size(); i++) {
if (i == fragments.size() - 1) {
fragments.get(i).finishFragment();
} else {
fragment.removeSelfFromStack();
}
}
}
}
moveScrollToLastMessage(false);
showFieldPanelForForward(true, fmessages);
if (AndroidUtilities.isTablet()) {
@ -25738,10 +25950,18 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (isTopic) {
replyingMessageObject.isTopicMainMessage = true;
}
updatePinnedTopicStarterMessage();
updateTopPanel(false);
updateBottomOverlay();
}
private void updatePinnedTopicStarterMessage() {
topicStarterMessageObject = isTopic && !pinnedMessageObjects.isEmpty() && pinnedMessageIds.size() == 1 ? pinnedMessageObjects.get(pinnedMessageIds.get(0)) : null;
if (isTopic && topicStarterMessageObject != null && topicStarterMessageObject.messageOwner != null && forumTopic != null && !MessageObject.peersEqual(forumTopic.from_id, topicStarterMessageObject.messageOwner.from_id) && !MessageObject.peersEqual(currentChat, topicStarterMessageObject.messageOwner.from_id)) {
topicStarterMessageObject = null;
}
}
public void setHighlightMessageId(int id) {
highlightMessageId = id;
}
@ -27718,6 +27938,20 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return true;
}
@Override
public void didPressTopicButton(ChatMessageCell cell) {
MessageObject message = cell.getMessageObject();
if (message != null) {
int topicId = MessageObject.getTopicId(message.messageOwner);
if (topicId != 0) {
TLRPC.TL_forumTopic topic = getMessagesController().getTopicsController().findTopic(currentChat.id, topicId);
if (topic != null) {
ForumUtilities.openTopic(ChatActivity.this, currentChat.id, topic, message.getId());
}
}
}
}
@Override
public void didPressExtendedMediaPreview(ChatMessageCell cell, TLRPC.KeyboardButton button) {
getSendMessagesHelper().sendCallback(true, cell.getMessageObject(), button, ChatActivity.this);
@ -30486,7 +30720,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
initServiceMessageColors(backgroundDrawable);
};
if (animated) {
animationSettings.animationProgress = new ActionBarLayout.ThemeAnimationSettings.onAnimationProgress() {
animationSettings.animationProgress = new INavigationLayout.ThemeAnimationSettings.onAnimationProgress() {
@Override
public void setProgress(float p) {
chatListView.invalidate();
@ -30965,6 +31199,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return skeleton;
}
@Override
public SizeNotifierFrameLayout getContentView() {
return contentView;
}
private final static class MessageSkeleton {
int width;
int height;

View File

@ -19,8 +19,13 @@ import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
@ -41,6 +46,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.browser.Browser;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
@ -69,6 +75,7 @@ import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.LinkActionView;
import org.telegram.ui.Components.Premium.LimitReachedBottomSheet;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.Components.TypefaceSpan;
import java.util.ArrayList;
import java.util.HashMap;
@ -467,7 +474,43 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe
permanentLinkView.setUsers(0, null);
privateContainer.addView(permanentLinkView);
checkTextView = new TextInfoPrivacyCell(context);
checkTextView = new TextInfoPrivacyCell(context) {
@Override
public void setText(CharSequence text) {
if (text != null) {
SpannableStringBuilder tagsString = AndroidUtilities.replaceTags(text.toString());
int index = tagsString.toString().indexOf('\n');
if (index >= 0) {
tagsString.replace(index, index + 1, " ");
tagsString.setSpan(new ForegroundColorSpan(getThemedColor(Theme.key_windowBackgroundWhiteRedText4)), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TypefaceSpan[] spans = tagsString.getSpans(0, tagsString.length(), TypefaceSpan.class);
final String username = usernameTextView == null || usernameTextView.getText() == null ? "" : usernameTextView.getText().toString();
for (int i = 0; i < spans.length; ++i) {
tagsString.setSpan(
new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
Browser.openUrl(getContext(), "https://fragment.com/username/" + username);
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
},
tagsString.getSpanStart(spans[i]),
tagsString.getSpanEnd(spans[i]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
tagsString.removeSpan(spans[i]);
}
text = tagsString;
}
super.setText(text);
}
};
checkTextView.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
checkTextView.setBottomPadding(6);
linearLayout.addView(checkTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
@ -1344,7 +1387,7 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe
}
}
}
if (name == null || name.length() < 5) {
if (name == null || name.length() < 4) {
if (isChannel) {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
} else {
@ -1374,13 +1417,23 @@ public class ChatEditTypeActivity extends BaseFragment implements NotificationCe
checkTextView.setTextColor(Theme.key_windowBackgroundWhiteGreenText);
lastNameAvailable = true;
} else {
if (error != null && error.text.equals("CHANNELS_ADMIN_PUBLIC_TOO_MUCH")) {
if (error != null && "USERNAME_INVALID".equals(error.text) && req.username.length() == 4) {
checkTextView.setText(LocaleController.getString("UsernameInvalidShort", R.string.UsernameInvalidShort));
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText4));
} else if (error != null && "USERNAME_PURCHASE_AVAILABLE".equals(error.text)) {
if (req.username.length() == 4) {
checkTextView.setText(LocaleController.getString("UsernameInvalidShortPurchase", R.string.UsernameInvalidShortPurchase));
} else {
checkTextView.setText(LocaleController.getString("UsernameInUsePurchase", R.string.UsernameInUsePurchase));
}
checkTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText8));
} else if (error != null && "CHANNELS_ADMIN_PUBLIC_TOO_MUCH".equals(error.text)) {
canCreatePublic = false;
showPremiumIncreaseLimitDialog();
} else {
checkTextView.setText(LocaleController.getString("LinkInUse", R.string.LinkInUse));
checkTextView.setTextColor(Theme.key_windowBackgroundWhiteRedText4);
}
checkTextView.setTextColor(Theme.key_windowBackgroundWhiteRedText4);
lastNameAvailable = false;
}
}

View File

@ -251,6 +251,9 @@ public class ChatReactionsEditActivity extends BaseFragment implements Notificat
} else {
chatReactions.remove(react.reaction);
if (chatReactions.isEmpty()) {
if (listAdapter != null) {
listAdapter.notifyItemRangeRemoved((isChannel ? 1 : 2), 1 + availableReactions.size());
}
setCheckedEnableReactionCell(SELECT_TYPE_NONE, true);
}
}

View File

@ -0,0 +1,174 @@
package org.telegram.ui.Components;
import android.animation.TimeInterpolator;
import android.os.SystemClock;
import android.view.View;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
public class AnimatedColor {
private View parent;
private Runnable invalidate;
private int value;
private int targetValue;
private boolean firstSet;
private long transitionDelay = 0;
private long transitionDuration = 200;
private TimeInterpolator transitionInterpolator = CubicBezierInterpolator.DEFAULT;
private boolean transition;
private long transitionStart;
private int startValue;
public AnimatedColor() {
this.parent = null;
this.firstSet = true;
}
public AnimatedColor(long transitionDuration, TimeInterpolator transitionInterpolator) {
this.parent = null;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = true;
}
public AnimatedColor(long transitionDelay, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.parent = null;
this.transitionDelay = transitionDelay;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = true;
}
public AnimatedColor(View parentToInvalidate) {
this.parent = parentToInvalidate;
this.firstSet = true;
}
public AnimatedColor(View parentToInvalidate, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.parent = parentToInvalidate;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = true;
}
public AnimatedColor(View parentToInvalidate, long transitionDelay, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.parent = parentToInvalidate;
this.transitionDelay = transitionDelay;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = true;
}
public AnimatedColor(Runnable invalidate) {
this.invalidate = invalidate;
this.firstSet = true;
}
public AnimatedColor(Runnable invalidate, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.invalidate = invalidate;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = true;
}
public AnimatedColor(int initialValue, View parentToInvalidate) {
this.parent = parentToInvalidate;
this.value = targetValue = initialValue;
this.firstSet = false;
}
public AnimatedColor(int initialValue, Runnable invalidate) {
this.invalidate = invalidate;
this.value = targetValue = initialValue;
this.firstSet = false;
}
public AnimatedColor(int initialValue, View parentToInvalidate, long transitionDelay, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.parent = parentToInvalidate;
this.value = targetValue = initialValue;
this.transitionDelay = transitionDelay;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = false;
}
public AnimatedColor(int initialValue, Runnable invalidate, long transitionDelay, long transitionDuration, TimeInterpolator transitionInterpolator) {
this.invalidate = invalidate;
this.value = targetValue = initialValue;
this.transitionDelay = transitionDelay;
this.transitionDuration = transitionDuration;
this.transitionInterpolator = transitionInterpolator;
this.firstSet = false;
}
public int get() {
return value;
}
// set() must be called inside onDraw/dispatchDraw
// the main purpose of AnimatedColor is to interpolate between abrupt changing states
public int set(int mustBeColor) {
return this.set(mustBeColor, false);
}
public int set(int mustBeColor, boolean force) {
final long now = SystemClock.elapsedRealtime();
if (force || transitionDuration <= 0 || firstSet) {
value = targetValue = mustBeColor;
transition = false;
firstSet = false;
} else if (targetValue != mustBeColor) {
transition = true;
targetValue = mustBeColor;
startValue = value;
transitionStart = now;
}
if (transition) {
final float t = MathUtils.clamp((now - transitionStart - transitionDelay) / (float) transitionDuration, 0, 1);
if (now - transitionStart >= transitionDelay) {
if (transitionInterpolator == null) {
value = ColorUtils.blendARGB(startValue, targetValue, t);
} else {
value = ColorUtils.blendARGB(startValue, targetValue, transitionInterpolator.getInterpolation(t));
}
}
if (t >= 1f) {
transition = false;
} else {
if (parent != null) {
parent.invalidate();
}
if (invalidate != null) {
invalidate.run();
}
}
}
return value;
}
public float getTransitionProgress() {
if (!transition) {
return 0;
}
final long now = SystemClock.elapsedRealtime();
return MathUtils.clamp((now - transitionStart - transitionDelay) / (float) transitionDuration, 0, 1);
}
public float getTransitionProgressInterpolated() {
if (transitionInterpolator != null) {
return transitionInterpolator.getInterpolation(getTransitionProgress());
} else {
return getTransitionProgress();
}
}
public void setParent(View parent) {
this.parent = parent;
}
}

View File

@ -38,6 +38,7 @@ import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.Premium.PremiumLockIconView;
import java.util.ArrayList;
import java.util.HashMap;
@ -687,6 +688,28 @@ public class AnimatedEmojiDrawable extends Drawable {
return imageReceiver;
}
private static HashMap<Long, Integer> dominantColors;
public static int getDominantColor(AnimatedEmojiDrawable yourDrawable) {
if (yourDrawable == null) {
return 0;
}
long documentId = yourDrawable.getDocumentId();
if (documentId == 0) {
return 0;
}
if (dominantColors == null) {
dominantColors = new HashMap<>();
}
Integer color = dominantColors.get(documentId);
if (color == null) {
if (yourDrawable.getImageReceiver() != null && yourDrawable.getImageReceiver().getBitmap() != null) {
dominantColors.put(documentId, color = PremiumLockIconView.getDominantColor(yourDrawable.getImageReceiver().getBitmap()));
}
}
return color == null ? 0 : color;
}
public static class WrapSizeDrawable extends Drawable {
private Drawable drawable;

View File

@ -34,6 +34,7 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
private float scale;
public boolean standard;
public boolean full = false;
public boolean top = false;
private Paint.FontMetricsInt fontMetrics;
private float size = AndroidUtilities.dp(20);
@ -101,6 +102,10 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
if (fm == null && top) {
fm = paint.getFontMetricsInt();
}
int ascent = fm == null ? 0 : fm.ascent, descent = fm == null ? 0 : fm.descent;
if (fontMetrics == null) {
int sz = (int) size;
@ -137,6 +142,11 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
}
}
}
if (fm != null && top) {
int diff = ((ascent - fm.ascent) + (descent - fm.descent)) / 2;
fm.ascent += diff;
fm.descent -= diff;
}
return measuredSize - 1;
}
@ -221,7 +231,7 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
public SpansChunk spansChunk;
public boolean insideSpoiler;
ImageReceiver.BackgroundThreadDrawHolder backgroundDrawHolder;
private ImageReceiver.BackgroundThreadDrawHolder[] backgroundDrawHolder = new ImageReceiver.BackgroundThreadDrawHolder[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
public AnimatedEmojiHolder(View view, boolean invalidateInParent) {
this.view = view;
@ -232,7 +242,7 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
return drawableBounds.bottom < boundTop || drawableBounds.top > boundBottom;
}
public void prepareForBackgroundDraw(long updateTime) {
public void prepareForBackgroundDraw(long updateTime, int threadIndex) {
if (drawable == null) {
return;
}
@ -245,16 +255,16 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
}
imageReceiver.setAlpha(alpha);
imageReceiver.setImageCoords(drawableBounds);
backgroundDrawHolder = imageReceiver.setDrawInBackgroundThread(backgroundDrawHolder);
backgroundDrawHolder.overrideAlpha = alpha;
backgroundDrawHolder.setBounds(drawableBounds);
backgroundDrawHolder.time = updateTime;
backgroundDrawHolder[threadIndex] = imageReceiver.setDrawInBackgroundThread(backgroundDrawHolder[threadIndex], threadIndex);
backgroundDrawHolder[threadIndex].overrideAlpha = alpha;
backgroundDrawHolder[threadIndex].setBounds(drawableBounds);
backgroundDrawHolder[threadIndex].time = updateTime;
}
}
public void releaseDrawInBackground() {
if (backgroundDrawHolder != null) {
backgroundDrawHolder.release();
public void releaseDrawInBackground(int threadIndex) {
if (backgroundDrawHolder[threadIndex] != null) {
backgroundDrawHolder[threadIndex].release();
}
}
@ -667,8 +677,8 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
public void drawInBackground(Canvas canvas) {
for (int i = 0; i < backgroundHolders.size(); i++) {
AnimatedEmojiHolder holder = backgroundHolders.get(i);
if (holder != null && holder.backgroundDrawHolder != null) {
holder.drawable.draw(canvas, holder.backgroundDrawHolder, true);
if (holder != null && holder.backgroundDrawHolder[threadIndex] != null) {
holder.drawable.draw(canvas, holder.backgroundDrawHolder[threadIndex], true);
}
}
}
@ -695,9 +705,7 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
backgroundHolders.remove(i--);
continue;
}
if (holder != null) {
holder.prepareForBackgroundDraw(time);
}
holder.prepareForBackgroundDraw(time, threadIndex);
}
}
@ -705,7 +713,7 @@ public class AnimatedEmojiSpan extends ReplacementSpan {
public void onFrameReady() {
for (int i = 0; i < backgroundHolders.size(); i++) {
if (backgroundHolders.get(i) != null) {
backgroundHolders.get(i).releaseDrawInBackground();
backgroundHolders.get(i).releaseDrawInBackground(threadIndex);
}
}
backgroundHolders.clear();

View File

@ -28,6 +28,7 @@ import android.view.View;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.AnimatedFileDrawableStream;
import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.DispatchQueuePoolBackground;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLocation;
@ -109,16 +110,16 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
private RectF actualDrawRect = new RectF();
private BitmapShader renderingShader;
private BitmapShader nextRenderingShader;
private BitmapShader backgroundShader;
private BitmapShader[] renderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private BitmapShader[] nextRenderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private BitmapShader[] backgroundShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private BitmapShader renderingShaderBackgroundDraw;
private int[] roundRadius = new int[4];
private int[] roundRadiusBackup;
private Matrix shaderMatrix = new Matrix();
private Path roundPath = new Path();
private Matrix[] shaderMatrix = new Matrix[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Path[] roundPath = new Path[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private static float[] radii = new float[8];
private Matrix shaderMatrixBackgroundDraw;
@ -139,8 +140,10 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
private float scaleFactor = 1f;
public boolean isWebmSticker;
private final TLRPC.Document document;
private RectF dstRectBackground;
private Paint backgroundPaint;
private RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Matrix[] shaderMatrixBackground = new Matrix[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Path[] roundPathBackground = new Path[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private View parentView;
private ArrayList<View> secondParentViews = new ArrayList<>();
@ -175,16 +178,21 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
private Runnable uiRunnableGenerateCache = new Runnable() {
@Override
public void run() {
if (!isRecycled && !destroyWhenDone && !generatingCache) {
if (!isRecycled && !destroyWhenDone && !generatingCache && cacheGenRunnable == null) {
startTime = System.currentTimeMillis();
if (RLottieDrawable.lottieCacheGenerateQueue == null) {
RLottieDrawable.createCacheGenQueue();
}
generatingCache = true;
loadFrameTask = null;
BitmapsCache.incrementTaskCounter();
RLottieDrawable.lottieCacheGenerateQueue.postRunnable(cacheGenRunnable = () -> {
bitmapsCache.createCache();
AndroidUtilities.runOnUIThread(() -> {
if (cacheGenRunnable != null) {
BitmapsCache.decrementTaskCounter();
cacheGenRunnable = null;
}
generatingCache = false;
scheduleNextGetFrame();
});
@ -241,7 +249,10 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
loadFrameTask = null;
nextRenderingBitmap = backgroundBitmap;
nextRenderingBitmapTime = backgroundBitmapTime;
nextRenderingShader = backgroundShader;
for (int i = 0; i < backgroundShader.length; i++) {
nextRenderingShader[i] = backgroundShader[i];
}
if (isRestarted) {
isRestarted = false;
repeatCount++;
@ -342,8 +353,8 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
} catch (Throwable e) {
FileLog.e(e);
}
if (backgroundShader == null && backgroundBitmap != null && hasRoundRadius()) {
backgroundShader = new BitmapShader(backgroundBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
if (backgroundShader[0] == null && backgroundBitmap != null && hasRoundRadius()) {
backgroundShader[0] = new BitmapShader(backgroundBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}
}
boolean seekWas = false;
@ -508,6 +519,7 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
}
private Runnable cancelCache;
public void checkCacheCancel() {
if (bitmapsCache == null) {
return;
@ -591,7 +603,9 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
isRunning = false;
isRecycled = true;
if (cacheGenRunnable != null) {
BitmapsCache.decrementTaskCounter();
RLottieDrawable.lottieCacheGenerateQueue.cancelRunnable(cacheGenRunnable);
cacheGenRunnable = null;
}
if (loadFrameTask == null) {
if (nativePtr != 0) {
@ -690,7 +704,7 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
}
private void scheduleNextGetFrame() {
if (loadFrameTask != null || !canLoadFrames() || destroyWhenDone || !isRunning && (!decodeSingleFrame || decodeSingleFrame && singleFrameDecoded) || parents.size() == 0 && !ignoreNoParent || generatingCache) {
if (loadFrameTask != null || nextRenderingBitmap != null || !canLoadFrames() || destroyWhenDone || !isRunning && (!decodeSingleFrame || decodeSingleFrame && singleFrameDecoded) || parents.size() == 0 && !ignoreNoParent || generatingCache) {
return;
}
long ms = 0;
@ -698,7 +712,11 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
ms = Math.min(invalidateAfter, Math.max(0, invalidateAfter - (System.currentTimeMillis() - lastFrameDecodeTime)));
}
if (useSharedQueue) {
executor.schedule(loadFrameTask = loadFrameRunnable, ms, TimeUnit.MILLISECONDS);
if (limitFps) {
DispatchQueuePoolBackground.execute(loadFrameTask = loadFrameRunnable);
} else {
executor.schedule(loadFrameTask = loadFrameRunnable, ms, TimeUnit.MILLISECONDS);
}
} else {
if (decodeQueue == null) {
decodeQueue = new DispatchQueue("decodeQueue" + this);
@ -751,22 +769,22 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
@Override
public void draw(Canvas canvas) {
drawInternal(canvas, false, System.currentTimeMillis());
drawInternal(canvas, false, System.currentTimeMillis(), 0);
}
public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter) {
if (dstRectBackground == null) {
dstRectBackground = new RectF();
backgroundPaint = new Paint();
backgroundPaint.setFilterBitmap(true);
public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter, int threadIndex) {
if (dstRectBackground[threadIndex] == null) {
dstRectBackground[threadIndex] = new RectF();
backgroundPaint[threadIndex] = new Paint();
backgroundPaint[threadIndex].setFilterBitmap(true);
}
backgroundPaint.setAlpha(alpha);
backgroundPaint.setColorFilter(colorFilter);
dstRectBackground.set(x, y, x + w, y + h);
drawInternal(canvas, true, 0);
backgroundPaint[threadIndex].setAlpha(alpha);
backgroundPaint[threadIndex].setColorFilter(colorFilter);
dstRectBackground[threadIndex].set(x, y, x + w, y + h);
drawInternal(canvas, true, 0, threadIndex);
}
public void drawInternal(Canvas canvas, boolean drawInBackground, long currentTime) {
public void drawInternal(Canvas canvas, boolean drawInBackground, long currentTime, int threadIndex) {
if (!canLoadFrames() || destroyWhenDone) {
return;
}
@ -775,8 +793,8 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
currentTime = System.currentTimeMillis();
}
RectF rect = drawInBackground ? dstRectBackground : dstRect;
Paint paint = drawInBackground ? backgroundPaint : getPaint();
RectF rect = drawInBackground ? dstRectBackground[threadIndex] : dstRect;
Paint paint = drawInBackground ? backgroundPaint[threadIndex] : getPaint();
if (!drawInBackground) {
updateCurrentFrame(currentTime, false);
@ -809,36 +827,47 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
applyTransformation = false;
}
if (hasRoundRadius()) {
if (renderingShader == null) {
renderingShader = new BitmapShader(renderingBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
int index = drawInBackground ? threadIndex + 1 : 0;
if (renderingShader[index] == null) {
renderingShader[index] = new BitmapShader(renderingBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
}
paint.setShader(renderingShader);
shaderMatrix.reset();
shaderMatrix.setTranslate(rect.left, rect.top);
paint.setShader(renderingShader[index]);
Matrix matrix = shaderMatrix[index];
if (matrix == null) {
matrix = shaderMatrix[index] = new Matrix();
}
Path path = roundPath[index];
if (path == null) {
path = roundPath[index] = new Path();
}
matrix.reset();
matrix.setTranslate(rect.left, rect.top);
if (metaData[2] == 90) {
shaderMatrix.preRotate(90);
shaderMatrix.preTranslate(0, -rect.width());
matrix.preRotate(90);
matrix.preTranslate(0, -rect.width());
} else if (metaData[2] == 180) {
shaderMatrix.preRotate(180);
shaderMatrix.preTranslate(-rect.width(), -rect.height());
matrix.preRotate(180);
matrix.preTranslate(-rect.width(), -rect.height());
} else if (metaData[2] == 270) {
shaderMatrix.preRotate(270);
shaderMatrix.preTranslate(-rect.height(), 0);
matrix.preRotate(270);
matrix.preTranslate(-rect.height(), 0);
}
shaderMatrix.preScale(scaleX, scaleY);
matrix.preScale(scaleX, scaleY);
renderingShader.setLocalMatrix(shaderMatrix);
if (invalidatePath) {
invalidatePath = false;
renderingShader[index].setLocalMatrix(matrix);
if (invalidatePath || drawInBackground) {
if (!drawInBackground) {
invalidatePath = false;
}
for (int a = 0; a < roundRadius.length; a++) {
radii[a * 2] = roundRadius[a];
radii[a * 2 + 1] = roundRadius[a];
}
roundPath.reset();
roundPath.addRoundRect(drawInBackground ? rect : actualDrawRect, radii, Path.Direction.CW);
roundPath.close();
path.reset();
path.addRoundRect(drawInBackground ? rect : actualDrawRect, radii, Path.Direction.CW);
path.close();
}
canvas.drawPath(roundPath, paint);
canvas.drawPath(path, paint);
} else {
canvas.translate(rect.left, rect.top);
if (metaData[2] == 90) {
@ -1086,28 +1115,43 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable,
if (renderingBitmap == null && nextRenderingBitmap == null) {
scheduleNextGetFrame();
} else if (nextRenderingBitmap != null && (renderingBitmap == null || (Math.abs(now - lastFrameTime) >= invalidateAfter && !skipFrameUpdate))) {
if (precache) {
//if (precache) {
backgroundBitmap = renderingBitmap;
}
// }
renderingBitmap = nextRenderingBitmap;
renderingBitmapTime = nextRenderingBitmapTime;
renderingShader = nextRenderingShader;
for (int i = 0; i < backgroundShader.length; i++) {
// if (precache) {
backgroundShader[i] = renderingShader[i];
// }
renderingShader[i] = nextRenderingShader[i];
nextRenderingShader[i] = null;
}
nextRenderingBitmap = null;
nextRenderingBitmapTime = 0;
nextRenderingShader = null;
lastFrameTime = now;
scheduleNextGetFrame();
} else {
invalidateInternal();
}
} else if (!isRunning && decodeSingleFrame && Math.abs(now - lastFrameTime) >= invalidateAfter && nextRenderingBitmap != null) {
if (precache) {
// if (precache) {
backgroundBitmap = renderingBitmap;
}
// }
renderingBitmap = nextRenderingBitmap;
renderingBitmapTime = nextRenderingBitmapTime;
renderingShader = nextRenderingShader;
for (int i = 0; i < backgroundShader.length; i++) {
// if (precache) {
backgroundShader[i] = renderingShader[i];
// }
renderingShader[i] = nextRenderingShader[i];
nextRenderingShader[i] = null;
}
nextRenderingBitmap = null;
nextRenderingBitmapTime = 0;
nextRenderingShader = null;
lastFrameTime = now;
scheduleNextGetFrame();
}
}
}

View File

@ -50,6 +50,10 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.core.graphics.ColorUtils;
import androidx.dynamicanimation.animation.FloatValueHolder;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@ -139,6 +143,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
private ActionBarMenuItem searchItem;
private boolean blurredAnimationInProgress;
private View[] buttons = new View[5];
private SpringAnimation seekBarBufferSpring;
private boolean draggingSeekBar;
@ -175,6 +180,8 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
long lastRewindingTime;
long lastUpdateRewindingPlayerTime;
private boolean wasLight;
private final static int menu_speed_slow = 1;
private final static int menu_speed_normal = 2;
private final static int menu_speed_fast = 3;
@ -273,18 +280,15 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
lastMeasturedHeight = totalHeight;
}
ignoreLayout = true;
if (Build.VERSION.SDK_INT >= 21 && !isFullscreen) {
setPadding(backgroundPaddingLeft, AndroidUtilities.statusBarHeight, backgroundPaddingLeft, 0);
}
playerLayout.setVisibility(searchWas || keyboardVisible ? INVISIBLE : VISIBLE);
playerShadow.setVisibility(playerLayout.getVisibility());
int availableHeight = totalHeight - getPaddingTop();
LayoutParams layoutParams = (LayoutParams) listView.getLayoutParams();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight() + AndroidUtilities.statusBarHeight;
layoutParams = (LayoutParams) actionBarShadow.getLayoutParams();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight();
layoutParams.topMargin = ActionBar.getCurrentActionBarHeight() + AndroidUtilities.statusBarHeight;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) blurredView.getLayoutParams();
lp.topMargin = -getPaddingTop();
@ -397,11 +401,6 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
Theme.dialogs_onlineCirclePaint.setAlpha((int) (alpha * alphaProgress * rad));
canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
}
int color1 = getThemedColor(Theme.key_dialogBackground);
int finalColor = Color.argb((int) (255 * actionBar.getAlpha()), (int) (Color.red(color1) * 0.8f), (int) (Color.green(color1) * 0.8f), (int) (Color.blue(color1) * 0.8f));
Theme.dialogs_onlineCirclePaint.setColor(finalColor);
canvas.drawRect(backgroundPaddingLeft, 0, getMeasuredWidth() - backgroundPaddingLeft, AndroidUtilities.statusBarHeight, Theme.dialogs_onlineCirclePaint);
}
}
@ -439,7 +438,7 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
actionBar.setTitleColor(getThemedColor(Theme.key_player_actionBarTitle));
actionBar.setTitle(LocaleController.getString("AttachMusic", R.string.AttachMusic));
actionBar.setSubtitleColor(getThemedColor(Theme.key_player_actionBarSubtitle));
actionBar.setOccupyStatusBar(false);
actionBar.setOccupyStatusBar(true);
actionBar.setAlpha(0.0f);
if (messageObject != null && !MediaController.getInstance().currentPlaylistIsGlobalSearch()) {
@ -647,6 +646,12 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
seekBarView.setReportChanges(true);
playerLayout.addView(seekBarView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 5, 70, 5, 0));
seekBarBufferSpring = new SpringAnimation(new FloatValueHolder(0))
.setSpring(new SpringForce()
.setStiffness(750f)
.setDampingRatio(SpringForce.DAMPING_RATIO_NO_BOUNCY))
.addUpdateListener((animation, value, velocity) -> seekBarView.setBufferedProgress(value / 1000f));
progressView = new LineProgressView(context);
progressView.setVisibility(View.INVISIBLE);
progressView.setBackgroundColor(getThemedColor(Theme.key_player_progressBackground));
@ -1661,7 +1666,8 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
}
}
if (bufferedProgress != -1) {
seekBarView.setBufferedProgress(bufferedProgress);
seekBarBufferSpring.getSpring().setFinalPosition(bufferedProgress * 1000);
seekBarBufferSpring.start();
}
}
}
@ -1711,11 +1717,30 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
actionBarAnimation.start();
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
newOffset += layoutParams.topMargin - AndroidUtilities.dp(11);
newOffset += layoutParams.topMargin - AndroidUtilities.statusBarHeight - AndroidUtilities.dp(11);
if (scrollOffsetY != newOffset) {
listView.setTopGlowOffset((scrollOffsetY = newOffset) - layoutParams.topMargin);
listView.setTopGlowOffset((scrollOffsetY = newOffset) - layoutParams.topMargin - AndroidUtilities.statusBarHeight);
containerView.invalidate();
}
int offset = AndroidUtilities.dp(13);
top = scrollOffsetY - backgroundPaddingTop - offset;
if (currentSheetAnimationType == 1) {
top += listView.getTranslationY();
}
float rad = 1.0f;
if (top + backgroundPaddingTop < ActionBar.getCurrentActionBarHeight()) {
float toMove = offset + AndroidUtilities.dp(11 - 7);
float moveProgress = Math.min(1.0f, (ActionBar.getCurrentActionBarHeight() - top - backgroundPaddingTop) / toMove);
rad = 1.0f - moveProgress;
}
boolean light = rad <= 0.5f && ColorUtils.calculateLuminance(getThemedColor(Theme.key_dialogBackground)) > 0.7f;
if (light != wasLight) {
AndroidUtilities.setLightStatusBar(getWindow(), wasLight = light);
}
}
@Override
@ -1846,7 +1871,8 @@ public class AudioPlayerAlert extends BottomSheet implements NotificationCenter.
}
}
if (bufferedProgress != -1) {
seekBarView.setBufferedProgress(bufferedProgress);
seekBarBufferSpring.getSpring().setFinalPosition(bufferedProgress * 1000);
seekBarBufferSpring.start();
}
if (updateRewinding) {
newTime = (int) (messageObject.getDuration() * seekBarView.getProgress());

View File

@ -10,9 +10,11 @@ package org.telegram.ui.Components;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
@ -32,7 +34,8 @@ import org.telegram.ui.ActionBar.Theme;
public class AvatarDrawable extends Drawable {
private TextPaint namePaint;
private int color;
private boolean hasGradient;
private int color, color2;
private boolean needApplyColorAccent;
private StaticLayout textLayout;
private float textWidth;
@ -46,6 +49,14 @@ public class AvatarDrawable extends Drawable {
private StringBuilder stringBuilder = new StringBuilder(5);
private int roundRadius = -1;
private int gradientTop, gradientBottom;
private int gradientColor1, gradientColor2;
private LinearGradient gradient;
private int gradientTop2, gradientBottom2;
private int gradientColor21, gradientColor22;
private LinearGradient gradient2;
public static final int AVATAR_TYPE_NORMAL = 0;
public static final int AVATAR_TYPE_SAVED = 1;
public static final int AVATAR_TYPE_ARCHIVED = 2;
@ -106,7 +117,7 @@ public class AvatarDrawable extends Drawable {
isProfile = value;
}
private static int getColorIndex(long id) {
public static int getColorIndex(long id) {
if (id >= 0 && id < 7) {
return (int) id;
}
@ -165,33 +176,55 @@ public class AvatarDrawable extends Drawable {
public void setAvatarType(int value) {
avatarType = value;
if (avatarType == AVATAR_TYPE_REGISTER) {
color = Theme.getColor(Theme.key_chats_actionBackground);
hasGradient = false;
color = color2 = Theme.getColor(Theme.key_chats_actionBackground);
} else if (avatarType == AVATAR_TYPE_ARCHIVED) {
color = getThemedColor(Theme.key_avatar_backgroundArchivedHidden);
hasGradient = false;
color = color2 = getThemedColor(Theme.key_avatar_backgroundArchivedHidden);
} else if (avatarType == AVATAR_TYPE_REPLIES) {
hasGradient = true;
color = getThemedColor(Theme.key_avatar_backgroundSaved);
color2 = getThemedColor(Theme.key_avatar_background2Saved);
} else if (avatarType == AVATAR_TYPE_SAVED) {
hasGradient = true;
color = getThemedColor(Theme.key_avatar_backgroundSaved);
color2 = getThemedColor(Theme.key_avatar_background2Saved);
} else if (avatarType == AVATAR_TYPE_SHARES) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(5)]);
} else if (avatarType == AVATAR_TYPE_FILTER_CONTACTS) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(5)]);
} else if (avatarType == AVATAR_TYPE_FILTER_NON_CONTACTS) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(4)]);
} else if (avatarType == AVATAR_TYPE_FILTER_GROUPS) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(3)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(3)]);
} else if (avatarType == AVATAR_TYPE_FILTER_CHANNELS) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(1)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(1)]);
} else if (avatarType == AVATAR_TYPE_FILTER_BOTS) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(0)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(0)]);
} else if (avatarType == AVATAR_TYPE_FILTER_MUTED) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(6)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(6)]);
} else if (avatarType == AVATAR_TYPE_FILTER_READ) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(5)]);
} else {
if (avatarType == AVATAR_TYPE_FILTER_CONTACTS) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]);
} else if (avatarType == AVATAR_TYPE_FILTER_NON_CONTACTS) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]);
} else if (avatarType == AVATAR_TYPE_FILTER_GROUPS) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(3)]);
} else if (avatarType == AVATAR_TYPE_FILTER_CHANNELS) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(1)]);
} else if (avatarType == AVATAR_TYPE_FILTER_BOTS) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(0)]);
} else if (avatarType == AVATAR_TYPE_FILTER_MUTED) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(6)]);
} else if (avatarType == AVATAR_TYPE_FILTER_READ) {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(5)]);
} else {
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]);
}
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(4)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(4)]);
}
needApplyColorAccent = avatarType != AVATAR_TYPE_ARCHIVED && avatarType != AVATAR_TYPE_SAVED && avatarType != AVATAR_TYPE_REPLIES;
}
@ -216,7 +249,15 @@ public class AvatarDrawable extends Drawable {
}
public void setColor(int value) {
hasGradient = false;
color = color2 = value;
needApplyColorAccent = false;
}
public void setColor(int value, int value2) {
hasGradient = true;
color = value;
color2 = value2;
needApplyColorAccent = false;
}
@ -232,8 +273,42 @@ public class AvatarDrawable extends Drawable {
return needApplyColorAccent ? Theme.changeColorAccent(color) : color;
}
public int getColor2() {
return needApplyColorAccent ? Theme.changeColorAccent(color2) : color2;
}
private String takeFirstCharacter(String text) {
StringBuilder sequence = new StringBuilder(16);
boolean isInJoin = false;
int codePoint;
for (int i = 0; i < text.length(); i = text.offsetByCodePoints(i, 1)) {
codePoint = text.codePointAt(i);
if (codePoint == 0x200D || codePoint == 0x1f1ea) {
isInJoin = true;
if (sequence.length() == 0)
continue;
} else {
if ((sequence.length() > 0) && (!isInJoin))
break;
isInJoin = false;
}
sequence.appendCodePoint(codePoint);
}
if (isInJoin) {
for (int i = sequence.length()-1; i >= 0; --i) {
if (sequence.charAt(i) == 0x200D)
sequence.deleteCharAt(i);
else
break;
}
}
return sequence.toString();
}
public void setInfo(long id, String firstName, String lastName, String custom) {
hasGradient = true;
color = getThemedColor(Theme.keys_avatar_background[getColorIndex(id)]);
color2 = getThemedColor(Theme.keys_avatar_background2[getColorIndex(id)]);
needApplyColorAccent = id == 5; // Tinting manually set blue color
avatarType = AVATAR_TYPE_NORMAL;
@ -249,21 +324,27 @@ public class AvatarDrawable extends Drawable {
stringBuilder.append(custom);
} else {
if (firstName != null && firstName.length() > 0) {
stringBuilder.appendCodePoint(firstName.codePointAt(0));
stringBuilder.append(takeFirstCharacter(firstName));
}
if (lastName != null && lastName.length() > 0) {
String lastNameLastWord = lastName;
int index;
if ((index = lastNameLastWord.lastIndexOf(' ')) >= 0) {
lastNameLastWord = lastNameLastWord.substring(index + 1);
}
if (Build.VERSION.SDK_INT > 17) {
stringBuilder.append("\u200C");
}
stringBuilder.append(Emoji.getFirstCharSafely(lastName));
stringBuilder.append(takeFirstCharacter(lastNameLastWord));
} else if (firstName != null && firstName.length() > 0) {
for (int a = firstName.length() - 1; a >= 0; a--) {
if (firstName.charAt(a) == ' ') {
if (a != firstName.length() - 1 && firstName.charAt(a + 1) != ' ') {
int index = stringBuilder.length();
if (Build.VERSION.SDK_INT > 17) {
stringBuilder.append("\u200C");
}
stringBuilder.append(Emoji.getFirstCharSafely(firstName.substring(a+1)));
stringBuilder.append(takeFirstCharacter(firstName.substring(index)));
break;
}
}
@ -297,7 +378,17 @@ public class AvatarDrawable extends Drawable {
}
int size = bounds.width();
namePaint.setColor(ColorUtils.setAlphaComponent(getThemedColor(Theme.key_avatar_text), alpha));
Theme.avatar_backgroundPaint.setColor(ColorUtils.setAlphaComponent(getColor(), alpha));
if (hasGradient) {
int color = ColorUtils.setAlphaComponent(getColor(), alpha);
int color2 = ColorUtils.setAlphaComponent(getColor2(), alpha);
if (gradient == null || gradientBottom != bounds.height() || gradientColor1 != color || gradientColor2 != color2) {
gradient = new LinearGradient(0, 0, 0, gradientBottom = bounds.height(), gradientColor1 = color, gradientColor2 = color2, Shader.TileMode.CLAMP);
}
Theme.avatar_backgroundPaint.setShader(gradient);
} else {
Theme.avatar_backgroundPaint.setShader(null);
Theme.avatar_backgroundPaint.setColor(ColorUtils.setAlphaComponent(getColor(), alpha));
}
canvas.save();
canvas.translate(bounds.left, bounds.top);
if (roundRadius > 0) {

View File

@ -30,7 +30,7 @@ import org.telegram.ui.Cells.GroupCallUserCell;
import java.util.Random;
public class AvatarsDarawable {
public class AvatarsDrawable {
public final static int STYLE_GROUP_CALL_TOOLTIP = 10;
public final static int STYLE_MESSAGE_SEEN = 11;
@ -198,9 +198,9 @@ public class AvatarsDarawable {
overrideSize = size;
}
public void animateFromState(AvatarsDarawable avatarsDarawable, int currentAccount, boolean createAnimator) {
if (avatarsDarawable.transitionProgressAnimator != null) {
avatarsDarawable.transitionProgressAnimator.cancel();
public void animateFromState(AvatarsDrawable avatarsDrawable, int currentAccount, boolean createAnimator) {
if (avatarsDrawable.transitionProgressAnimator != null) {
avatarsDrawable.transitionProgressAnimator.cancel();
if (transitionInProgress) {
transitionInProgress = false;
swapStates();
@ -209,7 +209,7 @@ public class AvatarsDarawable {
TLObject[] objects = new TLObject[3];
for (int i = 0; i < 3; i++) {
objects[i] = currentStates[i].object;
setObject(i, currentAccount, avatarsDarawable.currentStates[i].object);
setObject(i, currentAccount, avatarsDrawable.currentStates[i].object);
}
commitTransition(false);
for (int i = 0; i < 3; i++) {
@ -246,7 +246,7 @@ public class AvatarsDarawable {
Random random = new Random();
public AvatarsDarawable(View parent, boolean inCall) {
public AvatarsDrawable(View parent, boolean inCall) {
this.parent = parent;
for (int a = 0; a < 3; a++) {
currentStates[a] = new DrawingState();

View File

@ -10,72 +10,72 @@ import org.telegram.tgnet.TLObject;
public class AvatarsImageView extends View {
public final AvatarsDarawable avatarsDarawable;
public final AvatarsDrawable avatarsDrawable;
public AvatarsImageView(@NonNull Context context, boolean inCall) {
super(context);
avatarsDarawable = new AvatarsDarawable(this, inCall);
avatarsDrawable = new AvatarsDrawable(this, inCall);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
avatarsDarawable.width = getMeasuredWidth();
avatarsDarawable.height = getMeasuredHeight();
avatarsDrawable.width = getMeasuredWidth();
avatarsDrawable.height = getMeasuredHeight();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
avatarsDarawable.onAttachedToWindow();
avatarsDrawable.onAttachedToWindow();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
avatarsDarawable.onDraw(canvas);
avatarsDrawable.onDraw(canvas);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
avatarsDarawable.onDetachedFromWindow();
avatarsDrawable.onDetachedFromWindow();
}
public void setStyle(int style) {
avatarsDarawable.setStyle(style);
avatarsDrawable.setStyle(style);
}
public void setDelegate(Runnable delegate) {
avatarsDarawable.setDelegate(delegate);
avatarsDrawable.setDelegate(delegate);
}
public void setObject(int a, int currentAccount, TLObject object) {
avatarsDarawable.setObject(a, currentAccount, object);
avatarsDrawable.setObject(a, currentAccount, object);
}
public void setAvatarsTextSize(int size) {
avatarsDarawable.setAvatarsTextSize(size);
avatarsDrawable.setAvatarsTextSize(size);
}
public void reset() {
avatarsDarawable.reset();
avatarsDrawable.reset();
}
public void setCount(int usersCount) {
avatarsDarawable.setCount(usersCount);
avatarsDrawable.setCount(usersCount);
}
public void commitTransition(boolean animated) {
avatarsDarawable.commitTransition(animated);
avatarsDrawable.commitTransition(animated);
}
public void updateAfterTransitionEnd() {
avatarsDarawable.updateAfterTransitionEnd();
avatarsDrawable.updateAfterTransitionEnd();
}
public void setCentered(boolean centered) {
avatarsDarawable.setCentered(centered);
avatarsDrawable.setCentered(centered);
}
}

View File

@ -1,6 +1,8 @@
package org.telegram.ui.Components;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
@ -13,18 +15,24 @@ import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLocation;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBarLayout;
import org.telegram.ui.ActionBar.ActionBarPopupWindow;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.INavigationLayout;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.DialogsActivity;
import org.telegram.ui.ProfileActivity;
import org.telegram.ui.TopicsFragment;
import java.util.ArrayList;
import java.util.Collections;
@ -44,7 +52,7 @@ public class BackButtonMenu {
int filterId;
}
public static ActionBarPopupWindow show(BaseFragment thisFragment, View backButton, long currentDialogId, Theme.ResourcesProvider resourcesProvider) {
public static ActionBarPopupWindow show(BaseFragment thisFragment, View backButton, long currentDialogId, int topicId, Theme.ResourcesProvider resourcesProvider) {
if (thisFragment == null) {
return null;
}
@ -54,7 +62,14 @@ public class BackButtonMenu {
if (parentLayout == null || context == null || fragmentView == null) {
return null;
}
ArrayList<PulledDialog> dialogs = getStackedHistoryDialogs(thisFragment, currentDialogId);
ArrayList<PulledDialog> dialogs;
if (topicId != 0) {
new ArrayList<>();
dialogs = getStackedHistoryForTopic(thisFragment, currentDialogId, topicId);
} else {
dialogs = getStackedHistoryDialogs(thisFragment, currentDialogId);
}
if (dialogs.size() <= 0) {
return null;
}
@ -75,7 +90,11 @@ public class BackButtonMenu {
cell.setMinimumWidth(AndroidUtilities.dp(200));
BackupImageView imageView = new BackupImageView(context);
imageView.setRoundRadius(AndroidUtilities.dp(32));
if (chat == null && user == null) {
imageView.setRoundRadius(0);
} else {
imageView.setRoundRadius(chat != null && chat.forum ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16));
}
cell.addView(imageView, LayoutHelper.createFrameRelatively(32, 32, Gravity.START | Gravity.CENTER_VERTICAL, 13, 0, 0, 0));
TextView titleView = new TextView(context);
@ -88,6 +107,7 @@ public class BackButtonMenu {
AvatarDrawable avatarDrawable = new AvatarDrawable();
avatarDrawable.setSmallSize(true);
Drawable thumb = avatarDrawable;
boolean addDivider = false;
if (chat != null) {
avatarDrawable.setInfo(chat);
if (chat.photo != null && chat.photo.strippedBitmap != null) {
@ -118,6 +138,13 @@ public class BackButtonMenu {
imageView.setImage(ImageLocation.getForUser(user, ImageLocation.TYPE_SMALL), "50_50", thumb, user);
}
titleView.setText(name);
} else {
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.msg_viewchats).mutate();
imageView.setImageDrawable(drawable);
imageView.setSize(AndroidUtilities.dp(24), AndroidUtilities.dp(24));
imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon, resourcesProvider), PorterDuff.Mode.MULTIPLY));
titleView.setText(LocaleController.getString("AllChats", R.string.AllChats));
addDivider = true;
}
cell.setBackground(Theme.getSelectorDrawable(Theme.getColor(Theme.key_listSelector, resourcesProvider), false));
@ -143,13 +170,12 @@ public class BackButtonMenu {
}
} else {
if (parentLayout != null && parentLayout.getFragmentStack() != null) {
for (int j = parentLayout.getFragmentStack().size() - 2; j > pDialog.stackIndex; --j) {
if (j >= 0 && j < parentLayout.getFragmentStack().size()) {
parentLayout.removeFragmentFromStack(j);
}
ArrayList<BaseFragment> fragments = new ArrayList<>(parentLayout.getFragmentStack());
for (int j = fragments.size() - 2; j > pDialog.stackIndex; --j) {
fragments.get(j).removeSelfFromStack();
}
if (pDialog.stackIndex < parentLayout.getFragmentStack().size()) {
parentLayout.bringToFront(pDialog.stackIndex);
// parentLayout.bringToFront(pDialog.stackIndex);
parentLayout.closeLastFragment(true);
return;
}
@ -159,6 +185,12 @@ public class BackButtonMenu {
goToPulledDialog(thisFragment, pDialog);
});
layout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
if (addDivider) {
FrameLayout gap = new FrameLayout(context);
gap.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuSeparator, resourcesProvider));
gap.setTag(R.id.fit_width_tag, 1);
layout.addView(gap, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 8));
}
}
ActionBarPopupWindow scrimPopupWindow = new ActionBarPopupWindow(layout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
@ -191,6 +223,30 @@ public class BackButtonMenu {
return scrimPopupWindow;
}
private static ArrayList<PulledDialog> getStackedHistoryForTopic(BaseFragment thisFragment, long currentDialogId, int topicId) {
ArrayList<PulledDialog> dialogs = new ArrayList<>();
if (thisFragment.getParentLayout().getFragmentStack().size() > 1 && thisFragment.getParentLayout().getFragmentStack().get(thisFragment.getParentLayout().getFragmentStack().size() - 2) instanceof TopicsFragment) {
PulledDialog pulledDialog = new PulledDialog();
dialogs.add(pulledDialog);
pulledDialog.stackIndex = 0;
pulledDialog.activity = DialogsActivity.class;
pulledDialog = new PulledDialog();
dialogs.add(pulledDialog);
pulledDialog.stackIndex = thisFragment.getParentLayout().getFragmentStack().size() - 2;
pulledDialog.activity = TopicsFragment.class;
pulledDialog.chat = MessagesController.getInstance(thisFragment.getCurrentAccount()).getChat(-currentDialogId);
return dialogs;
} else {
PulledDialog pulledDialog = new PulledDialog();
dialogs.add(pulledDialog);
pulledDialog.stackIndex = -1;
pulledDialog.activity = TopicsFragment.class;
pulledDialog.chat = MessagesController.getInstance(thisFragment.getCurrentAccount()).getChat(-currentDialogId);
return dialogs;
}
}
public static void goToPulledDialog(BaseFragment fragment, PulledDialog dialog) {
if (dialog == null) {
return;
@ -209,6 +265,13 @@ public class BackButtonMenu {
Bundle bundle = new Bundle();
bundle.putLong("dialog_id", dialog.dialogId);
fragment.presentFragment(new ProfileActivity(bundle), true);
} if (dialog.activity == TopicsFragment.class) {
Bundle bundle = new Bundle();
bundle.putLong("chat_id", dialog.chat.id);
fragment.presentFragment(new TopicsFragment(bundle), true);
} if (dialog.activity == DialogsActivity.class) {
fragment.presentFragment(new DialogsActivity(null), true);
}
}
@ -359,7 +422,7 @@ public class BackButtonMenu {
if (thisFragment == null) {
return null;
}
final ActionBarLayout parentLayout = thisFragment.getParentLayout();
final INavigationLayout parentLayout = thisFragment.getParentLayout();
final Context context = thisFragment.getParentActivity();
final View fragmentView = thisFragment.getFragmentView();
if (parentLayout == null || context == null || fragmentView == null) {
@ -437,10 +500,10 @@ public class BackButtonMenu {
}
if (pDialog.stackIndex >= 0) {
Long nextFragmentDialogId = null;
if (parentLayout == null || parentLayout.fragmentsStack == null || pDialog.stackIndex >= parentLayout.fragmentsStack.size()) {
if (parentLayout == null || parentLayout.getFragmentStack() == null || pDialog.stackIndex >= parentLayout.getFragmentStack().size()) {
nextFragmentDialogId = null;
} else {
BaseFragment nextFragment = parentLayout.fragmentsStack.get(pDialog.stackIndex);
BaseFragment nextFragment = parentLayout.getFragmentStack().get(pDialog.stackIndex);
if (nextFragment instanceof ChatActivity) {
nextFragmentDialogId = ((ChatActivity) nextFragment).getDialogId();
} else if (nextFragment instanceof ProfileActivity) {
@ -448,18 +511,18 @@ public class BackButtonMenu {
}
}
if (nextFragmentDialogId != null && nextFragmentDialogId != pDialog.dialogId) {
for (int j = parentLayout.fragmentsStack.size() - 2; j > pDialog.stackIndex; --j) {
for (int j = parentLayout.getFragmentStack().size() - 2; j > pDialog.stackIndex; --j) {
parentLayout.removeFragmentFromStack(j);
}
} else {
if (parentLayout != null && parentLayout.fragmentsStack != null) {
for (int j = parentLayout.fragmentsStack.size() - 2; j > pDialog.stackIndex; --j) {
if (j >= 0 && j < parentLayout.fragmentsStack.size()) {
if (parentLayout != null && parentLayout.getFragmentStack() != null) {
for (int j = parentLayout.getFragmentStack().size() - 2; j > pDialog.stackIndex; --j) {
if (j >= 0 && j < parentLayout.getFragmentStack().size()) {
parentLayout.removeFragmentFromStack(j);
}
}
if (pDialog.stackIndex < parentLayout.fragmentsStack.size()) {
parentLayout.showFragment(pDialog.stackIndex);
if (pDialog.stackIndex < parentLayout.getFragmentStack().size()) {
parentLayout.bringToFront(pDialog.stackIndex);
parentLayout.closeLastFragment(true);
return;
}

View File

@ -81,7 +81,7 @@ public class Bulletin {
private View.OnLayoutChangeListener containerLayoutListener;
private SpringAnimation bottomOffsetSpring;
public static Bulletin make(@NonNull ViewGroup containerLayout, @NonNull Layout contentLayout, int duration) {
public static Bulletin make(@NonNull FrameLayout containerLayout, @NonNull Layout contentLayout, int duration) {
return new Bulletin(null, containerLayout, contentLayout, duration);
}
@ -125,7 +125,7 @@ public class Bulletin {
private final Layout layout;
private final ParentLayout parentLayout;
private final BaseFragment containerFragment;
private final ViewGroup containerLayout;
private final FrameLayout containerLayout;
private final Runnable hideRunnable = this::hide;
private int duration;
@ -1290,11 +1290,11 @@ public class Bulletin {
super(context, resourcesProvider);
avatarsImageView = new AvatarsImageView(context, false);
avatarsImageView.setStyle(AvatarsDarawable.STYLE_MESSAGE_SEEN);
avatarsImageView.setStyle(AvatarsDrawable.STYLE_MESSAGE_SEEN);
avatarsImageView.setAvatarsTextSize(AndroidUtilities.dp(18));
addView(avatarsImageView, LayoutHelper.createFrameRelatively(24 + 12 + 12 + 8, 48, Gravity.START | Gravity.CENTER_VERTICAL, 12, 0, 0, 0));
textView = new LinkSpanDrawable.LinksTextView(context);
textView.setSingleLine();
textView.setTypeface(Typeface.SANS_SERIF);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
textView.setEllipsize(TextUtils.TruncateAt.END);

View File

@ -11,6 +11,7 @@ import android.view.HapticFeedbackConstants;
import android.view.ViewGroup;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.CheckResult;
@ -123,7 +124,7 @@ public final class BulletinFactory {
}
private BaseFragment fragment;
private ViewGroup containerLayout;
private FrameLayout containerLayout;
private final Theme.ResourcesProvider resourcesProvider;
private BulletinFactory(BaseFragment fragment) {
@ -205,10 +206,17 @@ public final class BulletinFactory {
}
}
layout.avatarsImageView.commitTransition(false);
layout.textView.setSingleLine(true);
layout.textView.setLines(1);
layout.textView.setSingleLine(false);
layout.textView.setMaxLines(2);
layout.textView.setText(text);
layout.textView.setTranslationX(-(3 - count) * AndroidUtilities.dp(12));
if (layout.textView.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
int margin = AndroidUtilities.dp(12 + 56 + 2 - (3 - count) * 12);
if (LocaleController.isRTL) {
((ViewGroup.MarginLayoutParams) layout.textView.getLayoutParams()).rightMargin = margin;
} else {
((ViewGroup.MarginLayoutParams) layout.textView.getLayoutParams()).leftMargin = margin;
}
}
return create(layout, Bulletin.DURATION_LONG);
}
@ -218,9 +226,9 @@ public final class BulletinFactory {
text = null;
} else if (users.size() == 1) {
if (ChatObject.isChannelAndNotMegaGroup(chat)) {
text = AndroidUtilities.replaceTags(LocaleController.formatString("HasBeenAddedToChannel", R.string.HasBeenAddedToChannel, "**" + UserObject.getUserName(users.get(0)) + "**"));
text = AndroidUtilities.replaceTags(LocaleController.formatString("HasBeenAddedToChannel", R.string.HasBeenAddedToChannel, "**" + UserObject.getFirstName(users.get(0)) + "**"));
} else {
text = AndroidUtilities.replaceTags(LocaleController.formatString("HasBeenAddedToGroup", R.string.HasBeenAddedToGroup, "**" + UserObject.getUserName(users.get(0)) + "**"));
text = AndroidUtilities.replaceTags(LocaleController.formatString("HasBeenAddedToGroup", R.string.HasBeenAddedToGroup, "**" + UserObject.getFirstName(users.get(0)) + "**"));
}
} else {
if (ChatObject.isChannelAndNotMegaGroup(chat)) {

View File

@ -0,0 +1,218 @@
package org.telegram.ui.Components;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.util.StateSet;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.ui.ActionBar.Theme;
import java.util.ArrayList;
public class CanvasButton {
Path drawingPath = new Path();
ArrayList<RectF> drawingRects = new ArrayList<>();
int usingRectCount;
boolean buttonPressed;
RippleDrawable selectorDrawable;
private final static int[] pressedState = new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed};
private final View parent;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Runnable delegate;
private boolean pathCreated;
Runnable longPressRunnable;
Runnable longPressRunnableInner = new Runnable() {
@Override
public void run() {
checkTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0));
parent.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
if (longPressRunnable != null) {
longPressRunnable.run();
}
}
};
private boolean longPressEnabled;
public CanvasButton(View parent) {
this.parent = parent;
paint.setPathEffect(new CornerPathEffect(AndroidUtilities.dp(12)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final Paint maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskPaint.setFilterBitmap(true);
maskPaint.setPathEffect(new CornerPathEffect(AndroidUtilities.dp(12)));
maskPaint.setColor(0xffffffff);
Drawable maskDrawable = new Drawable() {
@Override
public void draw(Canvas canvas) {
drawInternal(canvas, maskPaint);
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return PixelFormat.TRANSPARENT;
}
};
ColorStateList colorStateList = new ColorStateList(
new int[][]{StateSet.WILD_CARD},
new int[]{Theme.getColor(Theme.key_listSelector) & 0x19ffffff}
);
selectorDrawable = new RippleDrawable(colorStateList, null, maskDrawable);
}
}
public void draw(Canvas canvas) {
drawInternal(canvas, paint);
if (selectorDrawable != null) {
selectorDrawable.draw(canvas);
}
}
private void drawInternal(Canvas canvas, Paint paint) {
if (usingRectCount > 1) {
if (!pathCreated) {
drawingPath.rewind();
int left = 0, top = 0, right = 0, bottom = 0;
for (int i = 0; i < usingRectCount; i++) {
if (i + 1 < usingRectCount) {
float rightCurrent = drawingRects.get(i).right;
float rightNext = drawingRects.get(i + 1).right;
if (Math.abs(rightCurrent - rightNext) < AndroidUtilities.dp(4)) {
drawingRects.get(i + 1).right = drawingRects.get(i).right = Math.max(rightCurrent, rightNext);
}
}
if (i == 0 || drawingRects.get(i).bottom > bottom) {
bottom = (int) drawingRects.get(i).bottom;
}
if (i == 0 || drawingRects.get(i).right > right) {
right = (int) drawingRects.get(i).right;
}
if (i == 0 || drawingRects.get(i).left < left) {
left = (int) drawingRects.get(i).left;
}
if (i == 0 || drawingRects.get(i).top < top) {
top = (int) drawingRects.get(i).top;
}
drawingPath.addRect(drawingRects.get(i), Path.Direction.CCW);
if (selectorDrawable != null) {
selectorDrawable.setBounds(left, top, right, bottom);
}
}
pathCreated = true;
}
canvas.drawPath(drawingPath, paint);
} else if (usingRectCount == 1) {
canvas.drawRoundRect(drawingRects.get(0), AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint);
}
}
public boolean checkTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (contains(x, y)) {
buttonPressed = true;
if (Build.VERSION.SDK_INT >= 21 && selectorDrawable != null) {
selectorDrawable.setHotspot(x, y);
selectorDrawable.setState(pressedState);
}
AndroidUtilities.cancelRunOnUIThread(longPressRunnableInner);
if (longPressEnabled) {
AndroidUtilities.runOnUIThread(longPressRunnableInner, ViewConfiguration.getLongPressTimeout());
}
parent.invalidate();
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (buttonPressed) {
if (event.getAction() == MotionEvent.ACTION_UP && delegate != null) {
delegate.run();
}
parent.playSoundEffect(SoundEffectConstants.CLICK);
if (Build.VERSION.SDK_INT >= 21 && selectorDrawable != null) {
selectorDrawable.setState(StateSet.NOTHING);
}
buttonPressed = false;
parent.invalidate();
}
AndroidUtilities.cancelRunOnUIThread(longPressRunnableInner);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (buttonPressed && Build.VERSION.SDK_INT >= 21 && selectorDrawable != null) {
selectorDrawable.setHotspot(x, y);
}
}
return buttonPressed;
}
private boolean contains(int x, int y) {
for (int i = 0; i < usingRectCount; i++) {
if (drawingRects.get(i).contains(x, y)) {
return true;
}
}
return false;
}
public void setColor(int color) {
paint.setColor(color);
if (selectorDrawable != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Theme.setSelectorDrawableColor(selectorDrawable, color, true);
}
}
public void setDelegate(Runnable delegate) {
this.delegate = delegate;
}
public void rewind() {
pathCreated = false;
usingRectCount = 0;
}
public void addRect(RectF rectF) {
usingRectCount++;
if (usingRectCount > drawingRects.size()) {
drawingRects.add(new RectF());
}
RectF rect = drawingRects.get(usingRectCount - 1);
rect.set(rectF);
}
public void setRect(RectF rectF) {
rewind();
addRect(rectF);
}
public void setLongPress(Runnable runnable) {
longPressEnabled = true;
longPressRunnable = runnable;
}
}

View File

@ -0,0 +1,52 @@
package org.telegram.ui.Components;
import org.telegram.messenger.ChatObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
public interface ChatActivityInterface {
default ChatObject.Call getGroupCall() {
return null;
}
default TLRPC.Chat getCurrentChat() {
return null;
}
default TLRPC.User getCurrentUser() {
return null;
}
long getDialogId();
default void scrollToMessageId(int id, int i, boolean b, int i1, boolean b1, int i2) {
}
default boolean shouldShowImport() {
return false;
}
default boolean openedWithLivestream() {
return false;
}
default long getMergeDialogId() {
return 0;
}
default int getTopicId() {
return 0;
}
ChatAvatarContainer getAvatarContainer();
default void checkAndUpdateAvatar() {
}
SizeNotifierFrameLayout getContentView();
ActionBar getActionBar();
}

View File

@ -727,6 +727,8 @@ public class ChatAvatarContainer extends FrameLayout implements NotificationCent
}
setTypingAnimation(false);
if (parentFragment.isTopic && chat != null) {
int count = parentFragment.getThreadMessage().getRepliesCount();
// newSubtitle = LocaleController.formatPluralString("messages", count, count);
newSubtitle = LocaleController.formatString("TopicProfileStatus", R.string.TopicProfileStatus, chat.title);
} else if (chat != null) {
TLRPC.ChatFull info = parentFragment.getCurrentChatInfo();

View File

@ -62,6 +62,7 @@ public class DialogsItemAnimator extends SimpleItemAnimator {
private final RecyclerListView listView;
public DialogsItemAnimator(RecyclerListView listView) {
setSupportsChangeAnimations(false);
this.listView = listView;
}

View File

@ -4,7 +4,6 @@ import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
@ -18,6 +17,7 @@ import java.util.ArrayList;
public class DrawingInBackgroundThreadDrawable implements NotificationCenter.NotificationCenterDelegate {
public final static int THREAD_COUNT = 2;
boolean attachedToWindow;
Bitmap backgroundBitmap;
@ -26,9 +26,6 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
Bitmap bitmap;
Canvas bitmapCanvas;
Bitmap nextRenderingBitmap;
Canvas nextRenderingCanvas;
private boolean bitmapUpdating;
public int currentLayerNum = 1;
@ -42,10 +39,11 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
int width;
int padding;
private static DispatchQueue backgroundQueue;
public static DispatchQueuePool queuePool;
private final DispatchQueue backgroundQueue;
boolean error;
Runnable bitmapCreateTask = new Runnable() {
private final Runnable bitmapCreateTask = new Runnable() {
@Override
public void run() {
try {
@ -74,6 +72,8 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
}
};
boolean needSwapBitmaps;
Runnable uiFrameRunnable = new Runnable() {
@Override
public void run() {
@ -89,26 +89,19 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
if (frameGuid != lastFrameId) {
return;
}
Bitmap bitmapTmp = bitmap;
Canvas bitmapCanvasTmp = bitmapCanvas;
bitmap = nextRenderingBitmap;
bitmapCanvas = nextRenderingCanvas;
nextRenderingBitmap = backgroundBitmap;
nextRenderingCanvas = backgroundCanvas;
backgroundBitmap = bitmapTmp;
backgroundCanvas = bitmapCanvasTmp;
needSwapBitmaps = true;
}
};
private boolean reset;
private int lastFrameId;
public final int threadIndex;
public DrawingInBackgroundThreadDrawable() {
if (backgroundQueue == null) {
backgroundQueue = new DispatchQueue("draw_background_queue");
if (queuePool == null) {
queuePool = new DispatchQueuePool(THREAD_COUNT);
}
backgroundQueue = queuePool.getNextQueue();
threadIndex = queuePool.pointer;
}
public void draw(Canvas canvas, long time, int w, int h, float alpha) {
@ -121,7 +114,19 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
height = h;
width = w;
if ((bitmap == null && nextRenderingBitmap == null) || reset) {
if (needSwapBitmaps) {
needSwapBitmaps = false;
Bitmap bitmapTmp = bitmap;
Canvas bitmapCanvasTmp = bitmapCanvas;
bitmap = backgroundBitmap;
bitmapCanvas = backgroundCanvas;
backgroundBitmap = bitmapTmp;
backgroundCanvas = bitmapCanvasTmp;
}
if (bitmap == null || reset) {
reset = false;
if (bitmap != null) {
@ -131,16 +136,16 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
bitmap = null;
}
int heightInternal = height + padding;
if (nextRenderingBitmap == null || nextRenderingBitmap.getHeight() != heightInternal || nextRenderingBitmap.getWidth() != width) {
nextRenderingBitmap = Bitmap.createBitmap(width, heightInternal, Bitmap.Config.ARGB_8888);
nextRenderingCanvas = new Canvas(nextRenderingBitmap);
if (bitmap == null || bitmap.getHeight() != heightInternal || bitmap.getWidth() != width) {
bitmap = Bitmap.createBitmap(width, heightInternal, Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(bitmap);
} else {
nextRenderingBitmap.eraseColor(Color.TRANSPARENT);
bitmap.eraseColor(Color.TRANSPARENT);
}
nextRenderingCanvas.save();
nextRenderingCanvas.translate(0, padding);
drawInUiThread(nextRenderingCanvas, 1f);
nextRenderingCanvas.restore();
bitmapCanvas.save();
bitmapCanvas.translate(0, padding);
drawInUiThread(bitmapCanvas, 1f);
bitmapCanvas.restore();
}
if (!bitmapUpdating && !paused) {
@ -150,11 +155,8 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
backgroundQueue.postRunnable(bitmapCreateTask);
}
if (bitmap != null || nextRenderingBitmap != null) {
if (bitmap != null ) {
Bitmap drawingBitmap = bitmap;
if (drawingBitmap == null) {
drawingBitmap = nextRenderingBitmap;
}
paint.setAlpha((int) (255 * alpha));
canvas.save();
canvas.translate(0, -padding);
@ -202,11 +204,7 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
if (bitmap != null) {
bitmaps.add(bitmap);
}
if (nextRenderingBitmap != null) {
bitmaps.add(nextRenderingBitmap);
}
bitmap = null;
nextRenderingBitmap = null;
AndroidUtilities.recycleBitmaps(bitmaps);
attachedToWindow = false;
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.stopAllHeavyOperations);
@ -261,4 +259,29 @@ public class DrawingInBackgroundThreadDrawable implements NotificationCenter.Not
AndroidUtilities.recycleBitmaps(bitmaps);
}
}
public static class DispatchQueuePool {
final int size;
int pointer;
public final DispatchQueue[] pool;
private DispatchQueuePool(int size) {
this.size = size;
pool = new DispatchQueue[size];
}
public DispatchQueue getNextQueue() {
pointer++;
if (pointer > size - 1) {
pointer = 0;
}
DispatchQueue queue = pool[pointer];
if (queue == null) {
queue = pool[pointer] = new DispatchQueue("draw_background_queue_" + pointer);
}
return queue;
}
}
}

View File

@ -312,11 +312,11 @@ public class EmojiPacksAlert extends BottomSheet implements NotificationCenter.N
}
drawable.update(time);
imageView.backgroundThreadDrawHolder = drawable.getImageReceiver().setDrawInBackgroundThread(imageView.backgroundThreadDrawHolder);
imageView.backgroundThreadDrawHolder.time = time;
imageView.backgroundThreadDrawHolder[threadIndex] = drawable.getImageReceiver().setDrawInBackgroundThread(imageView.backgroundThreadDrawHolder[threadIndex], threadIndex);
imageView.backgroundThreadDrawHolder[threadIndex].time = time;
drawable.setAlpha(255);
AndroidUtilities.rectTmp2.set(imageView.getLeft() + imageView.getPaddingLeft(), imageView.getPaddingTop(), imageView.getRight() - imageView.getPaddingRight(), imageView.getMeasuredHeight() - imageView.getPaddingBottom());
imageView.backgroundThreadDrawHolder.setBounds(AndroidUtilities.rectTmp2);
imageView.backgroundThreadDrawHolder[threadIndex].setBounds(AndroidUtilities.rectTmp2);
imageView.imageReceiver = drawable.getImageReceiver();
drawInBackgroundViews.add(imageView);
}
@ -350,7 +350,7 @@ public class EmojiPacksAlert extends BottomSheet implements NotificationCenter.N
public void drawInBackground(Canvas canvas) {
for (int i = 0; i < drawInBackgroundViews.size(); i++) {
EmojiImageView imageView = drawInBackgroundViews.get(i);
imageView.imageReceiver.draw(canvas, imageView.backgroundThreadDrawHolder);
imageView.imageReceiver.draw(canvas, imageView.backgroundThreadDrawHolder[threadIndex]);
}
}
@ -394,7 +394,7 @@ public class EmojiPacksAlert extends BottomSheet implements NotificationCenter.N
super.onFrameReady();
for (int i = 0; i < drawInBackgroundViews.size(); i++) {
EmojiImageView imageView = drawInBackgroundViews.get(i);
imageView.backgroundThreadDrawHolder.release();
imageView.backgroundThreadDrawHolder[threadIndex].release();
}
containerView.invalidate();
}
@ -930,6 +930,9 @@ public class EmojiPacksAlert extends BottomSheet implements NotificationCenter.N
@Override
public void dismiss() {
super.dismiss();
if (customEmojiPacks != null) {
customEmojiPacks.recycle();
}
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 4);
}
@ -1138,7 +1141,7 @@ public class EmojiPacksAlert extends BottomSheet implements NotificationCenter.N
}
}
private class EmojiImageView extends View {
public ImageReceiver.BackgroundThreadDrawHolder backgroundThreadDrawHolder;
public ImageReceiver.BackgroundThreadDrawHolder[] backgroundThreadDrawHolder = new ImageReceiver.BackgroundThreadDrawHolder[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
public ImageReceiver imageReceiver;
public EmojiImageView(Context context) {

View File

@ -21,7 +21,6 @@ import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Outline;
import android.graphics.Paint;
@ -936,7 +935,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private boolean isRecent;
private AnimatedEmojiSpan span;
private EmojiPack pack;
private ImageReceiver.BackgroundThreadDrawHolder backgroundThreadDrawHolder;
private ImageReceiver.BackgroundThreadDrawHolder[] backgroundThreadDrawHolder = new ImageReceiver.BackgroundThreadDrawHolder[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
float pressedProgress;
ValueAnimator backAnimator;
@ -2833,13 +2832,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
}
drawable.update(time);
imageView.backgroundThreadDrawHolder = drawable.getImageReceiver().setDrawInBackgroundThread(imageView.backgroundThreadDrawHolder);
imageView.backgroundThreadDrawHolder.time = time;
imageView.backgroundThreadDrawHolder.overrideAlpha = 1f;
imageView.backgroundThreadDrawHolder[threadIndex] = drawable.getImageReceiver().setDrawInBackgroundThread(imageView.backgroundThreadDrawHolder[threadIndex], threadIndex);
imageView.backgroundThreadDrawHolder[threadIndex].time = time;
imageView.backgroundThreadDrawHolder[threadIndex].overrideAlpha = 1f;
drawable.setAlpha(255);
int topOffset = (int) (imageView.getHeight() * .03f);
AndroidUtilities.rectTmp2.set(imageView.getLeft() + imageView.getPaddingLeft() - startOffset, topOffset, imageView.getRight() - imageView.getPaddingRight() - startOffset, topOffset + imageView.getMeasuredHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom());
imageView.backgroundThreadDrawHolder.setBounds(AndroidUtilities.rectTmp2);
imageView.backgroundThreadDrawHolder[threadIndex].setBounds(AndroidUtilities.rectTmp2);
imageView.drawable = drawable;
imageView.imageReceiver = drawable.getImageReceiver();
drawInBackgroundViews.add(imageView);
@ -2851,7 +2850,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
for (int i = 0; i < drawInBackgroundViews.size(); i++) {
ImageViewEmoji imageView = drawInBackgroundViews.get(i);
if (imageView.drawable != null) {
imageView.drawable.draw(canvas, imageView.backgroundThreadDrawHolder, false);
imageView.drawable.draw(canvas, imageView.backgroundThreadDrawHolder[threadIndex], false);
}
}
}
@ -2918,7 +2917,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
for (int i = 0; i < drawInBackgroundViews.size(); i++) {
ImageViewEmoji imageView = drawInBackgroundViews.get(i);
if (imageView.backgroundThreadDrawHolder != null) {
imageView.backgroundThreadDrawHolder.release();
imageView.backgroundThreadDrawHolder[threadIndex].release();
}
}
emojiGridView.invalidate();

View File

@ -5,6 +5,7 @@ import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.telegram.messenger.SharedConfig;
import org.telegram.ui.Components.AnimationProperties;
import org.telegram.ui.LaunchActivity;
public class FloatingDebugController {
@ -54,16 +55,34 @@ public class FloatingDebugController {
public static class DebugItem {
final CharSequence title;
final DebugItemType type;
final Runnable action;
Runnable action;
float from;
float to;
AnimationProperties.FloatProperty floatProperty;
public DebugItem(CharSequence title, Runnable action) {
this.type = DebugItemType.SIMPLE;
this.title = title;
this.action = action;
}
public DebugItem(CharSequence title) {
this.type = DebugItemType.HEADER;
this.title = title;
}
public DebugItem(CharSequence title, float from, float to, AnimationProperties.FloatProperty callback) {
this.type = DebugItemType.SEEKBAR;
this.title = title;
this.from = from;
this.to = to;
this.floatProperty = callback;
}
}
public enum DebugItemType {
SIMPLE
SIMPLE,
HEADER,
SEEKBAR
}
}

View File

@ -7,10 +7,13 @@ import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.GestureDetector;
@ -21,6 +24,7 @@ import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
@ -38,6 +42,7 @@ import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
@ -45,13 +50,17 @@ import org.telegram.messenger.SharedConfig;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.INavigationLayout;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.HeaderCell;
import org.telegram.ui.Components.AnimationProperties;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.Components.SeekBarView;
import org.telegram.ui.LaunchActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FloatingDebugView extends FrameLayout implements NotificationCenter.NotificationCenterDelegate {
private FrameLayout floatingButtonContainer;
@ -225,10 +234,16 @@ public class FloatingDebugView extends FrameLayout implements NotificationCenter
switch (FloatingDebugController.DebugItemType.values()[viewType]) {
default:
case SIMPLE:
v = new AlertDialog.AlertDialogCell(context, null);
v.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
break;
v = new AlertDialog.AlertDialogCell(context, null);
break;
case HEADER:
v = new HeaderCell(context);
break;
case SEEKBAR:
v = new SeekBarCell(context);
break;
}
v.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerListView.Holder(v);
}
@ -236,11 +251,28 @@ public class FloatingDebugView extends FrameLayout implements NotificationCenter
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
FloatingDebugController.DebugItem item = debugItems.get(position);
switch (item.type) {
case SIMPLE:
case SIMPLE: {
AlertDialog.AlertDialogCell cell = (AlertDialog.AlertDialogCell) holder.itemView;
cell.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
cell.setTextAndIcon(item.title, 0);
break;
}
case HEADER: {
HeaderCell cell = (HeaderCell) holder.itemView;
cell.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
cell.setText(item.title);
break;
}
case SEEKBAR: {
SeekBarCell cell = (SeekBarCell) holder.itemView;
cell.title = item.title.toString();
cell.value = (float) item.floatProperty.get(null);
cell.min = item.from;
cell.max = item.to;
cell.callback = item.floatProperty;
cell.invalidate();
break;
}
}
}
@ -450,6 +482,7 @@ public class FloatingDebugView extends FrameLayout implements NotificationCenter
private List<FloatingDebugController.DebugItem> getBuiltInDebugItems() {
List<FloatingDebugController.DebugItem> items = new ArrayList<>();
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(R.string.DebugGeneral)));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
items.add(new FloatingDebugController.DebugItem(LocaleController.getString(SharedConfig.debugWebView ? R.string.DebugMenuDisableWebViewDebug : R.string.DebugMenuEnableWebViewDebug), ()->{
SharedConfig.toggleDebugWebView();
@ -463,6 +496,37 @@ public class FloatingDebugView extends FrameLayout implements NotificationCenter
((Activity) getContext()).recreate();
}
}));
items.add(new FloatingDebugController.DebugItem(Theme.isCurrentThemeDark() ? "Switch to day theme" : "Switch to dark theme", () -> {
boolean toDark;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE);
String dayThemeName = preferences.getString("lastDayTheme", "Blue");
if (Theme.getTheme(dayThemeName) == null || Theme.getTheme(dayThemeName).isDark()) {
dayThemeName = "Blue";
}
String nightThemeName = preferences.getString("lastDarkTheme", "Dark Blue");
if (Theme.getTheme(nightThemeName) == null || !Theme.getTheme(nightThemeName).isDark()) {
nightThemeName = "Dark Blue";
}
Theme.ThemeInfo themeInfo = Theme.getActiveTheme();
if (dayThemeName.equals(nightThemeName)) {
if (themeInfo.isDark() || dayThemeName.equals("Dark Blue") || dayThemeName.equals("Night")) {
dayThemeName = "Blue";
} else {
nightThemeName = "Dark Blue";
}
}
if (!Theme.isCurrentThemeDark()) {
themeInfo = Theme.getTheme(nightThemeName);
} else {
themeInfo = Theme.getTheme(dayThemeName);
}
Theme.ThemeInfo finalThemeInfo = themeInfo;
AndroidUtilities.runOnUIThread(() -> {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, finalThemeInfo, true, null, -1);
}, 200);
}));
return items;
}
@ -511,4 +575,87 @@ public class FloatingDebugView extends FrameLayout implements NotificationCenter
public void dismiss(Runnable callback) {
callback.run();
}
@SuppressWarnings("unchecked")
private class SeekBarCell extends FrameLayout {
private SeekBarView seekBar;
private float min;
private float max;
private float value;
private AnimationProperties.FloatProperty callback;
private String title;
private TextPaint textPaint;
private int lastWidth;
public SeekBarCell(Context context) {
super(context);
setWillNotDraw(false);
textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(AndroidUtilities.dp(16));
seekBar = new SeekBarView(context);
seekBar.setReportChanges(true);
seekBar.setDelegate(new SeekBarView.SeekBarViewDelegate() {
@Override
public void onSeekBarDrag(boolean stop, float progress) {
value = min + (max - min) * progress;
if (stop) {
callback.set(null, value);
}
invalidate();
}
@Override
public void onSeekBarPressed(boolean pressed) {}
@Override
public CharSequence getContentDescription() {
return String.valueOf(Math.round(min + (max - min) * seekBar.getProgress()));
}
});
seekBar.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
addView(seekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.LEFT | Gravity.BOTTOM, 5, 5 + 24, 47, 0));
}
@Override
protected void onDraw(Canvas canvas) {
textPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
canvas.drawText(title, AndroidUtilities.dp(24), AndroidUtilities.dp(24), textPaint);
textPaint.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteValueText));
String str = String.format(Locale.ROOT, "%.2f", value);
canvas.drawText(str, getMeasuredWidth() - AndroidUtilities.dp(8) - textPaint.measureText(str), AndroidUtilities.dp(28 - 5) + seekBar.getY(), textPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
if (lastWidth != width) {
seekBar.setProgress(((float) callback.get(null) - min) / (float) (max - min));
lastWidth = width;
}
}
@Override
public void invalidate() {
super.invalidate();
seekBar.invalidate();
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
seekBar.getSeekBarAccessibilityDelegate().onInitializeAccessibilityNodeInfoInternal(this, info);
}
@Override
public boolean performAccessibilityAction(int action, Bundle arguments) {
return super.performAccessibilityAction(action, arguments) || seekBar.getSeekBarAccessibilityDelegate().performAccessibilityActionInternal(this, action, arguments);
}
}
}

View File

@ -1,10 +1,10 @@
package org.telegram.ui.Components.Forum;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ImageSpan;
@ -71,6 +71,16 @@ public class ForumUtilities {
return combinedDrawable;
}
public static Drawable createSmallTopicDrawable(String text, int color) {
ForumBubbleDrawable forumBubbleDrawable = new ForumBubbleDrawable(color);
LetterDrawable letterDrawable = new LetterDrawable(null, LetterDrawable.STYLE_SMALL_TOPIC_DRAWABLE);
String title = text.trim().toUpperCase();
letterDrawable.setTitle(title.length() >= 1 ? title.substring(0, 1) : "");
CombinedDrawable combinedDrawable = new CombinedDrawable(forumBubbleDrawable, letterDrawable, 0, 0);
combinedDrawable.setFullsize(true);
return combinedDrawable;
}
public static void openTopic(BaseFragment baseFragment, long chatId, TLRPC.TL_forumTopic topic, int fromMessageId) {
if (baseFragment == null || topic == null) {
return;
@ -78,8 +88,12 @@ public class ForumUtilities {
TLRPC.Chat chatLocal = baseFragment.getMessagesController().getChat(chatId);
Bundle args = new Bundle();
args.putLong("chat_id", chatId);
if (fromMessageId != 0) {
args.putInt("message_id", fromMessageId);
} else if (topic.read_inbox_max_id == 0) {
//scroll to first message in topic
args.putInt("message_id", topic.id);
}
args.putInt("unread_count", topic.unread_count);
args.putBoolean("historyPreloaded", false);
@ -104,11 +118,11 @@ public class ForumUtilities {
baseFragment.presentFragment(chatActivity);
}
public static CharSequence getTopicSpannedName(TLRPC.ForumTopic topic, TextPaint paint) {
public static CharSequence getTopicSpannedName(TLRPC.ForumTopic topic, Paint paint) {
return getTopicSpannedName(topic, paint, null);
}
public static CharSequence getTopicSpannedName(TLRPC.ForumTopic topic, TextPaint paint, ForumBubbleDrawable[] drawableToSet) {
public static CharSequence getTopicSpannedName(TLRPC.ForumTopic topic, Paint paint, ForumBubbleDrawable[] drawableToSet) {
SpannableStringBuilder sb = new SpannableStringBuilder();
if (topic instanceof TLRPC.TL_forumTopic) {
TLRPC.TL_forumTopic forumTopic = (TLRPC.TL_forumTopic) topic;
@ -116,6 +130,7 @@ public class ForumUtilities {
sb.append(" ");
AnimatedEmojiSpan span;
sb.setSpan(span = new AnimatedEmojiSpan(forumTopic.icon_emoji_id, .95f, paint == null ? null : paint.getFontMetricsInt()), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
span.top = true;
span.cacheType = AnimatedEmojiDrawable.CACHE_TYPE_EMOJI_STATUS;
} else {
sb.append(" ");

View File

@ -0,0 +1,434 @@
package org.telegram.ui.Components.Forum;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import androidx.core.graphics.ColorUtils;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.R;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.ChatMessageCell;
import org.telegram.ui.Components.AnimatedColor;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.StaticLayoutEx;
public class MessageTopicButton {
private final static float[] lightHueRanges = { 0, 43, 56, 86, 169, 183, 249, 289, 360 };
private final static float[] lightSatValues = { .60f, 1f, .95f, .98f, .80f, .88f, .51f, .55f, .60f };
private final static float[] lightValValues = { .79f, .77f, .60f, .62f, .60f, .61f, .80f, .70f, .79f };
private final static float[] darkHueRanges = { 0, 43, 56, 63, 86, 122, 147, 195, 205, 249, 270, 312, 388, 360 };
private final static float[] darkSatValues = { .64f, .89f, .84f, .87f, .74f, .66f, .81f, .81f, .71f, .51f, .61f, .55f, .62f, .64f };
private final static float[] darkValValues = { .92f, .90f, .82f, .82f, .84f, .84f, .82f, .88f, .96f, .100f, .93f, .88f, .96f, .92f };
private int topicWidth;
private int topicHeight;
private Paint topicPaint;
private Path topicPath;
private Drawable topicArrowDrawable;
private Drawable topicSelectorDrawable;
private Drawable topicIconDrawable;
private Rect topicIconDrawableBounds;
private float[] topicHSV;
private int topicBackgroundColor;
private int topicNameColor;
private int topicArrowColor;
private AnimatedColor topicBackgroundColorAnimated, topicNameColorAnimated;
private boolean topicIconWaiting;
private StaticLayout topicNameLayout;
private RectF topicHitRect;
private boolean topicPressed;
private MessageObject lastMessageObject;
private Context context;
private Theme.ResourcesProvider resourcesProvider;
private final static int[] idleState = new int[]{};
private final static int[] pressedState = new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed};
public MessageTopicButton(Context context, Theme.ResourcesProvider resourcesProvider) {
this.context = context;
this.resourcesProvider = resourcesProvider;
}
protected void onClick() {}
public int set(ChatMessageCell cell, MessageObject messageObject, TLRPC.TL_forumTopic topic, int maxWidth) {
lastMessageObject = messageObject;
if (cell == null || messageObject == null) {
return 0;
}
int iconsz = AndroidUtilities.dp(7) + (int) Theme.chat_topicTextPaint.getTextSize();
float padleft = AndroidUtilities.dp(10) + iconsz;
float padright1 = Theme.chat_topicTextPaint.getTextSize() - AndroidUtilities.dp(8);
float padright = AndroidUtilities.dp(5) + Theme.chat_topicTextPaint.getTextSize();
maxWidth -= padleft + padright;
String title = topic.title == null ? "" : topic.title;
topicNameLayout = StaticLayoutEx.createStaticLayout(title, 0, title.length(), Theme.chat_topicTextPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1f, 0, false, TextUtils.TruncateAt.END, maxWidth, 2, false);
topicHeight = AndroidUtilities.dp(4 + 4.5f) + Math.min(AndroidUtilities.dp(24), topicNameLayout == null ? 0 : topicNameLayout.getHeight());
float textWidth = 0;
int lineCount = topicNameLayout == null ? 0 : topicNameLayout.getLineCount();
if (topicPath == null) {
topicPath = new Path();
} else {
topicPath.rewind();
}
if (topicPaint == null) {
topicPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
int iconColor;
if (topic.icon_emoji_id != 0) {
if (!(topicIconDrawable instanceof AnimatedEmojiDrawable) || topic.icon_emoji_id != ((AnimatedEmojiDrawable) topicIconDrawable).getDocumentId()) {
if (topicIconDrawable instanceof AnimatedEmojiDrawable) {
((AnimatedEmojiDrawable) topicIconDrawable).removeView(cell::invalidateOutbounds);
topicIconDrawable = null;
}
topicIconDrawable = AnimatedEmojiDrawable.make(messageObject.currentAccount, AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, topic.icon_emoji_id);
((AnimatedEmojiDrawable) topicIconDrawable).addView(cell::invalidateOutbounds);
}
topicIconWaiting = false;
iconColor = topicIconDrawable instanceof AnimatedEmojiDrawable ? AnimatedEmojiDrawable.getDominantColor((AnimatedEmojiDrawable) topicIconDrawable) : 0;
if (iconColor == 0) {
topicIconWaiting = true;
iconColor = getThemedColor(messageObject.isOutOwner() ? Theme.key_chat_outReactionButtonText : Theme.key_chat_inReactionButtonText);
}
} else {
iconColor = topic.icon_color;
topicIconDrawable = ForumUtilities.createSmallTopicDrawable(title, topic.icon_color);
}
setupColors(iconColor);
if (topicIconWaiting) {
if (topicNameColorAnimated == null) {
topicNameColorAnimated = new AnimatedColor(cell);
}
if (topicBackgroundColorAnimated == null) {
topicBackgroundColorAnimated = new AnimatedColor(cell);
}
}
if (topicArrowDrawable == null && context != null) {
topicArrowDrawable = context.getResources().getDrawable(R.drawable.msg_mini_topicarrow).mutate();
}
topicArrowDrawable.setColorFilter(new PorterDuffColorFilter(topicArrowColor = ColorUtils.setAlphaComponent(topicNameColor, 140), PorterDuff.Mode.MULTIPLY));
float R = (AndroidUtilities.dp(11) + (int) Theme.chat_topicTextPaint.getTextSize());
int arrowsz = Math.max(1, (int) Theme.chat_topicTextPaint.getTextSize() + AndroidUtilities.dp(0));
if (lineCount == 2) {
topicHeight = AndroidUtilities.dp(15) + 2 * ((int) Theme.chat_topicTextPaint.getTextSize());
float l1w = topicNameLayout.getLineWidth(0) - topicNameLayout.getLineLeft(0);
float l2w = topicNameLayout.getLineWidth(1) - topicNameLayout.getLineLeft(1);
textWidth = Math.max(l1w, l2w);
float r = (AndroidUtilities.dp(11) + (int) Theme.chat_topicTextPaint.getTextSize()) / 1.5f;
boolean same = false;
AndroidUtilities.rectTmp.set(0, 0, R, R);
topicPath.arcTo(AndroidUtilities.rectTmp, 180, 90);
if (Math.abs(l1w - l2w) <= (padright - padright1)) {
l1w = Math.max(l1w, l2w + (padright - padright1));
l2w = Math.max(l2w, l1w - (padright - padright1));
same = true;
}
AndroidUtilities.rectTmp.set(padleft + padright1 + l1w - r, 0, padleft + padright1 + l1w, r);
topicPath.arcTo(AndroidUtilities.rectTmp, 270, 90);
float midly = AndroidUtilities.dp(11) + Theme.chat_topicTextPaint.getTextSize();
float r2 = Math.min(r, Math.abs(l1w - AndroidUtilities.dp(18 - 5) - l2w));
if (!same) {
if (l1w - (padright - padright1) > l2w) {
AndroidUtilities.rectTmp.set(padleft + padright1 + l1w - r2, midly - r2, padleft + padright1 + l1w, midly);
topicPath.arcTo(AndroidUtilities.rectTmp, 0, 90);
AndroidUtilities.rectTmp.set(padleft + padright + l2w, midly, padleft + padright + l2w + r2, midly + r2);
topicPath.arcTo(AndroidUtilities.rectTmp, 270, -90);
} else {
midly = topicHeight - midly;
AndroidUtilities.rectTmp.set(padleft + padright1 + l1w, midly - r2, padleft + padright1 + l1w + r2, midly);
topicPath.arcTo(AndroidUtilities.rectTmp, 180, -90);
AndroidUtilities.rectTmp.set(padleft + padright + l2w - r2, midly, padleft + padright + l2w, midly + r2);
topicPath.arcTo(AndroidUtilities.rectTmp, 270, 90);
}
}
topicArrowDrawable.setBounds(
(int) (padleft + padright + AndroidUtilities.dp(-4) + l2w - arrowsz),
(int) ((topicHeight - AndroidUtilities.dp(11) - Theme.chat_topicTextPaint.getTextSize() + topicHeight) / 2f - arrowsz / 2),
(int) (padleft + padright + AndroidUtilities.dp(-4) + l2w),
(int) ((topicHeight - AndroidUtilities.dp(11) - Theme.chat_topicTextPaint.getTextSize() + topicHeight) / 2f + arrowsz / 2)
);
AndroidUtilities.rectTmp.set(padleft + padright + l2w - r, topicHeight - r, padleft + padright + l2w, topicHeight);
topicPath.arcTo(AndroidUtilities.rectTmp, 0, 90);
AndroidUtilities.rectTmp.set(0, topicHeight - R, R, topicHeight);
topicPath.arcTo(AndroidUtilities.rectTmp, 90, 90);
topicPath.close();
} else if (lineCount == 1) {
topicHeight = AndroidUtilities.dp(11) + (int) Theme.chat_topicTextPaint.getTextSize();
textWidth = topicNameLayout.getLineWidth(0) - topicNameLayout.getLineLeft(0);
AndroidUtilities.rectTmp.set(0, 0, padleft + padright + textWidth, topicHeight);
topicArrowDrawable.setBounds(
(int) (padleft + padright + AndroidUtilities.dp(-4) + textWidth - arrowsz),
(int) (topicHeight / 2f - arrowsz / 2),
(int) (padleft + padright + AndroidUtilities.dp(-4) + textWidth),
(int) (topicHeight / 2f + arrowsz / 2)
);
topicPath.addRoundRect(AndroidUtilities.rectTmp, R, R, Path.Direction.CW);
}
topicWidth = (int) (padleft + padright -AndroidUtilities.dp(1) + textWidth);
int occupingHeight = 0;
if (!messageObject.isAnyKindOfSticker() && messageObject.type != MessageObject.TYPE_ROUND_VIDEO) {
occupingHeight += AndroidUtilities.dp(6) + topicHeight;
if (messageObject.type != MessageObject.TYPE_TEXT) {
occupingHeight += AndroidUtilities.dp(9);
}
}
if (topicSelectorDrawable == null) {
topicSelectorDrawable = Theme.createSelectorDrawable(topicBackgroundColor, Theme.RIPPLE_MASK_ALL);
topicSelectorDrawable.setCallback(cell);
} else {
Theme.setSelectorDrawableColor(topicSelectorDrawable, topicBackgroundColor, true);
}
topicPaint.setColor(topicBackgroundColor);
if (topicIconDrawable != null) {
if (topicIconDrawableBounds == null) {
topicIconDrawableBounds = new Rect();
}
topicIconDrawableBounds.set(
AndroidUtilities.dp(3 + 2f),
AndroidUtilities.dp(2 + (lineCount == 2 ? 3 : 0)),
AndroidUtilities.dp(3 + 2) + iconsz,
AndroidUtilities.dp(2 + (lineCount == 2 ? 3 : 0)) + iconsz
);
topicIconDrawable.setBounds(topicIconDrawableBounds);
}
return occupingHeight;
}
public void onAttached(ChatMessageCell cell) {
if (topicIconDrawable instanceof AnimatedEmojiDrawable && cell != null) {
((AnimatedEmojiDrawable) topicIconDrawable).addView(cell::invalidateOutbounds);
}
}
public void onDetached(ChatMessageCell cell) {
if (topicIconDrawable instanceof AnimatedEmojiDrawable && cell != null) {
((AnimatedEmojiDrawable) topicIconDrawable).removeView(cell::invalidateOutbounds);
}
}
private void setupColors(int iconColor) {
if (lastMessageObject != null && lastMessageObject.shouldDrawWithoutBackground()) {
topicNameColor = getThemedColor(Theme.key_chat_stickerReplyNameText);
} else if (lastMessageObject != null && lastMessageObject.isOutOwner()) {
topicNameColor = getThemedColor(Theme.key_chat_outReactionButtonText);
topicBackgroundColor = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_outReactionButtonBackground), 38);
} else {
if (topicHSV == null) {
topicHSV = new float[3];
}
Color.colorToHSV(iconColor, topicHSV);
float hue = topicHSV[0];
float sat = topicHSV[1];
if (sat <= 0.02f) {
topicNameColor = getThemedColor(Theme.key_chat_inReactionButtonText);
topicBackgroundColor = ColorUtils.setAlphaComponent(getThemedColor(Theme.key_chat_inReactionButtonBackground), 38);
} else {
Color.colorToHSV(getThemedColor(Theme.key_chat_inReactionButtonText), topicHSV);
topicHSV[0] = hue;
float[] hueRanges = Theme.isCurrentThemeDark() ? darkHueRanges : lightHueRanges;
float[] satValues = Theme.isCurrentThemeDark() ? darkSatValues : lightSatValues;
float[] valValues = Theme.isCurrentThemeDark() ? darkValValues : lightValValues;
for (int i = 1; i < hueRanges.length; ++i) {
if (hue <= hueRanges[i]) {
float t = (hue - hueRanges[i - 1]) / (hueRanges[i] - hueRanges[i - 1]);
topicHSV[1] = AndroidUtilities.lerp(satValues[i - 1], satValues[i], t);
topicHSV[2] = AndroidUtilities.lerp(valValues[i - 1], valValues[i], t);
break;
}
}
topicNameColor = Color.HSVToColor(Color.alpha(getThemedColor(Theme.key_chat_inReactionButtonText)), topicHSV);
topicBackgroundColor = Color.HSVToColor(38, topicHSV);
}
}
}
public boolean checkTouchEvent(MotionEvent event) {
if (topicHitRect == null) {
topicPressed = false;
return false;
}
boolean hit = topicHitRect.contains(event.getX(), event.getY());
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (hit) {
if (topicSelectorDrawable != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
topicSelectorDrawable.setHotspot(event.getX() - topicHitRect.left, event.getY() - topicHitRect.top);
}
topicSelectorDrawable.setState(pressedState);
}
topicPressed = true;
} else {
topicPressed = false;
}
return topicPressed;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (topicPressed != hit) {
if (topicPressed && topicSelectorDrawable != null) {
topicSelectorDrawable.setState(idleState);
}
topicPressed = hit;
}
return topicPressed;
} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (topicPressed) {
topicPressed = false;
if (topicSelectorDrawable != null) {
topicSelectorDrawable.setState(idleState);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
onClick();
return true;
}
}
}
return false;
}
public int width() {
return topicWidth;
}
public int height() {
return topicHeight;
}
public void draw(Canvas canvas, float x, float y, float alpha) {
if (topicIconWaiting && topicIconDrawable instanceof AnimatedEmojiDrawable) {
int iconColor = AnimatedEmojiDrawable.getDominantColor((AnimatedEmojiDrawable) topicIconDrawable);
if (iconColor != 0) {
topicIconWaiting = false;
setupColors(iconColor);
}
}
canvas.save();
if (lastMessageObject != null && lastMessageObject.shouldDrawWithoutBackground()) {
topicPath.offset(x, y);
int oldAlpha1 = -1, oldAlpha2 = -1;
if (alpha < 1) {
oldAlpha1 = getThemedPaint(Theme.key_paint_chatActionBackground).getAlpha();
getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha((int) (oldAlpha1 * alpha));
}
canvas.drawPath(topicPath, getThemedPaint(Theme.key_paint_chatActionBackground));
if (hasGradientService()) {
if (alpha < 1) {
oldAlpha2 = Theme.chat_actionBackgroundGradientDarkenPaint.getAlpha();
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha((int) (oldAlpha2 * alpha));
}
canvas.drawPath(topicPath, Theme.chat_actionBackgroundGradientDarkenPaint);
}
if (oldAlpha1 >= 0) {
getThemedPaint(Theme.key_paint_chatActionBackground).setAlpha(oldAlpha1);
}
if (oldAlpha2 >= 0) {
Theme.chat_actionBackgroundGradientDarkenPaint.setAlpha(oldAlpha2);
}
topicPath.offset(-x, -y);
canvas.translate(x, y);
} else {
canvas.translate(x, y);
if (topicPath != null && topicPaint != null) {
if (topicBackgroundColorAnimated != null) {
topicPaint.setColor(topicBackgroundColorAnimated.set(topicBackgroundColor));
} else {
topicPaint.setColor(topicBackgroundColor);
}
int wasAlpha = topicPaint.getAlpha();
topicPaint.setAlpha((int) (wasAlpha * alpha));
canvas.drawPath(topicPath, topicPaint);
topicPaint.setAlpha(wasAlpha);
}
}
if (topicHitRect == null) {
topicHitRect = new RectF();
}
topicHitRect.set(x, y, x + topicWidth, y + topicHeight);
if (topicSelectorDrawable != null) {
canvas.save();
canvas.clipPath(topicPath);
AndroidUtilities.rectTmp2.set(0, 0, topicWidth, topicHeight);
topicSelectorDrawable.setBounds(AndroidUtilities.rectTmp2);
topicSelectorDrawable.draw(canvas);
canvas.restore();
}
int nameColor = topicNameColor;
if (topicNameLayout != null) {
canvas.save();
canvas.translate(AndroidUtilities.dp(17) + Theme.chat_topicTextPaint.getTextSize(), AndroidUtilities.dp(4.5f));
if (topicNameColorAnimated != null) {
Theme.chat_topicTextPaint.setColor(nameColor = topicNameColorAnimated.set(topicNameColor));
} else {
Theme.chat_topicTextPaint.setColor(nameColor = topicNameColor);
}
Theme.chat_topicTextPaint.setAlpha((int) (Theme.chat_topicTextPaint.getAlpha() * alpha));
topicNameLayout.draw(canvas);
canvas.restore();
}
if (topicArrowDrawable != null) {
int arrowColor = ColorUtils.setAlphaComponent(nameColor, 140);
if (topicArrowColor != arrowColor) {
topicArrowDrawable.setColorFilter(new PorterDuffColorFilter(topicArrowColor = arrowColor, PorterDuff.Mode.MULTIPLY));
}
topicArrowDrawable.draw(canvas);
}
canvas.restore();
}
public void drawOutbounds(Canvas canvas, float alpha) {
if (topicHitRect != null) {
canvas.save();
canvas.translate(topicHitRect.left, topicHitRect.top);
topicIconDrawable.setAlpha((int) (255 * alpha));
topicIconDrawable.setBounds(topicIconDrawableBounds);
topicIconDrawable.draw(canvas);
canvas.restore();
}
}
public void resetClick() {
if (topicSelectorDrawable != null) {
topicSelectorDrawable.setState(idleState);
}
}
private int getThemedColor(String key) {
Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
}
private Paint getThemedPaint(String key) {
Paint paint = resourcesProvider != null ? resourcesProvider.getPaint(key) : null;
return paint != null ? paint : Theme.getThemePaint(key);
}
private boolean hasGradientService() {
return resourcesProvider != null ? resourcesProvider.hasGradientService() : Theme.hasGradientService();
}
}

View File

@ -69,6 +69,7 @@ import org.telegram.messenger.UserObject;
import org.telegram.messenger.voip.VoIPService;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.ActionBarMenuSubItem;
import org.telegram.ui.ActionBar.AlertDialog;
@ -489,6 +490,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
}
avatars = new AvatarsImageView(context, false);
avatars.setAvatarsTextSize(AndroidUtilities.dp(21));
avatars.setDelegate(() -> updateAvatars(true));
avatars.setVisibility(GONE);
addView(avatars, LayoutHelper.createFrame(108, 36, Gravity.LEFT | Gravity.TOP));
@ -1980,7 +1982,7 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
frameLayout.invalidate();
}
updateAvatars(avatars.avatarsDarawable.wasDraw && updateAnimated);
updateAvatars(avatars.avatarsDrawable.wasDraw && updateAnimated);
} else {
if (voIPService != null && voIPService.groupCall != null) {
updateAvatars(currentStyle == STYLE_ACTIVE_GROUP_CALL);
@ -2051,14 +2053,14 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
private void updateAvatars(boolean animated) {
if (!animated) {
if (avatars.avatarsDarawable.transitionProgressAnimator != null) {
avatars.avatarsDarawable.transitionProgressAnimator.cancel();
avatars.avatarsDarawable.transitionProgressAnimator = null;
if (avatars.avatarsDrawable.transitionProgressAnimator != null) {
avatars.avatarsDrawable.transitionProgressAnimator.cancel();
avatars.avatarsDrawable.transitionProgressAnimator = null;
}
}
ChatObject.Call call;
TLRPC.User userCall;
if (avatars.avatarsDarawable.transitionProgressAnimator == null) {
if (avatars.avatarsDrawable.transitionProgressAnimator == null) {
int currentAccount;
if (currentStyle == STYLE_INACTIVE_GROUP_CALL) {
if (chatActivity != null) {
@ -2272,41 +2274,4 @@ public class FragmentContextView extends FrameLayout implements NotificationCent
Integer color = resourcesProvider != null ? resourcesProvider.getColor(key) : null;
return color != null ? color : Theme.getColor(key);
}
public interface ChatActivityInterface {
default ChatObject.Call getGroupCall() {
return null;
}
default TLRPC.Chat getCurrentChat() {
return null;
}
default TLRPC.User getCurrentUser() {
return null;
}
long getDialogId();
default void scrollToMessageId(int id, int i, boolean b, int i1, boolean b1, int i2) {
}
default boolean shouldShowImport() {
return false;
}
default boolean openedWithLivestream() {
return false;
}
default long getMergeDialogId() {
return 0;
}
default int getTopicId() {
return 0;
}
}
}

View File

@ -680,7 +680,7 @@ public class GroupCallPip implements NotificationCenter.NotificationCenterDelega
}
private void updateAvatars(boolean animated) {
if (avatarsImageView.avatarsDarawable.transitionProgressAnimator == null) {
if (avatarsImageView.avatarsDrawable.transitionProgressAnimator == null) {
ChatObject.Call call;
VoIPService voIPService = VoIPService.getSharedInstance();

View File

@ -280,9 +280,11 @@ public class GroupCallPipAlertView extends LinearLayout implements VoIPService.S
super.onAttachedToWindow();
VoIPService service = VoIPService.getSharedInstance();
if (service != null && service.groupCall != null) {
int color2 = AvatarDrawable.getColorForId(service.getChat().id);
AvatarDrawable avatarDrawable = new AvatarDrawable();
avatarDrawable.setColor(color2);
avatarDrawable.setColor(
Theme.getColor(Theme.keys_avatar_background[AvatarDrawable.getColorIndex(service.getChat().id)]),
Theme.getColor(Theme.keys_avatar_background2[AvatarDrawable.getColorIndex(service.getChat().id)])
);
avatarDrawable.setInfo(service.getChat());
avatarImageView.setImage(ImageLocation.getForLocal(service.getChat().photo.photo_small), "50_50", avatarDrawable, null);

View File

@ -205,6 +205,9 @@ public class HintView extends FrameLayout {
if (!messageObject.isOutOwner() && cell.isDrawNameLayout()) {
top += AndroidUtilities.dp(20);
}
if (!messageObject.shouldDrawWithoutBackground() && cell.isDrawTopic()) {
top += AndroidUtilities.dp(5) + cell.getDrawTopicHeight();
}
}
if (!isTopArrow && top <= getMeasuredHeight() + AndroidUtilities.dp(10)) {
return false;

View File

@ -30,6 +30,7 @@ public class LetterDrawable extends Drawable {
public static Paint paint = new Paint();
private static TextPaint namePaint;
private static TextPaint namePaintTopic;
private static TextPaint namePaintSmallTopic;
private RectF rect = new RectF();
private StaticLayout textLayout;
@ -40,6 +41,7 @@ public class LetterDrawable extends Drawable {
public static final int STYLE_DEFAULT = 0;
public static final int STYLE_TOPIC_DRAWABLE = 1;
public static final int STYLE_SMALL_TOPIC_DRAWABLE = 2;
int style;
final TextPaint textPaint;
public float scale = 1f;
@ -48,7 +50,6 @@ public class LetterDrawable extends Drawable {
this(null, 0);
}
public LetterDrawable(Theme.ResourcesProvider resourcesProvider, int style) {
super();
this.style = style;
@ -60,7 +61,7 @@ public class LetterDrawable extends Drawable {
paint.setColor(Theme.getColor(Theme.key_sharedMedia_linkPlaceholder, resourcesProvider));
namePaint.setColor(Theme.getColor(Theme.key_sharedMedia_linkPlaceholderText, resourcesProvider));
textPaint = namePaint;
} else {
} else if (style == STYLE_TOPIC_DRAWABLE) {
if (namePaintTopic == null) {
namePaintTopic = new TextPaint(Paint.ANTI_ALIAS_FLAG);
}
@ -68,6 +69,14 @@ public class LetterDrawable extends Drawable {
namePaintTopic.setTextSize(AndroidUtilities.dp(13));
namePaintTopic.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
textPaint = namePaintTopic;
} else {
if (namePaintSmallTopic == null) {
namePaintSmallTopic = new TextPaint(Paint.ANTI_ALIAS_FLAG);
}
namePaintSmallTopic.setColor(Color.WHITE);
namePaintSmallTopic.setTextSize(Theme.chat_topicTextPaint.getTextSize() * .75f);
namePaintSmallTopic.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
textPaint = namePaintSmallTopic;
}
}

View File

@ -0,0 +1,73 @@
package org.telegram.ui.Components.ListView;
import androidx.recyclerview.widget.DiffUtil;
import org.telegram.ui.Components.RecyclerListView;
import java.util.ArrayList;
public abstract class AdapterWithDiffUtils extends RecyclerListView.SelectionAdapter {
DiffUtilsCallback callback = new DiffUtilsCallback();
public void setItems(ArrayList<? extends Item> oldItems, ArrayList<? extends Item> newItems) {
if (newItems == null) {
newItems = new ArrayList<>();
}
callback.setItems(oldItems, newItems);
DiffUtil.calculateDiff(callback).dispatchUpdatesTo(this);
}
public static class Item {
public final int viewType;
public boolean selectable;
public Item(int viewType, boolean selectable) {
this.viewType = viewType;
this.selectable = selectable;
}
boolean compare(Item item) {
if (viewType != item.viewType) {
return false;
}
if (this.equals(item)) {
return true;
}
return false;
}
}
private class DiffUtilsCallback extends DiffUtil.Callback {
ArrayList<? extends Item> oldItems;
ArrayList<? extends Item> newItems;
public void setItems(ArrayList<? extends Item> oldItems, ArrayList<? extends Item> newItems) {
this.oldItems = oldItems;
this.newItems = newItems;
}
@Override
public int getOldListSize() {
return oldItems.size();
}
@Override
public int getNewListSize() {
return newItems.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldItems.get(oldItemPosition).compare(newItems.get(newItemPosition));
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return false;
}
}
}

View File

@ -29,6 +29,8 @@ public class LoadingDrawable extends Drawable {
private long start = -1;
private LinearGradient gradient;
private int gradientColor1, gradientColor2;
public String colorKey1 = Theme.key_dialogBackground;
public String colorKey2 = Theme.key_dialogBackgroundGray;
private int gradientWidth;
public Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
@ -46,8 +48,8 @@ public class LoadingDrawable extends Drawable {
return;
}
int gwidth = Math.min(AndroidUtilities.dp(400), bounds.width());
int color1 = Theme.getColor(Theme.key_dialogBackground, resourcesProvider);
int color2 = Theme.getColor(Theme.key_dialogBackgroundGray, resourcesProvider);
int color1 = Theme.getColor(colorKey1, resourcesProvider);
int color2 = Theme.getColor(colorKey2, resourcesProvider);
if (gradient == null || gwidth != gradientWidth || color1 != gradientColor1 || color2 != gradientColor2) {
gradientWidth = gwidth;
gradientColor1 = color1;

View File

@ -149,6 +149,8 @@ public class MessageContainsEmojiButton extends FrameLayout implements Notificat
mainText = parts[0];
endText = parts[1];
loadingDrawable = new LoadingDrawable(resourcesProvider);
loadingDrawable.colorKey1 = Theme.key_actionBarDefaultSubmenuBackground;
loadingDrawable.colorKey2 = Theme.key_listSelector;
loadingDrawable.paint.setPathEffect(new CornerPathEffect(AndroidUtilities.dp(4)));
}
}

View File

@ -110,6 +110,7 @@ public class MotionBackgroundDrawable extends Drawable {
private ColorFilter legacyBitmapColorFilter;
private int legacyBitmapColor;
private float indeterminateSpeedScale = 1f;
private boolean isIndeterminateAnimation;
private Paint overrideBitmapPaint;
@ -861,7 +862,7 @@ public class MotionBackgroundDrawable extends Drawable {
float progress;
boolean isNeedGenerateGradient = postInvalidateParent || rotatingPreview;
if (isIndeterminateAnimation) {
posAnimationProgress += dt / 12000f;
posAnimationProgress += (dt / 12000f) * indeterminateSpeedScale;
if (posAnimationProgress >= 1.0f) {
posAnimationProgress = 0.0f;
}
@ -1007,6 +1008,18 @@ public class MotionBackgroundDrawable extends Drawable {
return colors[0] == colors[1] && colors[0] == colors[2] && colors[0] == colors[3];
}
public float getIndeterminateSpeedScale() {
return indeterminateSpeedScale;
}
public void setIndeterminateSpeedScale(float indeterminateSpeedScale) {
this.indeterminateSpeedScale = indeterminateSpeedScale;
}
public boolean isIndeterminateAnimation() {
return isIndeterminateAnimation;
}
public void setIndeterminateAnimation(boolean isIndeterminateAnimation) {
this.isIndeterminateAnimation = isIndeterminateAnimation;
}

View File

@ -120,6 +120,7 @@ public class LimitReachedBottomSheet extends BottomSheetWithRecyclerListView {
} else if (type == TYPE_TO_MANY_COMMUNITIES) {
loadInactiveChannels();
}
updatePremiumButtonText();
}
@Override
@ -128,7 +129,6 @@ public class LimitReachedBottomSheet extends BottomSheetWithRecyclerListView {
Context context = containerView.getContext();
premiumButtonView = new PremiumButtonView(context, true);
updatePremiumButtonText();
if (!hasFixedSize) {
divider = new View(context) {

View File

@ -65,6 +65,7 @@ public class PremiumFeatureBottomSheet extends BottomSheet implements Notificati
SvgHelper.SvgDrawable svgIcon;
private final int startType;
private final boolean onlySelectedType;
private boolean forceAbout;
private PremiumPreviewFragment.SubscriptionTier selectedTier;
private int gradientAlpha = 255;
@ -316,7 +317,7 @@ public class PremiumFeatureBottomSheet extends BottomSheet implements Notificati
if (fragment != null && fragment.getVisibleDialog() != null) {
fragment.getVisibleDialog().dismiss();
}
if (onlySelectedType && fragment != null) {
if ((onlySelectedType || forceAbout) && fragment != null) {
fragment.presentFragment(new PremiumPreviewFragment(PremiumPreviewFragment.featureTypeToServerString(featureData.type)));
} else {
PremiumPreviewFragment.buyPremium(fragment, selectedTier, PremiumPreviewFragment.featureTypeToServerString(featureData.type));
@ -414,9 +415,17 @@ public class PremiumFeatureBottomSheet extends BottomSheet implements Notificati
containerView.setPadding(backgroundPaddingLeft, backgroundPaddingTop - 1, backgroundPaddingLeft, 0);
}
public PremiumFeatureBottomSheet setForceAbout() {
this.forceAbout = true;
premiumButtonView.clearOverlayText();
setButtonText();
return this;
}
private void setButtonText() {
if (onlySelectedType) {
if (forceAbout) {
premiumButtonView.buttonTextView.setText(LocaleController.getString(R.string.AboutTelegramPremium));
} else if (onlySelectedType) {
if (startType == PremiumPreviewFragment.PREMIUM_FEATURE_REACTIONS) {
premiumButtonView.buttonTextView.setText(LocaleController.getString(R.string.UnlockPremiumReactions));
premiumButtonView.setIcon(R.raw.unlock_icon);

View File

@ -172,7 +172,7 @@ public class PremiumLockIconView extends ImageView {
int x = (int) (stepW * i);
int y = (int) (stepH * j);
int pixel = bitmap.getPixel(x, y);
if (pixel != Color.TRANSPARENT) {
if (Color.alpha(pixel) > 200) {
r += Color.red(pixel);
g += Color.green(pixel);
b += Color.blue(pixel);

View File

@ -69,8 +69,8 @@ public class VideoScreenPreview extends FrameLayout implements PagerHeaderView,
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(ApplicationLoader.applicationContext, Uri.fromFile(file));
int width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
int width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
retriever.release();
aspectRatio = width / (float) height;
} else {
@ -244,8 +244,8 @@ public class VideoScreenPreview extends FrameLayout implements PagerHeaderView,
}
}
attachFileName = FileLoader.getAttachFileName(document);
imageReceiver.setImage(null, null, drawable, null, null, 1);
FileLoader.getInstance(currentAccount).loadFile(document, null, FileLoader.PRIORITY_HIGH, 0);
imageReceiver.setImage(null, null, drawable, null, premiumPromo, 1);
FileLoader.getInstance(currentAccount).loadFile(document, premiumPromo, FileLoader.PRIORITY_HIGH, 0);
this.document = document;
Utilities.globalQueue.postRunnable(() -> {
File file = FileLoader.getInstance(currentAccount).getPathToAttach(document);
@ -577,7 +577,7 @@ public class VideoScreenPreview extends FrameLayout implements PagerHeaderView,
"&dc=" + document.dc_id +
"&size=" + document.size +
"&mime=" + URLEncoder.encode(document.mime_type, "UTF-8") +
"&rid=" + FileLoader.getInstance(currentAccount).getFileReference(document) +
"&rid=" + FileLoader.getInstance(currentAccount).getFileReference(MediaDataController.getInstance(currentAccount).getPremiumPromo()) +
"&name=" + URLEncoder.encode(FileLoader.getDocumentFileName(document), "UTF-8") +
"&reference=" + Utilities.bytesToHex(document.file_reference != null ? document.file_reference : new byte[0]);
uri = Uri.parse("tg://" + attachFileName + params);

View File

@ -7,10 +7,12 @@ import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.view.View;

View File

@ -50,10 +50,15 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
public boolean skipFrameUpdate;
public static native long create(String src, String json, int w, int h, int[] params, boolean precache, int[] colorReplacement, boolean limitFps, int fitzModifier);
protected static native long createWithJson(String json, String name, int[] params, int[] colorReplacement);
public static native void destroy(long ptr);
private static native void setLayerColor(long ptr, String layer, int color);
private static native void replaceColors(long ptr, int[] colorReplacement);
public static native int getFrame(long ptr, int frame, Bitmap bitmap, int w, int h, int stride, boolean clear);
protected final int width;
@ -110,8 +115,8 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
private boolean applyTransformation;
private boolean needScale;
private final RectF dstRect = new RectF();
private RectF dstRectBackground;
private Paint backgroundPaint;
private RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
private Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT];
protected static final Handler uiHandler = new Handler(Looper.getMainLooper());
protected volatile boolean isRunning;
protected volatile boolean isRecycled;
@ -177,10 +182,15 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
if (lottieCacheGenerateQueue == null) {
createCacheGenQueue();
}
BitmapsCache.incrementTaskCounter();
lottieCacheGenerateQueue.postRunnable(cacheGenerateTask = () -> {
BitmapsCache bitmapsCacheFinal = bitmapsCache;
if (bitmapsCacheFinal != null) {
bitmapsCacheFinal.createCache();
try {
BitmapsCache bitmapsCacheFinal = bitmapsCache;
if (bitmapsCacheFinal != null) {
bitmapsCacheFinal.createCache();
}
} catch (Throwable throwable) {
}
uiHandler.post(uiRunnableCacheFinished);
});
@ -191,7 +201,10 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
private Runnable uiRunnableCacheFinished = new Runnable() {
@Override
public void run() {
cacheGenerateTask = null;
if (cacheGenerateTask != null) {
BitmapsCache.decrementTaskCounter();
cacheGenerateTask = null;
}
generatingCache = false;
decodeFrameFinishedInternal();
}
@ -207,6 +220,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
protected void checkRunningTasks() {
if (cacheGenerateTask != null) {
lottieCacheGenerateQueue.cancelRunnable(cacheGenerateTask);
BitmapsCache.decrementTaskCounter();
cacheGenerateTask = null;
}
if (!hasParentView() && nextRenderingBitmap != null && loadFrameTask != null) {
@ -264,6 +278,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
private boolean genCacheSend;
protected Runnable loadFrameRunnable = new Runnable() {
private long lastUpdate = 0;
@Override
public void run() {
if (isRecycled) {
@ -714,7 +729,6 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
return;
}
parentViews.add(parent);
checkCacheCancel();
}
public void removeParentView(ImageReceiver parent) {
@ -726,6 +740,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
}
private Runnable cancelCache;
public void checkCacheCancel() {
if (bitmapsCache == null || lottieCacheGenerateQueue == null || cacheGenerateTask == null) {
return;
@ -736,16 +751,14 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
} else {
mustCancel = mustCancel && masterParent == null;
}
if (mustCancel && cancelCache == null) {
AndroidUtilities.runOnUIThread(cancelCache = () -> {
if (mustCancel) {
if (cacheGenerateTask != null) {
lottieCacheGenerateQueue.cancelRunnable(cacheGenerateTask);
if (bitmapsCache != null) {
bitmapsCache.cancelCreate();
}
}, 600);
} else if (!mustCancel && cancelCache != null) {
AndroidUtilities.cancelRunOnUIThread(cancelCache);
cancelCache = null;
BitmapsCache.decrementTaskCounter();
cacheGenerateTask = null;
}
generatingCache = false;
genCacheSend = false;
}
}
@ -907,10 +920,6 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
}
protected boolean scheduleNextGetFrame() {
return scheduleNextGetFrame(false);
}
protected boolean scheduleNextGetFrame(boolean allowGroupedUpdateLocal) {
if (loadFrameTask != null || nextRenderingBitmap != null || !canLoadFrames() || loadingInBackground || destroyWhenDone || !isRunning && (!decodeSingleFrame || decodeSingleFrame && singleFrameDecoded)) {
return false;
}
@ -926,8 +935,8 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
newReplaceColors = null;
}
loadFrameTask = loadFrameRunnable;
if (allowGroupedUpdateLocal && shouldLimitFps) {
DispatchQueuePoolBackground.execute(loadFrameTask);
if (shouldLimitFps) {
DispatchQueuePoolBackground.execute(loadFrameTask, frameWaitSync != null);
} else {
loadFrameRunnableQueue.execute(loadFrameTask);
}
@ -978,7 +987,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
if (resetFrame && !isRunning) {
isRunning = true;
}
if (scheduleNextGetFrame(false)) {
if (scheduleNextGetFrame()) {
if (!async) {
try {
frameWaitSync.await();
@ -1082,27 +1091,27 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
}
}
}
scheduleNextGetFrame(true);
scheduleNextGetFrame();
}
@Override
public void draw(Canvas canvas) {
drawInternal(canvas, false, 0);
drawInternal(canvas, false, 0, 0);
}
public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter) {
if (dstRectBackground == null) {
dstRectBackground = new RectF();
backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
backgroundPaint.setFilterBitmap(true);
public void drawInBackground(Canvas canvas, float x, float y, float w, float h, int alpha, ColorFilter colorFilter, int threadIndex) {
if (dstRectBackground[threadIndex] == null) {
dstRectBackground[threadIndex] = new RectF();
backgroundPaint[threadIndex] = new Paint(Paint.ANTI_ALIAS_FLAG);
backgroundPaint[threadIndex].setFilterBitmap(true);
}
backgroundPaint.setAlpha(alpha);
backgroundPaint.setColorFilter(colorFilter);
dstRectBackground.set(x, y, x + w, y + h);
drawInternal(canvas, true, 0);
backgroundPaint[threadIndex].setAlpha(alpha);
backgroundPaint[threadIndex].setColorFilter(colorFilter);
dstRectBackground[threadIndex].set(x, y, x + w, y + h);
drawInternal(canvas, true, 0, threadIndex);
}
public void drawInternal(Canvas canvas, boolean drawInBackground, long time) {
public void drawInternal(Canvas canvas, boolean drawInBackground, long time, int threadIndex) {
if (!canLoadFrames() || destroyWhenDone) {
return;
}
@ -1110,8 +1119,8 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
updateCurrentFrame(time, false);
}
RectF rect = drawInBackground ? dstRectBackground : dstRect;
Paint paint = drawInBackground ? backgroundPaint : getPaint();
RectF rect = drawInBackground ? dstRectBackground[threadIndex] : dstRect;
Paint paint = drawInBackground ? backgroundPaint[threadIndex] : getPaint();
if (paint.getAlpha() == 0) {
return;
@ -1165,7 +1174,7 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
}
if (isRunning) {
if (renderingBitmap == null && nextRenderingBitmap == null) {
scheduleNextGetFrame(true);
scheduleNextGetFrame();
} else if (nextRenderingBitmap != null && (renderingBitmap == null || (timeDiff >= timeCheck && !skipFrameUpdate))) {
if (vibrationPattern != null && currentParentView != null && allowVibration) {
Integer force = vibrationPattern.get(currentFrame - 1);
@ -1315,24 +1324,30 @@ public class RLottieDrawable extends BitmapDrawable implements Animatable, Bitma
AndroidUtilities.runOnUIThread(onReady);
return;
}
loadFrameRunnableQueue.execute(() -> {
if (bitmapsCache.cacheExist()) {
AndroidUtilities.runOnUIThread(onReady);
} else {
AndroidUtilities.runOnUIThread(() -> {
generatingCache = true;
if (lottieCacheGenerateQueue == null) {
createCacheGenQueue();
generatingCache = true;
if (lottieCacheGenerateQueue == null) {
createCacheGenQueue();
}
if (cacheGenerateTask == null) {
BitmapsCache.incrementTaskCounter();
lottieCacheGenerateQueue.postRunnable(cacheGenerateTask = () -> {
try {
BitmapsCache bitmapsCacheFinal = bitmapsCache;
if (bitmapsCacheFinal != null) {
bitmapsCacheFinal.createCache();
}
} catch (Throwable e) {
FileLog.e(e);
}
AndroidUtilities.runOnUIThread(() -> {
onReady.run();
if (cacheGenerateTask != null) {
cacheGenerateTask = null;
BitmapsCache.decrementTaskCounter();
}
lottieCacheGenerateQueue.postRunnable(cacheGenerateTask = () -> {
BitmapsCache bitmapsCacheFinal = bitmapsCache;
if (bitmapsCacheFinal != null) {
bitmapsCacheFinal.createCache();
}
AndroidUtilities.runOnUIThread(onReady);
});
});
}
});
});
}
}
}

View File

@ -70,7 +70,7 @@ public class ReactedHeaderView extends FrameLayout {
addView(titleView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 40, 0, 62, 0));
avatarsImageView = new AvatarsImageView(context, false);
avatarsImageView.setStyle(AvatarsDarawable.STYLE_MESSAGE_SEEN);
avatarsImageView.setStyle(AvatarsDrawable.STYLE_MESSAGE_SEEN);
addView(avatarsImageView, LayoutHelper.createFrameRelatively(24 + 12 + 12 + 8, LayoutHelper.MATCH_PARENT, Gravity.END | Gravity.CENTER_VERTICAL, 0, 0, 0, 0));
iconView = new ImageView(context);

View File

@ -8,16 +8,13 @@ import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.LongSparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
@ -187,6 +184,7 @@ public class ReactedUsersListView extends FrameLayout {
return !customReactionsEmoji.isEmpty() && messageContainsEmojiButton != null ? messageContainsEmojiButton.getMeasuredHeight() + AndroidUtilities.dp(8) : 0;
}
};
loadingView.setColors(Theme.key_actionBarDefaultSubmenuBackground, Theme.key_listSelector, null);
loadingView.setIsSingleCell(true);
loadingView.setItemsCount(predictiveCount);
@ -388,9 +386,10 @@ public class ReactedUsersListView extends FrameLayout {
titleView.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuItem));
titleView.setEllipsizeByGradient(true);
titleView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
titleView.setWidthWrapContent(true);
titleView.setPadding(0, AndroidUtilities.dp(12), 0, AndroidUtilities.dp(12));
addView(titleView, LayoutHelper.createFrameRelatively(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.START | Gravity.CENTER_VERTICAL, 58, 0, 36 + 6, 0));
titleView.setRightPadding(AndroidUtilities.dp(30));
titleView.setTranslationX(LocaleController.isRTL ? AndroidUtilities.dp(30) : 0);
addView(titleView, LayoutHelper.createFrameRelatively(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.FILL_HORIZONTAL | Gravity.CENTER_VERTICAL, 58, 0, 12, 0));
reactView = new BackupImageView(context);
addView(reactView, LayoutHelper.createFrameRelatively(24, 24, Gravity.END | Gravity.CENTER_VERTICAL, 0, 0, 12, 0));
@ -413,6 +412,7 @@ public class ReactedUsersListView extends FrameLayout {
}
avatarView.setImage(ImageLocation.getForUser(u, ImageLocation.TYPE_SMALL), "50_50", thumb, u);
boolean hasReactImage = false;
if (reaction.reaction != null) {
ReactionsLayoutInBubble.VisibleReaction visibleReaction = ReactionsLayoutInBubble.VisibleReaction.fromTLReaction(reaction.reaction);
if (visibleReaction.emojicon != null) {
@ -420,17 +420,21 @@ public class ReactedUsersListView extends FrameLayout {
if (r != null) {
SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(r.static_icon.thumbs, Theme.key_windowBackgroundGray, 1.0f);
reactView.setImage(ImageLocation.getForDocument(r.center_icon), "40_40_lastframe", "webp", svgThumb, r);
hasReactImage = true;
} else {
reactView.setImageDrawable(null);
}
} else {
reactView.setAnimatedEmojiDrawable(new AnimatedEmojiDrawable(AnimatedEmojiDrawable.CACHE_TYPE_MESSAGES, currentAccount, visibleReaction.documentId));
hasReactImage = true;
}
setContentDescription(LocaleController.formatString("AccDescrReactedWith", R.string.AccDescrReactedWith, UserObject.getUserName(u), reaction.reaction));
} else {
reactView.setImageDrawable(null);
setContentDescription(LocaleController.formatString("AccDescrPersonHasSeen", R.string.AccDescrPersonHasSeen, UserObject.getUserName(u)));
}
titleView.setRightPadding(AndroidUtilities.dp(hasReactImage ? 30 : 0));
titleView.setTranslationX(hasReactImage && LocaleController.isRTL ? AndroidUtilities.dp(30) : 0);
}
@Override

View File

@ -13,7 +13,6 @@ import android.view.ViewConfiguration;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.ChatListItemAnimator;
import org.checkerframework.checker.units.qual.A;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.DocumentObject;
@ -28,7 +27,7 @@ import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.ChatMessageCell;
import org.telegram.ui.Components.AnimatedEmojiDrawable;
import org.telegram.ui.Components.AvatarsDarawable;
import org.telegram.ui.Components.AvatarsDrawable;
import org.telegram.ui.Components.CounterView;
import java.util.ArrayList;
@ -218,12 +217,12 @@ public class ReactionsLayoutInBubble {
button.height = AndroidUtilities.dp(14);
} else {
button.width = (int) (AndroidUtilities.dp(8) + AndroidUtilities.dp(20) + AndroidUtilities.dp(4));
if (button.avatarsDarawable != null && button.users.size() > 0) {
if (button.avatarsDrawable != null && button.users.size() > 0) {
button.users.size();
int c1 = 1;
int c2 = button.users.size() > 1 ? button.users.size() - 1 : 0;
button.width += AndroidUtilities.dp(2) + c1 * AndroidUtilities.dp(20) + c2 * AndroidUtilities.dp(20) * 0.8f + AndroidUtilities.dp(1);
button.avatarsDarawable.height = AndroidUtilities.dp(26);
button.avatarsDrawable.height = AndroidUtilities.dp(26);
} else {
button.width += button.counterDrawable.textPaint.measureText(button.countText) + AndroidUtilities.dp(8);
}
@ -350,7 +349,7 @@ public class ReactionsLayoutInBubble {
}
if (lastButton != null) {
lastDrawingReactionButtonsTmp.remove(button.key);
if (button.x != lastButton.x || button.y != lastButton.y || button.width != lastButton.width || button.count != lastButton.count || button.choosen != lastButton.choosen || button.avatarsDarawable != null || lastButton.avatarsDarawable != null) {
if (button.x != lastButton.x || button.y != lastButton.y || button.width != lastButton.width || button.count != lastButton.count || button.choosen != lastButton.choosen || button.avatarsDrawable != null || lastButton.avatarsDrawable != null) {
button.animateFromX = lastButton.x;
button.animateFromY = lastButton.y;
button.animateFromWidth = lastButton.width;
@ -363,15 +362,15 @@ public class ReactionsLayoutInBubble {
button.counterDrawable.setCount(lastButton.count, false);
button.counterDrawable.setCount(button.count, true);
}
if (button.avatarsDarawable != null || lastButton.avatarsDarawable != null) {
if (button.avatarsDarawable == null) {
if (button.avatarsDrawable != null || lastButton.avatarsDrawable != null) {
if (button.avatarsDrawable == null) {
button.setUsers(new ArrayList<>());
}
if (lastButton.avatarsDarawable == null) {
if (lastButton.avatarsDrawable == null) {
lastButton.setUsers(new ArrayList<>());
}
if (!equalsUsersList(lastButton.users, button.users)) {
button.avatarsDarawable.animateFromState(lastButton.avatarsDarawable, currentAccount, false);
button.avatarsDrawable.animateFromState(lastButton.avatarsDrawable, currentAccount, false);
}
}
changed = true;
@ -493,7 +492,7 @@ public class ReactionsLayoutInBubble {
int lastDrawnTextColor;
int lastDrawnBackgroundColor;
boolean isSelected;
AvatarsDarawable avatarsDarawable;
AvatarsDrawable avatarsDrawable;
ArrayList<TLRPC.User> users;
public ReactionButton(TLRPC.ReactionCount reactionCount, boolean isSmall) {
@ -627,12 +626,12 @@ public class ReactionsLayoutInBubble {
canvas.restore();
}
if (avatarsDarawable != null) {
if (avatarsDrawable != null) {
canvas.save();
canvas.translate(AndroidUtilities.dp(10) + AndroidUtilities.dp(20) + AndroidUtilities.dp(2), 0);
avatarsDarawable.setAlpha(alpha);
avatarsDarawable.setTransitionProgress(progress);
avatarsDarawable.onDraw(canvas);
avatarsDrawable.setAlpha(alpha);
avatarsDrawable.setTransitionProgress(progress);
avatarsDrawable.onDraw(canvas);
canvas.restore();
}
}
@ -688,25 +687,25 @@ public class ReactionsLayoutInBubble {
this.users = users;
if (users != null) {
Collections.sort(users, usersComparator);
if (avatarsDarawable == null) {
avatarsDarawable = new AvatarsDarawable(parentView, false);
avatarsDarawable.transitionDuration = ChatListItemAnimator.DEFAULT_DURATION;
avatarsDarawable.transitionInterpolator = ChatListItemAnimator.DEFAULT_INTERPOLATOR;
avatarsDarawable.setSize(AndroidUtilities.dp(20));
avatarsDarawable.width = AndroidUtilities.dp(100);
avatarsDarawable.height = height;
avatarsDarawable.setAvatarsTextSize(AndroidUtilities.dp(22));
if (avatarsDrawable == null) {
avatarsDrawable = new AvatarsDrawable(parentView, false);
avatarsDrawable.transitionDuration = ChatListItemAnimator.DEFAULT_DURATION;
avatarsDrawable.transitionInterpolator = ChatListItemAnimator.DEFAULT_INTERPOLATOR;
avatarsDrawable.setSize(AndroidUtilities.dp(20));
avatarsDrawable.width = AndroidUtilities.dp(100);
avatarsDrawable.height = height;
avatarsDrawable.setAvatarsTextSize(AndroidUtilities.dp(22));
if (attached) {
avatarsDarawable.onAttachedToWindow();
avatarsDrawable.onAttachedToWindow();
}
}
for (int i = 0; i < users.size(); i++) {
if (i == 3) {
break;
}
avatarsDarawable.setObject(i, currentAccount, users.get(i));
avatarsDrawable.setObject(i, currentAccount, users.get(i));
}
avatarsDarawable.commitTransition(false);
avatarsDrawable.commitTransition(false);
}
}
@ -714,8 +713,8 @@ public class ReactionsLayoutInBubble {
if (imageReceiver != null) {
imageReceiver.onAttachedToWindow();
}
if (avatarsDarawable != null) {
avatarsDarawable.onAttachedToWindow();
if (avatarsDrawable != null) {
avatarsDrawable.onAttachedToWindow();
}
if (animatedEmojiDrawable != null) {
animatedEmojiDrawable.addView(parentView);
@ -726,8 +725,8 @@ public class ReactionsLayoutInBubble {
if (imageReceiver != null) {
imageReceiver.onDetachedFromWindow();
}
if (avatarsDarawable != null) {
avatarsDarawable.onDetachedFromWindow();
if (avatarsDrawable != null) {
avatarsDrawable.onDetachedFromWindow();
}
if (animatedEmojiDrawable != null) {
animatedEmojiDrawable.removeView(parentView);

View File

@ -8,7 +8,7 @@ import org.telegram.ui.Components.AnimatedEmojiSpan;
public class ReactionsUtils {
public static final String APPEAR_ANIMATION_FILTER = "30_30_nolimit_pcache";
public static final String APPEAR_ANIMATION_FILTER = "30_30_nolimit";
public static final String SELECT_ANIMATION_FILTER = "60_60_pcache";
public static final String ACTIVATE_ANIMATION_FILTER = "30_30_pcache";

View File

@ -56,6 +56,7 @@ import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.ListView.AdapterWithDiffUtils;
import org.telegram.ui.Components.Premium.PremiumFeatureBottomSheet;
import org.telegram.ui.Components.Premium.PremiumLockIconView;
import org.telegram.ui.Components.Reactions.CustomEmojiReactionsWindow;
@ -272,13 +273,12 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
});
recyclerListView.setLayoutManager(linearLayoutManager);
recyclerListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
recyclerListView.setAdapter(listAdapter = new RecyclerView.Adapter() {
recyclerListView.setAdapter(listAdapter = new AdapterWithDiffUtils() {
int rowCount;
int reactionsStartRow;
int reactionsEndRow;
int premiumUnlockButtonRow;
int customReactionsEmojiRow;
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return false;
}
@NonNull
@Override
@ -286,10 +286,10 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
View view;
switch (viewType) {
default:
case 0:
case VIEW_TYPE_REACTION:
view = new ReactionHolderView(context, true);
break;
case 1:
case VIEW_TYPE_PREMIUM_BUTTON:
premiumLockContainer = new FrameLayout(context);
premiumLockIconView = new PremiumLockIconView(context, PremiumLockIconView.TYPE_REACTIONS);
premiumLockIconView.setColor(ColorUtils.blendARGB(Theme.getColor(Theme.key_actionBarDefaultSubmenuItemIcon), Theme.getColor(Theme.key_dialogBackground), 0.7f));
@ -305,7 +305,7 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
});
view = premiumLockContainer;
break;
case 2:
case VIEW_TYPE_CUSTOM_EMOJI_BUTTON:
customReactionsContainer = new CustomReactionsContainer(context);
customEmojiReactionsIconView = new InternalImageView(context);
customEmojiReactionsIconView.setImageResource(R.drawable.msg_reactions_expand);
@ -328,45 +328,67 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder.getItemViewType() == 0) {
if (holder.getItemViewType() == VIEW_TYPE_REACTION) {
ReactionHolderView h = (ReactionHolderView) holder.itemView;
h.setScaleX(1);
h.setScaleY(1);
h.setReaction(visibleReactionsList.get(position), position);
h.setReaction(items.get(position).reaction, position);
}
}
@Override
public int getItemCount() {
return rowCount;
return items.size();
}
@Override
public int getItemViewType(int position) {
if (position >= 0 && position < visibleReactionsList.size()) {
return 0;
}
if (position == premiumUnlockButtonRow) {
return 1;
}
return 2;
return items.get(position).viewType;
}
ArrayList<InnerItem> items = new ArrayList<>();
ArrayList<InnerItem> oldItems = new ArrayList<>();
private static final int VIEW_TYPE_REACTION = 0;
private static final int VIEW_TYPE_PREMIUM_BUTTON = 1;
private static final int VIEW_TYPE_CUSTOM_EMOJI_BUTTON = 2;
@Override
public void notifyDataSetChanged() {
rowCount = 0;
premiumUnlockButtonRow = -1;
customReactionsEmojiRow = -1;
reactionsStartRow = rowCount;
rowCount += visibleReactionsList.size();
reactionsEndRow = rowCount;
oldItems.clear();
oldItems.addAll(items);
items.clear();
for (int i = 0; i < visibleReactionsList.size(); i++) {
items.add(new InnerItem(VIEW_TYPE_REACTION, visibleReactionsList.get(i)));
}
if (showUnlockPremiumButton()) {
premiumUnlockButtonRow = rowCount++;
items.add(new InnerItem(VIEW_TYPE_PREMIUM_BUTTON, null));
}
if (showCustomEmojiReaction()) {
customReactionsEmojiRow = rowCount++;
items.add(new InnerItem(VIEW_TYPE_CUSTOM_EMOJI_BUTTON, null));
}
super.notifyDataSetChanged();
setItems(oldItems, items);
}
class InnerItem extends AdapterWithDiffUtils.Item {
ReactionsLayoutInBubble.VisibleReaction reaction;
public InnerItem(int viewType, ReactionsLayoutInBubble.VisibleReaction reaction) {
super(viewType, false);
this.reaction = reaction;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InnerItem innerItem = (InnerItem) o;
if (viewType == innerItem.viewType && viewType == VIEW_TYPE_REACTION) {
return reaction != null && reaction.equals(innerItem.reaction);
}
return viewType == innerItem.viewType;
}
}
});
recyclerListView.addOnScrollListener(new LeftRightShadowsListener());
@ -439,7 +461,7 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
nextRecentReaction.getLayoutParams().height = size;
bgPaint.setColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground, resourcesProvider));
MediaDataController.getInstance(currentAccount).preloadReactions();
MediaDataController.getInstance(currentAccount).preloadDefaultReactions();
}
private void animatePullingBack() {
@ -462,21 +484,7 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
return;
}
reactionsWindow = new CustomEmojiReactionsWindow(fragment, allReactionsList, selectedReactions, this, resourcesProvider);
for (int i = 0; i < recyclerListView.getChildCount(); i++) {
View child = recyclerListView.getChildAt(i);
if (child instanceof ReactionHolderView) {
ReactionHolderView holderView = (ReactionHolderView) child;
if (holderView.loopImageView.getImageReceiver().getLottieAnimation() != null) {
holderView.loopImageView.getImageReceiver().moveLottieToFront();
}
if (holderView.loopImageView.animatedEmojiDrawable != null) {
reactionsWindow.getSelectAnimatedEmojiDialog().putAnimatedEmojiToCache(holderView.loopImageView.animatedEmojiDrawable);
}
}
}
if (nextRecentReaction != null && nextRecentReaction.getVisibility() == View.VISIBLE) {
nextRecentReaction.loopImageView.getImageReceiver().moveLottieToFront();
}
reactionsWindow.onDismissListener(() -> {
reactionsWindow = null;
});
@ -1225,33 +1233,27 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
addView(enterImageView, LayoutHelper.createFrame(34, 34, Gravity.CENTER));
addView(pressedBackupImageView, LayoutHelper.createFrame(34, 34, Gravity.CENTER));
addView(loopImageView, LayoutHelper.createFrame(34, 34, Gravity.CENTER));
enterImageView.setLayerNum(Integer.MAX_VALUE);
loopImageView.setLayerNum(Integer.MAX_VALUE);
pressedBackupImageView.setLayerNum(Integer.MAX_VALUE);
}
private void setReaction(ReactionsLayoutInBubble.VisibleReaction react, int position) {
if (currentReaction != null && currentReaction.equals(react)) {
updateImage(react);
return;
}
this.position = position;
resetAnimation();
currentReaction = react;
selected = selectedReactions.contains(react);
hasEnterAnimation = false;//currentReaction.emojicon != null && (!showCustomEmojiReaction() || allReactionsIsDefault);
hasEnterAnimation = currentReaction.emojicon != null && (!showCustomEmojiReaction() || allReactionsIsDefault);
if (currentReaction.emojicon != null) {
TLRPC.TL_availableReaction defaultReaction = MediaDataController.getInstance(currentAccount).getReactionsMap().get(currentReaction.emojicon);
if (defaultReaction != null) {
if (recyclerReaction) {
loopImageView.getImageReceiver().setUniqKeyPrefix("r");
}
SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(defaultReaction.activate_animation, Theme.key_windowBackgroundGray, 1.0f);
enterImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.appear_animation), ReactionsUtils.APPEAR_ANIMATION_FILTER, null, null, svgThumb, 0, "tgs", react, 0);
pressedBackupImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, null, null, svgThumb, 0, "tgs", react, 0);
loopImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, null, null, hasEnterAnimation ? null : svgThumb, 0, "tgs", currentReaction, 0);
loopImageView.setAnimatedEmojiDrawable(null);
updateImage(react);
pressedBackupImageView.setAnimatedEmojiDrawable(null);
if (enterImageView.getImageReceiver().getLottieAnimation() != null) {
enterImageView.getImageReceiver().getLottieAnimation().setCurrentFrame(0, false);
}
pressedBackupImageView.setAnimatedEmojiDrawable(null);
if (enterImageView.getImageReceiver().getLottieAnimation() != null) {
enterImageView.getImageReceiver().getLottieAnimation().setCurrentFrame(0, false);
}
} else {
pressedBackupImageView.getImageReceiver().clearImage();
@ -1259,8 +1261,6 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
pressedBackupImageView.setAnimatedEmojiDrawable(new AnimatedEmojiDrawable(AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW_LARGE, currentAccount, currentReaction.documentId));
loopImageView.setAnimatedEmojiDrawable(new AnimatedEmojiDrawable(AnimatedEmojiDrawable.CACHE_TYPE_ALERT_PREVIEW, currentAccount, currentReaction.documentId));
}
enterImageView.setLayerNum(Integer.MAX_VALUE);
loopImageView.setLayerNum(Integer.MAX_VALUE);
setFocusable(true);
shouldSwitchToLoopView = hasEnterAnimation && showCustomEmojiReaction();
if (!hasEnterAnimation) {
@ -1281,6 +1281,18 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
}
}
private void updateImage(ReactionsLayoutInBubble.VisibleReaction react) {
if (currentReaction.emojicon != null) {
TLRPC.TL_availableReaction defaultReaction = MediaDataController.getInstance(currentAccount).getReactionsMap().get(currentReaction.emojicon);
if (defaultReaction != null) {
SvgHelper.SvgDrawable svgThumb = DocumentObject.getSvgThumb(defaultReaction.activate_animation, Theme.key_windowBackgroundGray, 1.0f);
enterImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.appear_animation), ReactionsUtils.APPEAR_ANIMATION_FILTER, null, null, svgThumb, 0, "tgs", react, 0);
pressedBackupImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, null, null, svgThumb, 0, "tgs", react, 0);
loopImageView.getImageReceiver().setImage(ImageLocation.getForDocument(defaultReaction.select_animation), ReactionsUtils.SELECT_ANIMATION_FILTER, null, null, hasEnterAnimation ? null : svgThumb, 0, "tgs", currentReaction, 0);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
@ -1511,8 +1523,6 @@ public class ReactionsContainerLayout extends FrameLayout implements Notificatio
public void play(int delay) {
isEnter = true;
// cellFlickerDrawable.progress = 0;
// cellFlickerDrawable.repeatEnabled = false;
invalidate();
if (valueAnimator != null) {
valueAnimator.removeAllListeners();

View File

@ -68,6 +68,7 @@ import java.util.Objects;
import tw.nekomimi.nekogram.NekoConfig;
@SuppressWarnings("JavaReflectionMemberAccess")
public class RecyclerListView extends RecyclerView {
public final static int SECTIONS_TYPE_SIMPLE = 0,
SECTIONS_TYPE_STICKY_HEADERS = 1,
@ -183,6 +184,18 @@ public class RecyclerListView extends RecyclerView {
private boolean accessibilityEnabled = true;
private final static Method initializeScrollbars;
static {
Method notSoFinalInitializeScrollbars;
try {
notSoFinalInitializeScrollbars = android.view.View.class.getDeclaredMethod("initializeScrollbars", TypedArray.class);
} catch (Exception ignored) {
notSoFinalInitializeScrollbars = null;
}
initializeScrollbars = notSoFinalInitializeScrollbars;
}
private AccessibilityDelegate accessibilityDelegate = new AccessibilityDelegate() {
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
@ -1373,10 +1386,9 @@ public class RecyclerListView extends RecyclerView {
gotAttributes = true;
}
TypedArray a = context.getTheme().obtainStyledAttributes(attributes);
@SuppressLint("DiscouragedPrivateApi")
Method initializeScrollbars = android.view.View.class.getDeclaredMethod("initializeScrollbars", TypedArray.class);
initializeScrollbars.invoke(this, a);
a.recycle();
if (initializeScrollbars != null) {
initializeScrollbars.invoke(this, a);
}
} catch (Throwable e) {
FileLog.e(e);
}
@ -1905,6 +1917,10 @@ public class RecyclerListView extends RecyclerView {
int emptyViewAnimateToVisibility;
public void checkIfEmpty() {
checkIfEmpty(updateEmptyViewAnimated());
}
private void checkIfEmpty(boolean animated) {
if (isHidden) {
return;

View File

@ -434,7 +434,7 @@ public class SearchViewPager extends ViewPagerFixed implements FilteredSearchVie
return false;
}
for (MessageObject obj : selectedFiles.values()) {
if (obj.getDocument() != null && obj.getDocument().size >= 500 * 1024 * 1024) {
if (obj.getDocument() != null && obj.getDocument().size >= 150 * 1024 * 1024) {
return true;
}
}

View File

@ -16,7 +16,6 @@ import android.view.MotionEvent;
import android.view.View;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.ui.ActionBar.Theme;
public class SeekBar {
@ -153,6 +152,9 @@ public class SeekBar {
}
public void setSize(int w, int h) {
if (width == w && height == h) {
return;
}
width = w;
height = h;
setProgress(thumbProgress);

View File

@ -1723,7 +1723,7 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi
topicsGridView.setScaleY(0.75f + value * 0.25f);
topicsGridView.setAlpha(value);
RecyclerListView mainGridView = getMainGridView();
RecyclerListView mainGridView = gridView;
mainGridView.setPivotX(cell.getX() + cell.getWidth() / 2f);
mainGridView.setPivotY(cell.getY() + cell.getHeight() / 2f);
mainGridView.setScaleX(1f + value * 0.25f);
@ -1746,8 +1746,14 @@ public class ShareAlert extends BottomSheet implements NotificationCenter.Notifi
for (int i = 0; i < mainGridView.getChildCount(); i++) {
View v = mainGridView.getChildAt(i);
if (v instanceof ShareDialogCell) {
v.setTranslationX((v.getX() - cell.getX()) * 0.75f * moveValue);
v.setTranslationY((v.getY() - cell.getY()) * 0.75f * moveValue);
v.setTranslationX((v.getX() - cell.getX()) * 0.5f * moveValue);
v.setTranslationY((v.getY() - cell.getY()) * 0.5f * moveValue);
if (v != cell) {
v.setAlpha(1f - Math.min(value, 0.5f) / 0.5f);
} else {
v.setAlpha(1f - value);
}
}
}
for (int i = 0; i < topicsGridView.getChildCount(); i++) {

View File

@ -542,8 +542,8 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter
public SharedMediaPreloader(BaseFragment fragment) {
parentFragment = fragment;
if (fragment instanceof FragmentContextView.ChatActivityInterface) {
FragmentContextView.ChatActivityInterface chatActivity = (FragmentContextView.ChatActivityInterface) fragment;
if (fragment instanceof ChatActivityInterface) {
ChatActivityInterface chatActivity = (ChatActivityInterface) fragment;
dialogId = chatActivity.getDialogId();
mergeDialogId = chatActivity.getMergeDialogId();
topicId = chatActivity.getTopicId();
@ -847,12 +847,23 @@ public class SharedMediaLayout extends FrameLayout implements NotificationCenter
for (int i = 0 ; i < sharedMediaData.length; i++) {
allMessages.addAll(sharedMediaData[i].messages);
}
Utilities.globalQueue.postRunnable(new Runnable() {
@Override
public void run() {
FileLoader.getInstance(account).checkMediaExistance(allMessages);
}
});
String fileName = (String) args[0];
if (fileName != null) {
Utilities.globalQueue.postRunnable(new Runnable() {
@Override
public void run() {
for (int i = 0; i < allMessages.size(); i++) {
if (!fileName.equals(allMessages.get(i).getFileName())) {
allMessages.remove(i);
i--;
}
}
if (allMessages.size() > 0) {
FileLoader.getInstance(account).checkMediaExistance(allMessages);
}
}
});
}
}
}

View File

@ -32,7 +32,6 @@ import org.telegram.messenger.Emoji;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.SharedConfig;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.Theme;
@ -133,12 +132,6 @@ public class SuggestEmojiView extends FrameLayout implements NotificationCenter.
}
});
this.leftGradient = getResources().getDrawable(R.drawable.gradient_right).mutate();
this.leftGradient.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
this.rightGradient = getResources().getDrawable(R.drawable.gradient_left).mutate();
this.rightGradient.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
MediaDataController.getInstance(currentAccount).checkStickers(MediaDataController.TYPE_EMOJIPACKS);
}
@ -154,8 +147,8 @@ public class SuggestEmojiView extends FrameLayout implements NotificationCenter.
if (backgroundPaint != null) {
backgroundPaint.setColor(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider));
}
this.leftGradient.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
this.rightGradient.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
Theme.chat_gradientLeftDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
Theme.chat_gradientRightDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_stickersHintPanel, resourcesProvider), PorterDuff.Mode.MULTIPLY));
}
public void forceClose() {
@ -423,7 +416,6 @@ public class SuggestEmojiView extends FrameLayout implements NotificationCenter.
private AnimatedFloat showFloat2 = new AnimatedFloat(containerView, 150, 600, CubicBezierInterpolator.EASE_OUT_QUINT);
private OvershootInterpolator overshootInterpolator = new OvershootInterpolator(.4f);
private Drawable leftGradient, rightGradient;
private AnimatedFloat leftGradientAlpha = new AnimatedFloat(containerView, 300, CubicBezierInterpolator.EASE_OUT_QUINT);
private AnimatedFloat rightGradientAlpha = new AnimatedFloat(containerView, 300, CubicBezierInterpolator.EASE_OUT_QUINT);
@ -549,16 +541,16 @@ public class SuggestEmojiView extends FrameLayout implements NotificationCenter.
float leftAlpha = leftGradientAlpha.set(listView.canScrollHorizontally(-1) ? 1f : 0f);
if (leftAlpha > 0) {
leftGradient.setBounds((int) left, (int) top, (int) left + AndroidUtilities.dp(32), (int) bottom);
leftGradient.setAlpha((int) (255 * leftAlpha));
leftGradient.draw(canvas);
Theme.chat_gradientLeftDrawable.setBounds((int) left, (int) top, (int) left + AndroidUtilities.dp(32), (int) bottom);
Theme.chat_gradientLeftDrawable.setAlpha((int) (255 * leftAlpha));
Theme.chat_gradientLeftDrawable.draw(canvas);
}
float rightAlpha = rightGradientAlpha.set(listView.canScrollHorizontally(1) ? 1f : 0f);
if (rightAlpha > 0) {
rightGradient.setBounds((int) right - AndroidUtilities.dp(32), (int) top, (int) right, (int) bottom);
rightGradient.setAlpha((int) (255 * rightAlpha));
rightGradient.draw(canvas);
Theme.chat_gradientRightDrawable.setBounds((int) right - AndroidUtilities.dp(32), (int) top, (int) right, (int) bottom);
Theme.chat_gradientRightDrawable.setAlpha((int) (255 * rightAlpha));
Theme.chat_gradientRightDrawable.draw(canvas);
}
canvas.restore();

View File

@ -46,6 +46,8 @@ public class UnreadCounterTextView extends View {
int counterColor;
CharSequence lastText;
String textColorKey = Theme.key_chat_fieldOverlayText;
public UnreadCounterTextView(Context context) {
super(context);
textPaint.setTextSize(AndroidUtilities.dp(13));
@ -202,7 +204,7 @@ public class UnreadCounterTextView extends View {
@Override
protected void onDraw(Canvas canvas) {
Layout layout = textLayout;
int color = Theme.getColor(isEnabled() ? Theme.key_chat_fieldOverlayText : Theme.key_windowBackgroundWhiteGrayText, getResourceProvider());
int color = Theme.getColor(isEnabled() ? textColorKey : Theme.key_windowBackgroundWhiteGrayText, getResourceProvider());
if (textColor != color) {
layoutPaint.setColor(textColor = color);
}
@ -218,8 +220,8 @@ public class UnreadCounterTextView extends View {
if (getParent() != null) {
int contentWidth = getMeasuredWidth();
int x = (getMeasuredWidth() - contentWidth) / 2;
if (rippleColor != Theme.getColor(Theme.key_chat_fieldOverlayText, getResourceProvider()) || selectableBackground == null) {
selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(rippleColor = Theme.getColor(Theme.key_chat_fieldOverlayText, getResourceProvider()), 26));
if (rippleColor != Theme.getColor(textColorKey, getResourceProvider()) || selectableBackground == null) {
selectableBackground = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(60), 0, ColorUtils.setAlphaComponent(rippleColor = Theme.getColor(textColorKey, getResourceProvider()), 26));
selectableBackground.setCallback(this);
}
int start = (getLeft() + x) <= 0 ? x - AndroidUtilities.dp(20) : x;
@ -298,4 +300,9 @@ public class UnreadCounterTextView extends View {
}
}
}
public void setTextColorKey(String textColorKey) {
this.textColorKey = textColorKey;
invalidate();
}
}

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