use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class FileUploadOperation method startUploadRequest.
private void startUploadRequest() {
if (state != 1) {
return;
}
final TLObject finalRequest;
final int currentRequestPartNum;
final int currentRequestBytes;
final byte[] currentRequestIv;
try {
started = true;
if (stream == null) {
File cacheFile = new File(uploadingFilePath);
if (AndroidUtilities.isInternalUri(Uri.fromFile(cacheFile))) {
throw new Exception("trying to upload internal file");
}
stream = new RandomAccessFile(cacheFile, "r");
boolean isInternalFile = false;
try {
@SuppressLint("DiscouragedPrivateApi") Method getInt = FileDescriptor.class.getDeclaredMethod("getInt$");
int fdint = (Integer) getInt.invoke(stream.getFD());
if (AndroidUtilities.isInternalUri(fdint)) {
isInternalFile = true;
}
} catch (Throwable e) {
FileLog.e(e);
}
if (isInternalFile) {
throw new Exception("trying to upload internal file");
}
if (estimatedSize != 0) {
totalFileSize = estimatedSize;
} else {
totalFileSize = cacheFile.length();
}
if (!forceSmallFile && totalFileSize > 10 * 1024 * 1024) {
isBigFile = true;
}
uploadChunkSize = (int) Math.max(slowNetwork ? minUploadChunkSlowNetworkSize : minUploadChunkSize, (totalFileSize + 1024 * maxUploadParts - 1) / (1024 * maxUploadParts));
if (1024 % uploadChunkSize != 0) {
int chunkSize = 64;
while (uploadChunkSize > chunkSize) {
chunkSize *= 2;
}
uploadChunkSize = chunkSize;
}
maxRequestsCount = Math.max(1, (slowNetwork ? maxUploadingSlowNetworkKBytes : maxUploadingKBytes) / uploadChunkSize);
if (isEncrypted) {
freeRequestIvs = new ArrayList<>(maxRequestsCount);
for (int a = 0; a < maxRequestsCount; a++) {
freeRequestIvs.add(new byte[32]);
}
}
uploadChunkSize *= 1024;
calcTotalPartsCount();
readBuffer = new byte[uploadChunkSize];
fileKey = Utilities.MD5(uploadingFilePath + (isEncrypted ? "enc" : ""));
long fileSize = preferences.getLong(fileKey + "_size", 0);
uploadStartTime = (int) (System.currentTimeMillis() / 1000);
boolean rewrite = false;
if (!uploadFirstPartLater && !nextPartFirst && estimatedSize == 0 && fileSize == totalFileSize) {
currentFileId = preferences.getLong(fileKey + "_id", 0);
int date = preferences.getInt(fileKey + "_time", 0);
long uploadedSize = preferences.getLong(fileKey + "_uploaded", 0);
if (isEncrypted) {
String ivString = preferences.getString(fileKey + "_iv", null);
String keyString = preferences.getString(fileKey + "_key", null);
if (ivString != null && keyString != null) {
key = Utilities.hexToBytes(keyString);
iv = Utilities.hexToBytes(ivString);
if (key != null && iv != null && key.length == 32 && iv.length == 32) {
ivChange = new byte[32];
System.arraycopy(iv, 0, ivChange, 0, 32);
} else {
rewrite = true;
}
} else {
rewrite = true;
}
}
if (!rewrite && date != 0) {
if (isBigFile && date < uploadStartTime - 60 * 60 * 24) {
date = 0;
} else if (!isBigFile && date < uploadStartTime - 60 * 60 * 1.5f) {
date = 0;
}
if (date != 0) {
if (uploadedSize > 0) {
readBytesCount = uploadedSize;
currentPartNum = (int) (uploadedSize / uploadChunkSize);
if (!isBigFile) {
for (int b = 0; b < readBytesCount / uploadChunkSize; b++) {
int bytesRead = stream.read(readBuffer);
int toAdd = 0;
if (isEncrypted && bytesRead % 16 != 0) {
toAdd += 16 - bytesRead % 16;
}
NativeByteBuffer sendBuffer = new NativeByteBuffer(bytesRead + toAdd);
if (bytesRead != uploadChunkSize || totalPartsCount == currentPartNum + 1) {
isLastPart = true;
}
sendBuffer.writeBytes(readBuffer, 0, bytesRead);
if (isEncrypted) {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, bytesRead + toAdd);
}
sendBuffer.reuse();
}
} else {
stream.seek(uploadedSize);
if (isEncrypted) {
String ivcString = preferences.getString(fileKey + "_ivc", null);
if (ivcString != null) {
ivChange = Utilities.hexToBytes(ivcString);
if (ivChange == null || ivChange.length != 32) {
rewrite = true;
readBytesCount = 0;
currentPartNum = 0;
}
} else {
rewrite = true;
readBytesCount = 0;
currentPartNum = 0;
}
}
}
} else {
rewrite = true;
}
}
} else {
rewrite = true;
}
} else {
rewrite = true;
}
if (rewrite) {
if (isEncrypted) {
iv = new byte[32];
key = new byte[32];
ivChange = new byte[32];
Utilities.random.nextBytes(iv);
Utilities.random.nextBytes(key);
System.arraycopy(iv, 0, ivChange, 0, 32);
}
currentFileId = Utilities.random.nextLong();
if (!nextPartFirst && !uploadFirstPartLater && estimatedSize == 0) {
storeFileUploadInfo();
}
}
if (isEncrypted) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] arr = new byte[64];
System.arraycopy(key, 0, arr, 0, 32);
System.arraycopy(iv, 0, arr, 32, 32);
byte[] digest = md.digest(arr);
for (int a = 0; a < 4; a++) {
fingerprint |= ((digest[a] ^ digest[a + 4]) & 0xFF) << (a * 8);
}
} catch (Exception e) {
FileLog.e(e);
}
}
uploadedBytesCount = readBytesCount;
lastSavedPartNum = currentPartNum;
if (uploadFirstPartLater) {
if (isBigFile) {
stream.seek(uploadChunkSize);
readBytesCount = uploadChunkSize;
} else {
stream.seek(1024);
readBytesCount = 1024;
}
currentPartNum = 1;
}
}
if (estimatedSize != 0) {
if (readBytesCount + uploadChunkSize > availableSize) {
return;
}
}
if (nextPartFirst) {
stream.seek(0);
if (isBigFile) {
currentRequestBytes = stream.read(readBuffer);
} else {
currentRequestBytes = stream.read(readBuffer, 0, 1024);
}
currentPartNum = 0;
} else {
currentRequestBytes = stream.read(readBuffer);
}
if (currentRequestBytes == -1) {
return;
}
int toAdd = 0;
if (isEncrypted && currentRequestBytes % 16 != 0) {
toAdd += 16 - currentRequestBytes % 16;
}
NativeByteBuffer sendBuffer = new NativeByteBuffer(currentRequestBytes + toAdd);
if (nextPartFirst || currentRequestBytes != uploadChunkSize || estimatedSize == 0 && totalPartsCount == currentPartNum + 1) {
if (uploadFirstPartLater) {
nextPartFirst = true;
uploadFirstPartLater = false;
} else {
isLastPart = true;
}
}
sendBuffer.writeBytes(readBuffer, 0, currentRequestBytes);
if (isEncrypted) {
for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0);
}
Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, currentRequestBytes + toAdd);
currentRequestIv = freeRequestIvs.get(0);
System.arraycopy(ivChange, 0, currentRequestIv, 0, 32);
freeRequestIvs.remove(0);
} else {
currentRequestIv = null;
}
if (isBigFile) {
TLRPC.TL_upload_saveBigFilePart req = new TLRPC.TL_upload_saveBigFilePart();
req.file_part = currentRequestPartNum = currentPartNum;
req.file_id = currentFileId;
if (estimatedSize != 0) {
req.file_total_parts = -1;
} else {
req.file_total_parts = totalPartsCount;
}
req.bytes = sendBuffer;
finalRequest = req;
} else {
TLRPC.TL_upload_saveFilePart req = new TLRPC.TL_upload_saveFilePart();
req.file_part = currentRequestPartNum = currentPartNum;
req.file_id = currentFileId;
req.bytes = sendBuffer;
finalRequest = req;
}
if (isLastPart && nextPartFirst) {
nextPartFirst = false;
currentPartNum = totalPartsCount - 1;
stream.seek(totalFileSize);
}
readBytesCount += currentRequestBytes;
} catch (Exception e) {
FileLog.e(e);
state = 4;
delegate.didFailedUploadingFile(this);
cleanup();
return;
}
currentPartNum++;
currentUploadRequetsCount++;
final int requestNumFinal = requestNum++;
final long currentRequestBytesOffset = currentRequestPartNum + currentRequestBytes;
final int requestSize = finalRequest.getObjectSize() + 4;
final int currentOperationGuid = operationGuid;
int connectionType;
if (slowNetwork) {
connectionType = ConnectionsManager.ConnectionTypeUpload;
} else {
connectionType = ConnectionsManager.ConnectionTypeUpload | ((requestNumFinal % 4) << 16);
}
int requestToken = ConnectionsManager.getInstance(currentAccount).sendRequest(finalRequest, (response, error) -> {
if (currentOperationGuid != operationGuid) {
return;
}
int networkType = response != null ? response.networkType : ApplicationLoader.getCurrentNetworkType();
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementSentBytesCount(networkType, StatsController.TYPE_AUDIOS, requestSize);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementSentBytesCount(networkType, StatsController.TYPE_VIDEOS, requestSize);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementSentBytesCount(networkType, StatsController.TYPE_PHOTOS, requestSize);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementSentBytesCount(networkType, StatsController.TYPE_FILES, requestSize);
}
if (currentRequestIv != null) {
freeRequestIvs.add(currentRequestIv);
}
requestTokens.delete(requestNumFinal);
if (response instanceof TLRPC.TL_boolTrue) {
if (state != 1) {
return;
}
uploadedBytesCount += currentRequestBytes;
long size;
if (estimatedSize != 0) {
size = Math.max(availableSize, estimatedSize);
} else {
size = totalFileSize;
}
delegate.didChangedUploadProgress(FileUploadOperation.this, uploadedBytesCount, size);
currentUploadRequetsCount--;
if (isLastPart && currentUploadRequetsCount == 0 && state == 1) {
state = 3;
if (key == null) {
TLRPC.InputFile result;
if (isBigFile) {
result = new TLRPC.TL_inputFileBig();
} else {
result = new TLRPC.TL_inputFile();
result.md5_checksum = "";
}
result.parts = currentPartNum;
result.id = currentFileId;
result.name = uploadingFilePath.substring(uploadingFilePath.lastIndexOf("/") + 1);
delegate.didFinishUploadingFile(FileUploadOperation.this, result, null, null, null);
cleanup();
} else {
TLRPC.InputEncryptedFile result;
if (isBigFile) {
result = new TLRPC.TL_inputEncryptedFileBigUploaded();
} else {
result = new TLRPC.TL_inputEncryptedFileUploaded();
result.md5_checksum = "";
}
result.parts = currentPartNum;
result.id = currentFileId;
result.key_fingerprint = fingerprint;
delegate.didFinishUploadingFile(FileUploadOperation.this, null, result, key, iv);
cleanup();
}
if (currentType == ConnectionsManager.FileTypeAudio) {
StatsController.getInstance(currentAccount).incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_AUDIOS, 1);
} else if (currentType == ConnectionsManager.FileTypeVideo) {
StatsController.getInstance(currentAccount).incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_VIDEOS, 1);
} else if (currentType == ConnectionsManager.FileTypePhoto) {
StatsController.getInstance(currentAccount).incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_PHOTOS, 1);
} else if (currentType == ConnectionsManager.FileTypeFile) {
StatsController.getInstance(currentAccount).incrementSentItemsCount(ApplicationLoader.getCurrentNetworkType(), StatsController.TYPE_FILES, 1);
}
} else if (currentUploadRequetsCount < maxRequestsCount) {
if (estimatedSize == 0 && !uploadFirstPartLater && !nextPartFirst) {
if (saveInfoTimes >= 4) {
saveInfoTimes = 0;
}
if (currentRequestPartNum == lastSavedPartNum) {
lastSavedPartNum++;
long offsetToSave = currentRequestBytesOffset;
byte[] ivToSave = currentRequestIv;
UploadCachedResult result;
while ((result = cachedResults.get(lastSavedPartNum)) != null) {
offsetToSave = result.bytesOffset;
ivToSave = result.iv;
cachedResults.remove(lastSavedPartNum);
lastSavedPartNum++;
}
if (isBigFile && offsetToSave % (1024 * 1024) == 0 || !isBigFile && saveInfoTimes == 0) {
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(fileKey + "_uploaded", offsetToSave);
if (isEncrypted) {
editor.putString(fileKey + "_ivc", Utilities.bytesToHex(ivToSave));
}
editor.commit();
}
} else {
UploadCachedResult result = new UploadCachedResult();
result.bytesOffset = currentRequestBytesOffset;
if (currentRequestIv != null) {
result.iv = new byte[32];
System.arraycopy(currentRequestIv, 0, result.iv, 0, 32);
}
cachedResults.put(currentRequestPartNum, result);
}
saveInfoTimes++;
}
startUploadRequest();
}
} else {
state = 4;
delegate.didFailedUploadingFile(FileUploadOperation.this);
cleanup();
}
}, null, () -> Utilities.stageQueue.postRunnable(() -> {
if (currentUploadRequetsCount < maxRequestsCount) {
startUploadRequest();
}
}), forceSmallFile ? ConnectionsManager.RequestFlagCanCompress : 0, ConnectionsManager.DEFAULT_DATACENTER_ID, connectionType, true);
requestTokens.put(requestNumFinal, requestToken);
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class ChatUsersActivity method createView.
@Override
public View createView(Context context) {
searching = false;
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
if (type == TYPE_KICKED) {
actionBar.setTitle(LocaleController.getString("ChannelPermissions", R.string.ChannelPermissions));
} else if (type == TYPE_BANNED) {
actionBar.setTitle(LocaleController.getString("ChannelBlacklist", R.string.ChannelBlacklist));
} else if (type == TYPE_ADMIN) {
actionBar.setTitle(LocaleController.getString("ChannelAdministrators", R.string.ChannelAdministrators));
} else if (type == TYPE_USERS) {
if (selectType == SELECT_TYPE_MEMBERS) {
if (isChannel) {
actionBar.setTitle(LocaleController.getString("ChannelSubscribers", R.string.ChannelSubscribers));
} else {
actionBar.setTitle(LocaleController.getString("ChannelMembers", R.string.ChannelMembers));
}
} else {
if (selectType == SELECT_TYPE_ADMIN) {
actionBar.setTitle(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin));
} else if (selectType == SELECT_TYPE_BLOCK) {
actionBar.setTitle(LocaleController.getString("ChannelBlockUser", R.string.ChannelBlockUser));
} else if (selectType == SELECT_TYPE_EXCEPTION) {
actionBar.setTitle(LocaleController.getString("ChannelAddException", R.string.ChannelAddException));
}
}
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
if (checkDiscard()) {
finishFragment();
}
} else if (id == done_button) {
processDone();
}
}
});
if (selectType != SELECT_TYPE_MEMBERS || type == TYPE_USERS || type == TYPE_BANNED || type == TYPE_KICKED) {
searchListViewAdapter = new SearchAdapter(context);
ActionBarMenu menu = actionBar.createMenu();
searchItem = menu.addItem(search_button, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
@Override
public void onSearchExpand() {
searching = true;
if (doneItem != null) {
doneItem.setVisibility(View.GONE);
}
}
@Override
public void onSearchCollapse() {
searchListViewAdapter.searchUsers(null);
searching = false;
listView.setAnimateEmptyView(false, 0);
listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
listView.setFastScrollVisible(true);
listView.setVerticalScrollBarEnabled(false);
if (doneItem != null) {
doneItem.setVisibility(View.VISIBLE);
}
}
@Override
public void onTextChanged(EditText editText) {
if (searchListViewAdapter == null) {
return;
}
String text = editText.getText().toString();
int oldItemsCount = listView.getAdapter() == null ? 0 : listView.getAdapter().getItemCount();
searchListViewAdapter.searchUsers(text);
if (TextUtils.isEmpty(text) && listView != null && listView.getAdapter() != listViewAdapter) {
listView.setAnimateEmptyView(false, 0);
listView.setAdapter(listViewAdapter);
if (oldItemsCount == 0) {
showItemsAnimated(0);
}
}
progressBar.setVisibility(View.GONE);
flickerLoadingView.setVisibility(View.VISIBLE);
}
});
if (type == TYPE_KICKED) {
searchItem.setSearchFieldHint(LocaleController.getString("ChannelSearchException", R.string.ChannelSearchException));
} else {
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
}
if (!(ChatObject.isChannel(currentChat) || currentChat.creator)) {
searchItem.setVisibility(View.GONE);
}
if (type == TYPE_KICKED) {
doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56), LocaleController.getString("Done", R.string.Done));
}
}
fragmentView = new FrameLayout(context) {
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.drawColor(Theme.getColor(listView.getAdapter() == searchListViewAdapter ? Theme.key_windowBackgroundWhite : Theme.key_windowBackgroundGray));
super.dispatchDraw(canvas);
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
FrameLayout progressLayout = new FrameLayout(context);
flickerLoadingView = new FlickerLoadingView(context);
flickerLoadingView.setViewType(FlickerLoadingView.USERS_TYPE);
flickerLoadingView.showDate(false);
flickerLoadingView.setUseHeaderOffset(true);
progressLayout.addView(flickerLoadingView);
progressBar = new RadialProgressView(context);
progressLayout.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
flickerLoadingView.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
emptyView = new StickerEmptyView(context, progressLayout, StickerEmptyView.STICKER_TYPE_SEARCH);
emptyView.title.setText(LocaleController.getString("NoResult", R.string.NoResult));
emptyView.subtitle.setText(LocaleController.getString("SearchEmptyViewFilteredSubtitle2", R.string.SearchEmptyViewFilteredSubtitle2));
emptyView.setVisibility(View.GONE);
emptyView.setAnimateLayoutChange(true);
emptyView.showProgress(true, false);
frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
emptyView.addView(progressLayout, 0);
listView = new RecyclerListView(context) {
@Override
public void invalidate() {
super.invalidate();
if (fragmentView != null) {
fragmentView.invalidate();
}
}
};
listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (!firstLoaded && type == TYPE_BANNED && participants.size() == 0) {
return 0;
}
return super.scrollVerticallyBy(dy, recycler, state);
}
});
DefaultItemAnimator itemAnimator = new DefaultItemAnimator() {
@Override
protected long getAddAnimationDelay(long removeDuration, long moveDuration, long changeDuration) {
return 0;
}
@Override
protected long getMoveAnimationDelay() {
return 0;
}
@Override
public long getMoveDuration() {
return 220;
}
@Override
public long getRemoveDuration() {
return 220;
}
@Override
public long getAddDuration() {
return 220;
}
int animationIndex = -1;
@Override
protected void onAllAnimationsDone() {
super.onAllAnimationsDone();
getNotificationCenter().onAnimationFinish(animationIndex);
}
@Override
public void runPendingAnimations() {
boolean removalsPending = !mPendingRemovals.isEmpty();
boolean movesPending = !mPendingMoves.isEmpty();
boolean changesPending = !mPendingChanges.isEmpty();
boolean additionsPending = !mPendingAdditions.isEmpty();
if (removalsPending || movesPending || additionsPending || changesPending) {
animationIndex = getNotificationCenter().setAnimationInProgress(animationIndex, null);
}
super.runPendingAnimations();
}
};
listView.setItemAnimator(itemAnimator);
itemAnimator.setSupportsChangeAnimations(false);
listView.setAnimateEmptyView(true, 0);
listView.setAdapter(listViewAdapter = new ListAdapter(context));
listView.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
listView.setOnItemClickListener((view, position) -> {
boolean listAdapter = listView.getAdapter() == listViewAdapter;
if (listAdapter) {
if (position == addNewRow) {
if (type == TYPE_BANNED || type == TYPE_KICKED) {
Bundle bundle = new Bundle();
bundle.putLong("chat_id", chatId);
bundle.putInt("type", ChatUsersActivity.TYPE_USERS);
bundle.putInt("selectType", type == TYPE_BANNED ? ChatUsersActivity.SELECT_TYPE_BLOCK : ChatUsersActivity.SELECT_TYPE_EXCEPTION);
ChatUsersActivity fragment = new ChatUsersActivity(bundle);
fragment.setInfo(info);
fragment.setDelegate(new ChatUsersActivityDelegate() {
@Override
public void didAddParticipantToList(long uid, TLObject participant) {
if (participantsMap.get(uid) == null) {
DiffCallback diffCallback = saveState();
participants.add(participant);
participantsMap.put(uid, participant);
sortUsers(participants);
updateListAnimated(diffCallback);
}
}
@Override
public void didKickParticipant(long uid) {
if (participantsMap.get(uid) == null) {
DiffCallback diffCallback = saveState();
TLRPC.TL_channelParticipantBanned chatParticipant = new TLRPC.TL_channelParticipantBanned();
if (uid > 0) {
chatParticipant.peer = new TLRPC.TL_peerUser();
chatParticipant.peer.user_id = uid;
} else {
chatParticipant.peer = new TLRPC.TL_peerChannel();
chatParticipant.peer.channel_id = -uid;
}
chatParticipant.date = getConnectionsManager().getCurrentTime();
chatParticipant.kicked_by = getAccountInstance().getUserConfig().clientUserId;
info.kicked_count++;
participants.add(chatParticipant);
participantsMap.put(uid, chatParticipant);
sortUsers(participants);
updateListAnimated(diffCallback);
}
}
});
presentFragment(fragment);
} else if (type == TYPE_ADMIN) {
Bundle bundle = new Bundle();
bundle.putLong("chat_id", chatId);
bundle.putInt("type", ChatUsersActivity.TYPE_USERS);
bundle.putInt("selectType", ChatUsersActivity.SELECT_TYPE_ADMIN);
ChatUsersActivity fragment = new ChatUsersActivity(bundle);
fragment.setDelegate(new ChatUsersActivityDelegate() {
@Override
public void didAddParticipantToList(long uid, TLObject participant) {
if (participant != null && participantsMap.get(uid) == null) {
DiffCallback diffCallback = saveState();
participants.add(participant);
participantsMap.put(uid, participant);
sortAdmins(participants);
updateListAnimated(diffCallback);
}
}
@Override
public void didChangeOwner(TLRPC.User user) {
onOwnerChaged(user);
}
@Override
public void didSelectUser(long uid) {
final TLRPC.User user = getMessagesController().getUser(uid);
if (user != null) {
AndroidUtilities.runOnUIThread(() -> {
if (BulletinFactory.canShowBulletin(ChatUsersActivity.this)) {
BulletinFactory.createPromoteToAdminBulletin(ChatUsersActivity.this, user.first_name).show();
}
}, 200);
}
if (participantsMap.get(uid) == null) {
DiffCallback diffCallback = saveState();
TLRPC.TL_channelParticipantAdmin chatParticipant = new TLRPC.TL_channelParticipantAdmin();
chatParticipant.peer = new TLRPC.TL_peerUser();
chatParticipant.peer.user_id = user.id;
chatParticipant.date = getConnectionsManager().getCurrentTime();
chatParticipant.promoted_by = getAccountInstance().getUserConfig().clientUserId;
participants.add(chatParticipant);
participantsMap.put(user.id, chatParticipant);
sortAdmins(participants);
updateListAnimated(diffCallback);
}
}
});
fragment.setInfo(info);
presentFragment(fragment);
} else if (type == TYPE_USERS) {
Bundle args = new Bundle();
args.putBoolean("addToGroup", true);
args.putLong(isChannel ? "channelId" : "chatId", currentChat.id);
GroupCreateActivity fragment = new GroupCreateActivity(args);
fragment.setInfo(info);
fragment.setIgnoreUsers(contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap);
fragment.setDelegate(new GroupCreateActivity.ContactsAddActivityDelegate() {
@Override
public void didSelectUsers(ArrayList<TLRPC.User> users, int fwdCount) {
DiffCallback savedState = saveState();
ArrayList<TLObject> array = contactsMap != null && contactsMap.size() != 0 ? contacts : participants;
LongSparseArray<TLObject> map = contactsMap != null && contactsMap.size() != 0 ? contactsMap : participantsMap;
int k = 0;
for (int a = 0, N = users.size(); a < N; a++) {
TLRPC.User user = users.get(a);
getMessagesController().addUserToChat(chatId, user, fwdCount, null, ChatUsersActivity.this, null);
getMessagesController().putUser(user, false);
if (map.get(user.id) == null) {
if (ChatObject.isChannel(currentChat)) {
TLRPC.TL_channelParticipant channelParticipant1 = new TLRPC.TL_channelParticipant();
channelParticipant1.inviter_id = getUserConfig().getClientUserId();
channelParticipant1.peer = new TLRPC.TL_peerUser();
channelParticipant1.peer.user_id = user.id;
channelParticipant1.date = getConnectionsManager().getCurrentTime();
array.add(k, channelParticipant1);
k++;
map.put(user.id, channelParticipant1);
} else {
TLRPC.ChatParticipant participant = new TLRPC.TL_chatParticipant();
participant.user_id = user.id;
participant.inviter_id = getUserConfig().getClientUserId();
array.add(k, participant);
k++;
map.put(user.id, participant);
}
}
}
if (array == participants) {
sortAdmins(participants);
}
updateListAnimated(savedState);
}
@Override
public void needAddBot(TLRPC.User user) {
openRightsEdit(user.id, null, null, null, "", true, ChatRightsEditActivity.TYPE_ADMIN, false);
}
});
presentFragment(fragment);
}
return;
} else if (position == recentActionsRow) {
presentFragment(new ChannelAdminLogActivity(currentChat));
return;
} else if (position == removedUsersRow) {
Bundle args = new Bundle();
args.putLong("chat_id", chatId);
args.putInt("type", ChatUsersActivity.TYPE_BANNED);
ChatUsersActivity fragment = new ChatUsersActivity(args);
fragment.setInfo(info);
presentFragment(fragment);
return;
} else if (position == gigaConvertRow) {
showDialog(new GigagroupConvertAlert(getParentActivity(), ChatUsersActivity.this) {
@Override
protected void onCovert() {
getMessagesController().convertToGigaGroup(getParentActivity(), currentChat, ChatUsersActivity.this, (result) -> {
if (result && parentLayout != null) {
BaseFragment editActivity = parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 2);
if (editActivity instanceof ChatEditActivity) {
editActivity.removeSelfFromStack();
Bundle args = new Bundle();
args.putLong("chat_id", chatId);
ChatEditActivity fragment = new ChatEditActivity(args);
fragment.setInfo(info);
parentLayout.addFragmentToStack(fragment, parentLayout.fragmentsStack.size() - 1);
finishFragment();
fragment.showConvertTooltip();
} else {
finishFragment();
}
}
});
}
@Override
protected void onCancel() {
}
});
} else if (position == addNew2Row) {
ManageLinksActivity fragment = new ManageLinksActivity(chatId, 0, 0);
fragment.setInfo(info, info.exported_invite);
presentFragment(fragment);
return;
} else if (position > permissionsSectionRow && position <= changeInfoRow) {
TextCheckCell2 checkCell = (TextCheckCell2) view;
if (!checkCell.isEnabled()) {
return;
}
if (checkCell.hasIcon()) {
if (!TextUtils.isEmpty(currentChat.username) && (position == pinMessagesRow || position == changeInfoRow)) {
BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("EditCantEditPermissionsPublic", R.string.EditCantEditPermissionsPublic)).show();
} else {
BulletinFactory.of(this).createErrorBulletin(LocaleController.getString("EditCantEditPermissions", R.string.EditCantEditPermissions)).show();
}
return;
}
checkCell.setChecked(!checkCell.isChecked());
if (position == changeInfoRow) {
defaultBannedRights.change_info = !defaultBannedRights.change_info;
} else if (position == addUsersRow) {
defaultBannedRights.invite_users = !defaultBannedRights.invite_users;
} else if (position == pinMessagesRow) {
defaultBannedRights.pin_messages = !defaultBannedRights.pin_messages;
} else {
boolean disabled = !checkCell.isChecked();
if (position == sendMessagesRow) {
defaultBannedRights.send_messages = !defaultBannedRights.send_messages;
} else if (position == sendMediaRow) {
defaultBannedRights.send_media = !defaultBannedRights.send_media;
} else if (position == sendStickersRow) {
defaultBannedRights.send_stickers = defaultBannedRights.send_games = defaultBannedRights.send_gifs = defaultBannedRights.send_inline = !defaultBannedRights.send_stickers;
} else if (position == embedLinksRow) {
defaultBannedRights.embed_links = !defaultBannedRights.embed_links;
} else if (position == sendPollsRow) {
defaultBannedRights.send_polls = !defaultBannedRights.send_polls;
}
if (disabled) {
if (defaultBannedRights.view_messages && !defaultBannedRights.send_messages) {
defaultBannedRights.send_messages = true;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMessagesRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(false);
}
}
if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_media) {
defaultBannedRights.send_media = true;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMediaRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(false);
}
}
if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_polls) {
defaultBannedRights.send_polls = true;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendPollsRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(false);
}
}
if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.send_stickers) {
defaultBannedRights.send_stickers = defaultBannedRights.send_games = defaultBannedRights.send_gifs = defaultBannedRights.send_inline = true;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendStickersRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(false);
}
}
if ((defaultBannedRights.view_messages || defaultBannedRights.send_messages) && !defaultBannedRights.embed_links) {
defaultBannedRights.embed_links = true;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(embedLinksRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(false);
}
}
} else {
if ((!defaultBannedRights.embed_links || !defaultBannedRights.send_inline || !defaultBannedRights.send_media || !defaultBannedRights.send_polls) && defaultBannedRights.send_messages) {
defaultBannedRights.send_messages = false;
RecyclerListView.ViewHolder holder = listView.findViewHolderForAdapterPosition(sendMessagesRow);
if (holder != null) {
((TextCheckCell2) holder.itemView).setChecked(true);
}
}
}
}
return;
}
}
TLRPC.TL_chatBannedRights bannedRights = null;
TLRPC.TL_chatAdminRights adminRights = null;
String rank = "";
final TLObject participant;
long peerId = 0;
long promoted_by = 0;
boolean canEditAdmin = false;
if (listAdapter) {
participant = listViewAdapter.getItem(position);
if (participant instanceof TLRPC.ChannelParticipant) {
TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
peerId = MessageObject.getPeerId(channelParticipant.peer);
bannedRights = channelParticipant.banned_rights;
adminRights = channelParticipant.admin_rights;
rank = channelParticipant.rank;
canEditAdmin = !(channelParticipant instanceof TLRPC.TL_channelParticipantAdmin || channelParticipant instanceof TLRPC.TL_channelParticipantCreator) || channelParticipant.can_edit;
if (participant instanceof TLRPC.TL_channelParticipantCreator) {
adminRights = ((TLRPC.TL_channelParticipantCreator) participant).admin_rights;
if (adminRights == null) {
adminRights = new TLRPC.TL_chatAdminRights();
adminRights.change_info = adminRights.post_messages = adminRights.edit_messages = adminRights.delete_messages = adminRights.ban_users = adminRights.invite_users = adminRights.pin_messages = adminRights.add_admins = true;
if (!isChannel) {
adminRights.manage_call = true;
}
}
}
} else if (participant instanceof TLRPC.ChatParticipant) {
TLRPC.ChatParticipant chatParticipant = (TLRPC.ChatParticipant) participant;
peerId = chatParticipant.user_id;
canEditAdmin = currentChat.creator;
if (participant instanceof TLRPC.TL_chatParticipantCreator) {
adminRights = new TLRPC.TL_chatAdminRights();
adminRights.change_info = adminRights.post_messages = adminRights.edit_messages = adminRights.delete_messages = adminRights.ban_users = adminRights.invite_users = adminRights.pin_messages = adminRights.add_admins = true;
if (!isChannel) {
adminRights.manage_call = true;
}
}
}
} else {
TLObject object = searchListViewAdapter.getItem(position);
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
getMessagesController().putUser(user, false);
participant = getAnyParticipant(peerId = user.id);
} else if (object instanceof TLRPC.ChannelParticipant || object instanceof TLRPC.ChatParticipant) {
participant = object;
} else {
participant = null;
}
if (participant instanceof TLRPC.ChannelParticipant) {
TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
peerId = MessageObject.getPeerId(channelParticipant.peer);
canEditAdmin = !(channelParticipant instanceof TLRPC.TL_channelParticipantAdmin || channelParticipant instanceof TLRPC.TL_channelParticipantCreator) || channelParticipant.can_edit;
bannedRights = channelParticipant.banned_rights;
adminRights = channelParticipant.admin_rights;
rank = channelParticipant.rank;
} else if (participant instanceof TLRPC.ChatParticipant) {
TLRPC.ChatParticipant chatParticipant = (TLRPC.ChatParticipant) participant;
peerId = chatParticipant.user_id;
canEditAdmin = currentChat.creator;
bannedRights = null;
adminRights = null;
} else if (participant == null) {
canEditAdmin = true;
}
}
if (peerId != 0) {
if (selectType != SELECT_TYPE_MEMBERS) {
if (selectType == SELECT_TYPE_EXCEPTION || selectType == SELECT_TYPE_ADMIN) {
if (selectType != SELECT_TYPE_ADMIN && canEditAdmin && (participant instanceof TLRPC.TL_channelParticipantAdmin || participant instanceof TLRPC.TL_chatParticipantAdmin)) {
final TLRPC.User user = getMessagesController().getUser(peerId);
final TLRPC.TL_chatBannedRights br = bannedRights;
final TLRPC.TL_chatAdminRights ar = adminRights;
final boolean canEdit = canEditAdmin;
final String rankFinal = rank;
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.formatString("AdminWillBeRemoved", R.string.AdminWillBeRemoved, UserObject.getUserName(user)));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> openRightsEdit(user.id, participant, ar, br, rankFinal, canEdit, selectType == SELECT_TYPE_ADMIN ? 0 : 1, false));
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else {
openRightsEdit(peerId, participant, adminRights, bannedRights, rank, canEditAdmin, selectType == SELECT_TYPE_ADMIN ? 0 : 1, selectType == SELECT_TYPE_ADMIN || selectType == SELECT_TYPE_EXCEPTION);
}
} else {
removeParticipant(peerId);
}
} else {
boolean canEdit = false;
if (type == TYPE_ADMIN) {
canEdit = peerId != getUserConfig().getClientUserId() && (currentChat.creator || canEditAdmin);
} else if (type == TYPE_BANNED || type == TYPE_KICKED) {
canEdit = ChatObject.canBlockUsers(currentChat);
}
if (type == TYPE_BANNED || type != TYPE_ADMIN && isChannel || type == TYPE_USERS && selectType == SELECT_TYPE_MEMBERS) {
if (peerId == getUserConfig().getClientUserId()) {
return;
}
Bundle args = new Bundle();
if (peerId > 0) {
args.putLong("user_id", peerId);
} else {
args.putLong("chat_id", -peerId);
}
presentFragment(new ProfileActivity(args));
} else {
if (bannedRights == null) {
bannedRights = new TLRPC.TL_chatBannedRights();
bannedRights.view_messages = true;
bannedRights.send_stickers = true;
bannedRights.send_media = true;
bannedRights.embed_links = true;
bannedRights.send_messages = true;
bannedRights.send_games = true;
bannedRights.send_inline = true;
bannedRights.send_gifs = true;
bannedRights.pin_messages = true;
bannedRights.send_polls = true;
bannedRights.invite_users = true;
bannedRights.change_info = true;
}
ChatRightsEditActivity fragment = new ChatRightsEditActivity(peerId, chatId, adminRights, defaultBannedRights, bannedRights, rank, type == TYPE_ADMIN ? ChatRightsEditActivity.TYPE_ADMIN : ChatRightsEditActivity.TYPE_BANNED, canEdit, participant == null);
fragment.setDelegate(new ChatRightsEditActivity.ChatRightsEditActivityDelegate() {
@Override
public void didSetRights(int rights, TLRPC.TL_chatAdminRights rightsAdmin, TLRPC.TL_chatBannedRights rightsBanned, String rank) {
if (participant instanceof TLRPC.ChannelParticipant) {
TLRPC.ChannelParticipant channelParticipant = (TLRPC.ChannelParticipant) participant;
channelParticipant.admin_rights = rightsAdmin;
channelParticipant.banned_rights = rightsBanned;
channelParticipant.rank = rank;
updateParticipantWithRights(channelParticipant, rightsAdmin, rightsBanned, 0, false);
}
}
@Override
public void didChangeOwner(TLRPC.User user) {
onOwnerChaged(user);
}
});
presentFragment(fragment);
}
}
}
});
listView.setOnItemLongClickListener((view, position) -> !(getParentActivity() == null || listView.getAdapter() != listViewAdapter) && createMenuForParticipant(listViewAdapter.getItem(position), false));
if (searchItem != null) {
listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
});
}
undoView = new UndoView(context);
frameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
updateRows();
listView.setEmptyView(emptyView);
listView.setAnimateEmptyView(false, 0);
if (needOpenSearch) {
searchItem.openSearch(false);
}
return fragmentView;
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class ChatActivity method createView.
@Override
public View createView(Context context) {
textSelectionHelper = new TextSelectionHelper.ChatListTextSelectionHelper() {
@Override
public int getParentTopPadding() {
return (int) chatListViewPaddingTop;
}
@Override
protected int getThemedColor(String key) {
Integer color = themeDelegate.getColor(key);
return color != null ? color : super.getThemedColor(key);
}
@Override
protected Theme.ResourcesProvider getResourcesProvider() {
return themeDelegate;
}
};
if (reportType >= 0) {
actionBar.setBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefault));
actionBar.setItemsColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), false);
actionBar.setItemsBackgroundColor(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false);
actionBar.setTitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
actionBar.setSubtitleColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
}
actionBarBackgroundPaint.setColor(getThemedColor(Theme.key_actionBarDefault));
if (chatMessageCellsCache.isEmpty()) {
for (int a = 0; a < 15; a++) {
chatMessageCellsCache.add(new ChatMessageCell(context, true, themeDelegate));
}
}
for (int a = 1; a >= 0; a--) {
selectedMessagesIds[a].clear();
selectedMessagesCanCopyIds[a].clear();
selectedMessagesCanStarIds[a].clear();
}
scheduledOrNoSoundHint = null;
infoTopView = null;
aspectRatioFrameLayout = null;
videoTextureView = null;
searchAsListHint = null;
mediaBanTooltip = null;
noSoundHintView = null;
forwardHintView = null;
checksHintView = null;
textSelectionHint = null;
emojiButtonRed = null;
gifHintTextView = null;
pollHintView = null;
timerHintView = null;
videoPlayerContainer = null;
voiceHintTextView = null;
blurredView = null;
dummyMessageCell = null;
cantDeleteMessagesCount = 0;
canEditMessagesCount = 0;
cantForwardMessagesCount = 0;
canForwardMessagesCount = 0;
cantSaveMessagesCount = 0;
canSaveMusicCount = 0;
canSaveDocumentsCount = 0;
hasOwnBackground = true;
if (chatAttachAlert != null) {
try {
if (chatAttachAlert.isShowing()) {
chatAttachAlert.dismiss();
}
} catch (Exception ignore) {
}
chatAttachAlert.onDestroy();
chatAttachAlert = null;
}
if (stickersAdapter != null) {
stickersAdapter.onDestroy();
stickersAdapter = null;
}
Theme.createChatResources(context, false);
actionBar.setAddToContainer(false);
if (inPreviewMode) {
actionBar.setBackButtonDrawable(null);
} else {
actionBar.setBackButtonDrawable(new BackDrawable(reportType >= 0));
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(final int id) {
if (id == -1) {
if (actionBar.isActionModeShowed()) {
clearSelectionMode();
} else {
if (!checkRecordLocked(true)) {
finishFragment();
}
}
} else if (id == copy) {
String str = "";
long previousUid = 0;
for (int a = 1; a >= 0; a--) {
ArrayList<Integer> ids = new ArrayList<>();
for (int b = 0; b < selectedMessagesCanCopyIds[a].size(); b++) {
ids.add(selectedMessagesCanCopyIds[a].keyAt(b));
}
if (currentEncryptedChat == null) {
Collections.sort(ids);
} else {
Collections.sort(ids, Collections.reverseOrder());
}
for (int b = 0; b < ids.size(); b++) {
Integer messageId = ids.get(b);
MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
if (str.length() != 0) {
str += "\n\n";
}
str += getMessageContent(messageObject, previousUid, ids.size() != 1 && (currentUser == null || !currentUser.self));
previousUid = messageObject.getFromChatId();
}
}
if (str.length() != 0) {
AndroidUtilities.addToClipboard(str);
undoView.showWithAction(0, UndoView.ACTION_TEXT_COPIED, null);
}
clearSelectionMode();
} else if (id == delete) {
if (getParentActivity() == null) {
return;
}
createDeleteMessagesAlert(null, null);
} else if (id == forward) {
openForward(true);
} else if (id == save_to) {
ArrayList<MessageObject> messageObjects = new ArrayList<>();
for (int a = 1; a >= 0; a--) {
for (int b = 0; b < selectedMessagesIds[a].size(); b++) {
messageObjects.add(selectedMessagesIds[a].valueAt(b));
}
selectedMessagesIds[a].clear();
selectedMessagesCanCopyIds[a].clear();
selectedMessagesCanStarIds[a].clear();
}
boolean isMusic = canSaveMusicCount > 0;
hideActionMode();
updatePinnedMessageView(true);
updateVisibleRows();
MediaController.saveFilesFromMessages(getParentActivity(), getAccountInstance(), messageObjects, (count) -> {
if (count > 0) {
if (getParentActivity() == null) {
return;
}
BulletinFactory.of(ChatActivity.this).createDownloadBulletin(isMusic ? BulletinFactory.FileType.AUDIOS : BulletinFactory.FileType.UNKNOWNS, count, themeDelegate).show();
}
});
} else if (id == chat_enc_timer) {
if (getParentActivity() == null) {
return;
}
showDialog(AlertsCreator.createTTLAlert(getParentActivity(), currentEncryptedChat, themeDelegate).create());
} else if (id == clear_history || id == delete_chat || id == auto_delete_timer) {
if (getParentActivity() == null) {
return;
}
if (id == auto_delete_timer || id == clear_history && currentEncryptedChat == null && (currentUser != null && !UserObject.isUserSelf(currentUser) && !UserObject.isDeleted(currentUser) || ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES) && (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)))) {
ClearHistoryAlert alert = new ClearHistoryAlert(getParentActivity(), currentUser, currentChat, id != auto_delete_timer, themeDelegate);
alert.setDelegate(new ClearHistoryAlert.ClearHistoryAlertDelegate() {
@Override
public void onClearHistory(boolean revoke) {
if (revoke && currentUser != null) {
getMessagesStorage().getMessagesCount(currentUser.id, (count) -> {
if (count >= 50) {
AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, true, false, true, null, currentUser, false, false, (param) -> performHistoryClear(true), themeDelegate);
} else {
performHistoryClear(true);
}
});
} else {
performHistoryClear(revoke);
}
}
@Override
public void onAutoDeleteHistory(int ttl, int action) {
getMessagesController().setDialogHistoryTTL(dialog_id, ttl);
if (userInfo != null || chatInfo != null) {
undoView.showWithAction(dialog_id, action, currentUser, userInfo != null ? userInfo.ttl_period : chatInfo.ttl_period, null, null);
}
}
});
showDialog(alert);
return;
}
AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, id == clear_history, currentChat, currentUser, currentEncryptedChat != null, true, (param) -> {
if (id == clear_history && ChatObject.isChannel(currentChat) && (!currentChat.megagroup || !TextUtils.isEmpty(currentChat.username))) {
getMessagesController().deleteDialog(dialog_id, 2, param);
} else {
if (id != clear_history) {
getNotificationCenter().removeObserver(ChatActivity.this, NotificationCenter.closeChats);
getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
finishFragment();
getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, dialog_id, currentUser, currentChat, param);
} else {
performHistoryClear(param);
}
}
}, themeDelegate);
} else if (id == share_contact) {
if (currentUser == null || getParentActivity() == null) {
return;
}
if (addToContactsButton.getTag() != null) {
shareMyContact((Integer) addToContactsButton.getTag(), null);
} else {
Bundle args = new Bundle();
args.putLong("user_id", currentUser.id);
args.putBoolean("addContact", true);
presentFragment(new ContactAddActivity(args));
}
} else if (id == mute) {
toggleMute(false);
} else if (id == add_shortcut) {
try {
getMediaDataController().installShortcut(currentUser.id);
} catch (Exception e) {
FileLog.e(e);
}
} else if (id == report) {
AlertsCreator.createReportAlert(getParentActivity(), dialog_id, 0, ChatActivity.this, themeDelegate, null);
} else if (id == star) {
for (int a = 0; a < 2; a++) {
for (int b = 0; b < selectedMessagesCanStarIds[a].size(); b++) {
MessageObject msg = selectedMessagesCanStarIds[a].valueAt(b);
getMediaDataController().addRecentSticker(MediaDataController.TYPE_FAVE, msg, msg.getDocument(), (int) (System.currentTimeMillis() / 1000), !hasUnfavedSelected);
}
}
clearSelectionMode();
} else if (id == edit) {
MessageObject messageObject = null;
for (int a = 1; a >= 0; a--) {
if (messageObject == null && selectedMessagesIds[a].size() == 1) {
ArrayList<Integer> ids = new ArrayList<>();
for (int b = 0; b < selectedMessagesIds[a].size(); b++) {
ids.add(selectedMessagesIds[a].keyAt(b));
}
messageObject = messagesDict[a].get(ids.get(0));
}
selectedMessagesIds[a].clear();
selectedMessagesCanCopyIds[a].clear();
selectedMessagesCanStarIds[a].clear();
}
startEditingMessageObject(messageObject);
hideActionMode();
updatePinnedMessageView(true);
updateVisibleRows();
} else if (id == chat_menu_attach) {
ActionBarMenuSubItem attach = new ActionBarMenuSubItem(context, false, true, true, getResourceProvider());
attach.setTextAndIcon(LocaleController.getString("AttachMenu", R.string.AttachMenu), R.drawable.input_attach);
attach.setOnClickListener(view -> {
headerItem.closeSubMenu();
if (chatAttachAlert != null) {
chatAttachAlert.setEditingMessageObject(null);
}
openAttachMenu();
});
headerItem.toggleSubMenu(attach, attachItem);
} else if (id == bot_help) {
getSendMessagesHelper().sendMessage("/help", dialog_id, null, null, null, false, null, null, null, true, 0, null);
} else if (id == bot_settings) {
getSendMessagesHelper().sendMessage("/settings", dialog_id, null, null, null, false, null, null, null, true, 0, null);
} else if (id == search) {
openSearchWithText(null);
} else if (id == call || id == video_call) {
if (currentUser != null && getParentActivity() != null) {
VoIPHelper.startCall(currentUser, id == video_call, userInfo != null && userInfo.video_calls_available, getParentActivity(), getMessagesController().getUserFull(currentUser.id), getAccountInstance());
}
} else if (id == text_bold) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedBold();
}
} else if (id == text_italic) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedItalic();
}
} else if (id == text_spoiler) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedSpoiler();
}
} else if (id == text_mono) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedMono();
}
} else if (id == text_strike) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedStrike();
}
} else if (id == text_underline) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedUnderline();
}
} else if (id == text_link) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedUrl();
}
} else if (id == text_regular) {
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setSelectionOverride(editTextStart, editTextEnd);
chatActivityEnterView.getEditField().makeSelectedRegular();
}
} else if (id == change_colors) {
showChatThemeBottomSheet();
}
}
});
View backButton = actionBar.getBackButton();
backButton.setOnLongClickListener(e -> {
scrimPopupWindow = BackButtonMenu.show(this, backButton, dialog_id);
if (scrimPopupWindow != null) {
scrimPopupWindow.setOnDismissListener(() -> {
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(false);
}
return true;
} else {
return false;
}
});
actionBar.setInterceptTouchEventListener((view, motionEvent) -> {
if (chatThemeBottomSheet != null) {
chatThemeBottomSheet.close();
return true;
}
return false;
});
if (avatarContainer != null) {
avatarContainer.onDestroy();
}
avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null, themeDelegate);
AndroidUtilities.updateViewVisibilityAnimated(avatarContainer, true, 1f, false);
if (inPreviewMode || inBubbleMode) {
avatarContainer.setOccupyStatusBar(false);
}
if (reportType >= 0) {
if (reportType == 0) {
actionBar.setTitle(LocaleController.getString("ReportChatSpam", R.string.ReportChatSpam));
} else if (reportType == 2) {
actionBar.setTitle(LocaleController.getString("ReportChatViolence", R.string.ReportChatViolence));
} else if (reportType == 3) {
actionBar.setTitle(LocaleController.getString("ReportChatChild", R.string.ReportChatChild));
} else if (reportType == 4) {
actionBar.setTitle(LocaleController.getString("ReportChatPornography", R.string.ReportChatPornography));
}
actionBar.setSubtitle(LocaleController.getString("ReportSelectMessages", R.string.ReportSelectMessages));
} else if (startLoadFromDate != 0) {
final int date = startLoadFromDate;
actionBar.setOnClickListener((v) -> {
jumpToDate(date);
});
actionBar.setTitle(LocaleController.formatDateChat(startLoadFromDate, false));
actionBar.setSubtitle(LocaleController.getString("Loading", R.string.Loading));
TLRPC.TL_messages_getHistory gh1 = new TLRPC.TL_messages_getHistory();
gh1.peer = getMessagesController().getInputPeer(dialog_id);
gh1.offset_date = startLoadFromDate;
gh1.limit = 1;
gh1.add_offset = -1;
int req = getConnectionsManager().sendRequest(gh1, (response, error) -> {
if (response instanceof TLRPC.messages_Messages) {
List<TLRPC.Message> l = ((TLRPC.messages_Messages) response).messages;
if (!l.isEmpty()) {
TLRPC.TL_messages_getHistory gh2 = new TLRPC.TL_messages_getHistory();
gh2.peer = getMessagesController().getInputPeer(dialog_id);
gh2.offset_date = startLoadFromDate + 60 * 60 * 24;
gh2.limit = 1;
getConnectionsManager().sendRequest(gh2, (response1, error1) -> {
if (response1 instanceof TLRPC.messages_Messages) {
List<TLRPC.Message> l2 = ((TLRPC.messages_Messages) response1).messages;
int count = 0;
if (!l2.isEmpty()) {
count = ((TLRPC.messages_Messages) response).offset_id_offset - ((TLRPC.messages_Messages) response1).offset_id_offset;
} else {
count = ((TLRPC.messages_Messages) response).offset_id_offset;
}
int finalCount = count;
AndroidUtilities.runOnUIThread(() -> {
if (finalCount != 0) {
AndroidUtilities.runOnUIThread(() -> actionBar.setSubtitle(LocaleController.formatPluralString("messages", finalCount)));
} else {
actionBar.setSubtitle(LocaleController.getString("NoMessagesForThisDay", R.string.NoMessagesForThisDay));
}
});
}
});
} else {
actionBar.setSubtitle(LocaleController.getString("NoMessagesForThisDay", R.string.NoMessagesForThisDay));
}
}
});
getConnectionsManager().bindRequestToGuid(req, classGuid);
} else {
actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, !inPreviewMode ? 56 : (chatMode == MODE_PINNED ? 10 : 0), 0, 40, 0));
}
ActionBarMenu menu = actionBar.createMenu();
if (currentEncryptedChat == null && chatMode == 0 && reportType < 0) {
searchIconItem = menu.addItem(search, R.drawable.ic_ab_search);
searchItem = menu.addItem(0, R.drawable.ic_ab_search, themeDelegate).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
boolean searchWas;
@Override
public boolean canCollapseSearch() {
if (messagesSearchListView.getTag() != null) {
showMessagesSearchListView(false);
return false;
}
return true;
}
@Override
public void onSearchCollapse() {
searchCalendarButton.setVisibility(View.VISIBLE);
if (searchUserButton != null) {
searchUserButton.setVisibility(View.VISIBLE);
}
if (searchingForUser) {
mentionsAdapter.searchUsernameOrHashtag(null, 0, null, false, true);
searchingForUser = false;
}
mentionLayoutManager.setReverseLayout(false);
mentionsAdapter.setSearchingMentions(false);
searchingUserMessages = null;
searchingChatMessages = null;
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
searchItem.setSearchFieldCaption(null);
AndroidUtilities.updateViewVisibilityAnimated(avatarContainer, true, 0.95f, true);
if (editTextItem != null && editTextItem.getTag() != null) {
if (headerItem != null) {
headerItem.setVisibility(View.GONE);
}
if (editTextItem != null) {
editTextItem.setVisibility(View.VISIBLE);
}
if (attachItem != null) {
attachItem.setVisibility(View.GONE);
}
if (searchIconItem != null && showSearchAsIcon) {
searchIconItem.setVisibility(View.GONE);
}
if (audioCallIconItem != null && showAudioCallAsIcon) {
audioCallIconItem.setVisibility(View.GONE);
}
} else if (chatActivityEnterView.hasText() && TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer()) && (currentChat == null || ChatObject.canSendMessages(currentChat))) {
if (headerItem != null) {
headerItem.setVisibility(View.GONE);
}
if (editTextItem != null) {
editTextItem.setVisibility(View.GONE);
}
if (attachItem != null) {
attachItem.setVisibility(View.VISIBLE);
}
if (searchIconItem != null && showSearchAsIcon) {
searchIconItem.setVisibility(View.GONE);
}
if (audioCallIconItem != null && showAudioCallAsIcon) {
audioCallIconItem.setVisibility(View.GONE);
}
} else {
if (headerItem != null) {
headerItem.setVisibility(View.VISIBLE);
}
if (audioCallIconItem != null && showAudioCallAsIcon) {
audioCallIconItem.setVisibility(View.VISIBLE);
}
if (searchIconItem != null && showSearchAsIcon) {
searchIconItem.setVisibility(View.VISIBLE);
}
if (editTextItem != null) {
editTextItem.setVisibility(View.GONE);
}
if (attachItem != null) {
attachItem.setVisibility(View.GONE);
}
}
if (threadMessageId == 0 && !UserObject.isReplyUser(currentUser) || threadMessageObject != null && threadMessageObject.getRepliesCount() == 0) {
searchItem.setVisibility(View.GONE);
}
searchItemVisible = false;
getMediaDataController().clearFoundMessageObjects();
if (messagesSearchAdapter != null) {
messagesSearchAdapter.notifyDataSetChanged();
}
removeSelectedMessageHighlight();
updateBottomOverlay();
updatePinnedMessageView(true);
updateVisibleRows();
}
@Override
public void onSearchExpand() {
if (threadMessageId != 0 || UserObject.isReplyUser(currentUser)) {
openSearchWithText(null);
}
if (!openSearchKeyboard) {
return;
}
saveKeyboardPositionBeforeTransition();
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
AndroidUtilities.runOnUIThread(() -> {
searchWas = false;
searchItem.getSearchField().requestFocus();
AndroidUtilities.showKeyboard(searchItem.getSearchField());
removeKeyboardPositionBeforeTransition();
}, 500);
}
@Override
public void onSearchPressed(EditText editText) {
searchWas = true;
updateSearchButtons(0, 0, -1);
getMediaDataController().searchMessagesInChat(editText.getText().toString(), dialog_id, mergeDialogId, classGuid, 0, threadMessageId, searchingUserMessages, searchingChatMessages);
}
@Override
public void onTextChanged(EditText editText) {
showMessagesSearchListView(false);
if (searchingForUser) {
mentionsAdapter.searchUsernameOrHashtag("@" + editText.getText().toString(), 0, messages, true, true);
} else if (searchingUserMessages == null && searchingChatMessages == null && searchUserButton != null && TextUtils.equals(editText.getText(), LocaleController.getString("SearchFrom", R.string.SearchFrom))) {
searchUserButton.callOnClick();
}
}
@Override
public void onCaptionCleared() {
if (searchingUserMessages != null || searchingChatMessages != null) {
searchUserButton.callOnClick();
} else {
if (searchingForUser) {
mentionsAdapter.searchUsernameOrHashtag(null, 0, null, false, true);
searchingForUser = false;
searchItem.setSearchFieldText("", true);
}
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
searchCalendarButton.setVisibility(View.VISIBLE);
searchUserButton.setVisibility(View.VISIBLE);
searchingUserMessages = null;
searchingChatMessages = null;
}
}
@Override
public boolean forceShowClear() {
return searchingForUser;
}
});
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
if (threadMessageId == 0 && !UserObject.isReplyUser(currentUser) || threadMessageObject != null && threadMessageObject.getRepliesCount() == 0) {
searchItem.setVisibility(View.GONE);
}
searchItemVisible = false;
}
if (chatMode == 0 && threadMessageId == 0 && !UserObject.isReplyUser(currentUser) && reportType < 0 && !inMenuMode) {
TLRPC.UserFull userFull = null;
if (currentUser != null) {
audioCallIconItem = menu.addItem(call, R.drawable.ic_call, themeDelegate);
userFull = getMessagesController().getUserFull(currentUser.id);
if (userFull != null && userFull.phone_calls_available) {
showAudioCallAsIcon = !inPreviewMode;
audioCallIconItem.setVisibility(View.VISIBLE);
} else {
showAudioCallAsIcon = false;
audioCallIconItem.setVisibility(View.GONE);
}
}
headerItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate);
headerItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
if (currentUser != null) {
headerItem.addSubItem(call, R.drawable.msg_callback, LocaleController.getString("Call", R.string.Call), themeDelegate);
if (Build.VERSION.SDK_INT >= 18) {
headerItem.addSubItem(video_call, R.drawable.msg_videocall, LocaleController.getString("VideoCall", R.string.VideoCall), themeDelegate);
}
if (userFull != null && userFull.phone_calls_available) {
headerItem.showSubItem(call);
if (userFull.video_calls_available) {
headerItem.showSubItem(video_call);
} else {
headerItem.hideSubItem(video_call);
}
} else {
headerItem.hideSubItem(call);
headerItem.hideSubItem(video_call);
}
}
editTextItem = menu.addItem(0, R.drawable.ic_ab_other, themeDelegate);
editTextItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
editTextItem.setTag(null);
editTextItem.setVisibility(View.GONE);
editTextItem.addSubItem(text_spoiler, LocaleController.getString("Spoiler", R.string.Spoiler));
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(LocaleController.getString("Bold", R.string.Bold));
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextItem.addSubItem(text_bold, stringBuilder);
stringBuilder = new SpannableStringBuilder(LocaleController.getString("Italic", R.string.Italic));
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/ritalic.ttf")), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextItem.addSubItem(text_italic, stringBuilder);
stringBuilder = new SpannableStringBuilder(LocaleController.getString("Mono", R.string.Mono));
stringBuilder.setSpan(new TypefaceSpan(Typeface.MONOSPACE), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextItem.addSubItem(text_mono, stringBuilder);
if (currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 101) {
stringBuilder = new SpannableStringBuilder(LocaleController.getString("Strike", R.string.Strike));
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_STRIKE;
stringBuilder.setSpan(new TextStyleSpan(run), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextItem.addSubItem(text_strike, stringBuilder);
stringBuilder = new SpannableStringBuilder(LocaleController.getString("Underline", R.string.Underline));
run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_UNDERLINE;
stringBuilder.setSpan(new TextStyleSpan(run), 0, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
editTextItem.addSubItem(text_underline, stringBuilder);
}
editTextItem.addSubItem(text_link, LocaleController.getString("CreateLink", R.string.CreateLink));
editTextItem.addSubItem(text_regular, LocaleController.getString("Regular", R.string.Regular));
if (searchItem != null) {
headerItem.addSubItem(search, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search), themeDelegate);
}
if (currentChat != null && !currentChat.creator && !ChatObject.hasAdminRights(currentChat)) {
headerItem.addSubItem(report, R.drawable.msg_report, LocaleController.getString("ReportChat", R.string.ReportChat), themeDelegate);
}
if (currentUser != null) {
addContactItem = headerItem.addSubItem(share_contact, R.drawable.msg_addcontact, "", themeDelegate);
}
if (currentEncryptedChat != null) {
timeItem2 = headerItem.addSubItem(chat_enc_timer, R.drawable.msg_timer, LocaleController.getString("SetTimer", R.string.SetTimer), themeDelegate);
}
if (!ChatObject.isChannel(currentChat) || currentChat.megagroup && TextUtils.isEmpty(currentChat.username)) {
headerItem.addSubItem(clear_history, R.drawable.msg_clear, LocaleController.getString("ClearHistory", R.string.ClearHistory), themeDelegate);
} else if (ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_DELETE_MESSAGES)) {
headerItem.addSubItem(auto_delete_timer, R.drawable.msg_timer, LocaleController.getString("AutoDeleteSetTimer", R.string.AutoDeleteSetTimer), themeDelegate);
}
if (themeDelegate.isThemeChangeAvailable()) {
headerItem.addSubItem(change_colors, R.drawable.msg_colors, LocaleController.getString("ChangeColors", R.string.ChangeColors), themeDelegate);
}
if (currentUser == null || !currentUser.self) {
muteItem = headerItem.addSubItem(mute, R.drawable.msg_mute, null, themeDelegate);
}
if (ChatObject.isChannel(currentChat) && !currentChat.creator) {
if (!ChatObject.isNotInChat(currentChat)) {
if (currentChat.megagroup) {
headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveMegaMenu", R.string.LeaveMegaMenu), themeDelegate);
} else {
headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("LeaveChannelMenu", R.string.LeaveChannelMenu), themeDelegate);
}
}
} else if (!ChatObject.isChannel(currentChat)) {
if (currentChat != null) {
headerItem.addSubItem(delete_chat, R.drawable.msg_leave, LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), themeDelegate);
} else {
headerItem.addSubItem(delete_chat, R.drawable.msg_delete, LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), themeDelegate);
}
}
if (currentUser != null && currentUser.self) {
headerItem.addSubItem(add_shortcut, R.drawable.msg_home, LocaleController.getString("AddShortcut", R.string.AddShortcut), themeDelegate);
}
if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
headerItem.addSubItem(bot_settings, R.drawable.menu_settings, LocaleController.getString("BotSettings", R.string.BotSettings), themeDelegate);
headerItem.addSubItem(bot_help, R.drawable.menu_help, LocaleController.getString("BotHelp", R.string.BotHelp), themeDelegate);
updateBotButtons();
}
}
updateTitle();
avatarContainer.updateOnlineCount();
avatarContainer.updateSubtitle();
updateTitleIcons();
if (chatMode == 0 && !isThreadChat() && reportType < 0) {
attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other, themeDelegate).setOverrideMenuClick(true).setAllowCloseAnimation(false);
attachItem.setContentDescription(LocaleController.getString("AccDescrAttachButton", R.string.AccDescrAttachButton));
attachItem.setVisibility(View.GONE);
}
actionModeViews.clear();
if (inPreviewMode) {
if (headerItem != null) {
headerItem.setAlpha(0.0f);
}
if (attachItem != null) {
attachItem.setAlpha(0.0f);
}
}
final ActionBarMenu actionMode = actionBar.createActionMode();
selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
selectedMessagesCountTextView.setTextSize(18);
selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
selectedMessagesCountTextView.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
actionMode.addView(selectedMessagesCountTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
selectedMessagesCountTextView.setOnTouchListener((v, event) -> true);
if (currentEncryptedChat == null) {
actionModeViews.add(actionMode.addItemWithWidth(save_to, R.drawable.msg_download, AndroidUtilities.dp(54), LocaleController.getString("SaveToMusic", R.string.SaveToMusic)));
actionModeViews.add(actionMode.addItemWithWidth(edit, R.drawable.msg_edit, AndroidUtilities.dp(54), LocaleController.getString("Edit", R.string.Edit)));
actionModeViews.add(actionMode.addItemWithWidth(star, R.drawable.msg_fave, AndroidUtilities.dp(54), LocaleController.getString("AddToFavorites", R.string.AddToFavorites)));
actionModeViews.add(actionMode.addItemWithWidth(copy, R.drawable.msg_copy, AndroidUtilities.dp(54), LocaleController.getString("Copy", R.string.Copy)));
actionModeViews.add(actionMode.addItemWithWidth(forward, R.drawable.msg_forward, AndroidUtilities.dp(54), LocaleController.getString("Forward", R.string.Forward)));
actionModeViews.add(actionMode.addItemWithWidth(delete, R.drawable.msg_delete, AndroidUtilities.dp(54), LocaleController.getString("Delete", R.string.Delete)));
} else {
actionModeViews.add(actionMode.addItemWithWidth(edit, R.drawable.msg_edit, AndroidUtilities.dp(54), LocaleController.getString("Edit", R.string.Edit)));
actionModeViews.add(actionMode.addItemWithWidth(star, R.drawable.msg_fave, AndroidUtilities.dp(54), LocaleController.getString("AddToFavorites", R.string.AddToFavorites)));
actionModeViews.add(actionMode.addItemWithWidth(copy, R.drawable.msg_copy, AndroidUtilities.dp(54), LocaleController.getString("Copy", R.string.Copy)));
actionModeViews.add(actionMode.addItemWithWidth(delete, R.drawable.msg_delete, AndroidUtilities.dp(54), LocaleController.getString("Delete", R.string.Delete)));
}
actionMode.getItem(edit).setVisibility(canEditMessagesCount == 1 && selectedMessagesIds[0].size() + selectedMessagesIds[1].size() == 1 ? View.VISIBLE : View.GONE);
actionMode.getItem(copy).setVisibility(!getMessagesController().isChatNoForwards(currentChat) && selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0 ? View.VISIBLE : View.GONE);
actionMode.getItem(star).setVisibility(selectedMessagesCanStarIds[0].size() + selectedMessagesCanStarIds[1].size() != 0 ? View.VISIBLE : View.GONE);
actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
checkActionBarMenu(false);
scrimPaint = new Paint();
fragmentView = new SizeNotifierFrameLayout(context, parentLayout) {
int inputFieldHeight = 0;
int lastHeight;
int lastWidth;
ArrayList<ChatMessageCell> drawTimeAfter = new ArrayList<>();
ArrayList<ChatMessageCell> drawNamesAfter = new ArrayList<>();
ArrayList<ChatMessageCell> drawCaptionAfter = new ArrayList<>();
Paint backgroundPaint;
int backgroundColor;
@Override
protected void drawList(Canvas blurCanvas, boolean top) {
float cilpTop = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
for (int i = 0; i < chatListView.getChildCount(); i++) {
View child = chatListView.getChildAt(i);
if (top && child.getY() > cilpTop + AndroidUtilities.dp(40)) {
continue;
}
if (!top && child.getY() + child.getMeasuredHeight() < AndroidUtilities.dp(203)) {
continue;
}
blurCanvas.save();
blurCanvas.translate(chatListView.getX() + child.getX(), chatListView.getY() + child.getY());
child.draw(blurCanvas);
blurCanvas.restore();
}
}
@Override
protected int getScrollOffset() {
return chatListView.computeVerticalScrollOffset();
}
@Override
protected float getBottomOffset() {
return chatListView.getBottom();
}
AdjustPanLayoutHelper adjustPanLayoutHelper = new AdjustPanLayoutHelper(this) {
@Override
protected void onTransitionStart(boolean keyboardVisible, int contentHeight) {
wasManualScroll = true;
if (chatActivityEnterView != null) {
chatActivityEnterView.onAdjustPanTransitionStart(keyboardVisible);
}
}
@Override
protected void onTransitionEnd() {
if (chatActivityEnterView != null) {
chatActivityEnterView.onAdjustPanTransitionEnd();
}
}
@Override
protected void onPanTranslationUpdate(float y, float progress, boolean keyboardVisible) {
if (getParentLayout() != null && getParentLayout().isPreviewOpenAnimationInProgress()) {
return;
}
contentPanTranslation = y;
if (chatAttachAlert != null && chatAttachAlert.isShowing()) {
setNonNoveTranslation(y);
} else {
actionBar.setTranslationY(y);
emptyViewContainer.setTranslationY(y / 2);
progressView.setTranslationY(y / 2);
contentView.setBackgroundTranslation((int) y);
instantCameraView.onPanTranslationUpdate(y);
if (blurredView != null) {
blurredView.drawable.onPanTranslationUpdate(y);
}
setFragmentPanTranslationOffset((int) y);
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
}
chatListView.invalidate();
updateBulletinLayout();
}
@Override
protected boolean heightAnimationEnabled() {
ActionBarLayout actionBarLayout = getParentLayout();
if (inPreviewMode || inBubbleMode || AndroidUtilities.isInMultiwindow || actionBarLayout == null || fixedKeyboardHeight > 0) {
return false;
}
if (System.currentTimeMillis() - activityResumeTime < 250) {
return false;
}
if ((ChatActivity.this == actionBarLayout.getLastFragment() && actionBarLayout.isTransitionAnimationInProgress()) || actionBarLayout.isPreviewOpenAnimationInProgress() || isPaused || !openAnimationEnded || (chatAttachAlert != null && chatAttachAlert.isShowing())) {
return false;
}
if (chatActivityEnterView != null && chatActivityEnterView.getTrendingStickersAlert() != null && chatActivityEnterView.getTrendingStickersAlert().isShowing()) {
return false;
}
return true;
}
@Override
protected int startOffset() {
int keyboardSize = getKeyboardHeight();
if (keyboardSize <= AndroidUtilities.dp(20) && chatActivityEnterView.isPopupShowing()) {
return chatActivityEnterView.getEmojiPadding();
}
return 0;
}
};
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
adjustPanLayoutHelper.onAttach();
chatActivityEnterView.setAdjustPanLayoutHelper(adjustPanLayoutHelper);
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
if (messageObject != null && (messageObject.isRoundVideo() || messageObject.isVideo()) && messageObject.eventId == 0 && messageObject.getDialogId() == dialog_id) {
MediaController.getInstance().setTextureView(createTextureView(false), aspectRatioFrameLayout, videoPlayerContainer, true);
}
if (pullingDownDrawable != null) {
pullingDownDrawable.onAttach();
}
emojiAnimationsOverlay.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
adjustPanLayoutHelper.onDetach();
if (pullingDownDrawable != null) {
pullingDownDrawable.onDetach();
pullingDownDrawable = null;
}
emojiAnimationsOverlay.onDetachedFromWindow();
AndroidUtilities.runOnUIThread(() -> {
ReactionsEffectOverlay.removeCurrent(true);
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float expandY;
if (AndroidUtilities.isInMultiwindow || isInBubbleMode()) {
expandY = chatActivityEnterView.getEmojiView() != null ? chatActivityEnterView.getEmojiView().getY() : chatActivityEnterView.getY();
} else {
expandY = chatActivityEnterView.getY();
}
if (scrimView != null || chatActivityEnterView != null && chatActivityEnterView.isStickersExpanded() && ev.getY() < expandY) {
return false;
}
lastTouchY = ev.getY();
TextSelectionHelper.TextSelectionOverlay selectionOverlay = textSelectionHelper.getOverlayView(context);
ev.offsetLocation(-selectionOverlay.getX(), -selectionOverlay.getY());
if (textSelectionHelper.isSelectionMode() && textSelectionHelper.getOverlayView(context).onTouchEvent(ev)) {
return true;
} else {
ev.offsetLocation(selectionOverlay.getX(), selectionOverlay.getY());
}
if (selectionOverlay.checkOnTap(ev)) {
ev.setAction(MotionEvent.ACTION_CANCEL);
}
if (ev.getAction() == MotionEvent.ACTION_DOWN && textSelectionHelper.isSelectionMode() && (ev.getY() < chatListView.getTop() || ev.getY() > chatListView.getBottom())) {
ev.offsetLocation(-selectionOverlay.getX(), -selectionOverlay.getY());
if (textSelectionHelper.getOverlayView(context).onTouchEvent(ev)) {
ev.offsetLocation(selectionOverlay.getX(), selectionOverlay.getY());
return super.dispatchTouchEvent(ev);
} else {
return true;
}
}
if (pinchToZoomHelper.isInOverlayMode()) {
return pinchToZoomHelper.onTouchEvent(ev);
}
if (AvatarPreviewer.hasVisibleInstance()) {
AvatarPreviewer.getInstance().onTouchEvent(ev);
return true;
}
return super.dispatchTouchEvent(ev);
}
@Override
protected void onDraw(Canvas canvas) {
if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) != null) {
return;
}
if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) == null && (instantCameraView.blurFullyDrawing() || (blurredView != null && blurredView.fullyDrawing() && blurredView.getTag() != null))) {
return;
}
super.onDraw(canvas);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if ((scrimView != null || messageEnterTransitionContainer.isRunning()) && (child == pagedownButton || child == mentiondownButton || child == floatingDateView || child == fireworksOverlay || child == reactionsMentiondownButton || child == gifHintTextView)) {
return false;
}
if (child == fragmentContextView && fragmentContextView.isCallStyle()) {
return true;
}
if (child == undoView && PhotoViewer.getInstance().isVisible()) {
return true;
}
if (toPullingDownTransition && child == chatListView) {
return true;
}
if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) != null) {
boolean needBlur;
if (((int) getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND)) == BlurBehindDrawable.STATIC_CONTENT) {
needBlur = child == actionBar || child == fragmentContextView || child == pinnedMessageView;
} else {
needBlur = child == chatListView || child == chatActivityEnterView || chatActivityEnterView.isPopupView(child);
}
if (!needBlur) {
return false;
}
} else if (getTag(BlurBehindDrawable.TAG_DRAWING_AS_BACKGROUND) == null && (instantCameraView.blurFullyDrawing() || (blurredView != null && blurredView.fullyDrawing() && blurredView.getTag() != null))) {
boolean needBlur = child == actionBar || child == chatListView || child == pinnedMessageView || child == fragmentContextView;
if (needBlur) {
return false;
}
}
boolean result;
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
boolean isRoundVideo = false;
boolean isVideo = messageObject != null && messageObject.eventId == 0 && ((isRoundVideo = messageObject.isRoundVideo()) || messageObject.isVideo());
if (child == videoPlayerContainer) {
canvas.save();
float transitionOffset = 0;
if (pullingDownAnimateProgress != 0) {
transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
}
canvas.translate(0, -pullingDownOffset - transitionOffset);
if (messageObject != null && messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
if (Theme.chat_roundVideoShadow != null && aspectRatioFrameLayout.isDrawingReady()) {
int x = (int) child.getX() - AndroidUtilities.dp(3);
int y = (int) child.getY() - AndroidUtilities.dp(2);
canvas.save();
canvas.scale(videoPlayerContainer.getScaleX(), videoPlayerContainer.getScaleY(), child.getX(), child.getY());
Theme.chat_roundVideoShadow.setAlpha(255);
Theme.chat_roundVideoShadow.setBounds(x, y, x + AndroidUtilities.roundPlayingMessageSize + AndroidUtilities.dp(6), y + AndroidUtilities.roundPlayingMessageSize + AndroidUtilities.dp(6));
Theme.chat_roundVideoShadow.draw(canvas);
canvas.restore();
}
result = super.drawChild(canvas, child, drawingTime);
} else {
if (child.getTag() == null) {
float oldTranslation = child.getTranslationY();
child.setTranslationY(-AndroidUtilities.dp(1000));
result = super.drawChild(canvas, child, drawingTime);
child.setTranslationY(oldTranslation);
} else {
result = false;
}
}
canvas.restore();
} else {
result = super.drawChild(canvas, child, drawingTime);
if (isVideo && child == chatListView && messageObject.type != 5 && videoPlayerContainer != null && videoPlayerContainer.getTag() != null) {
canvas.save();
float transitionOffset = 0;
if (pullingDownAnimateProgress != 0) {
transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
}
canvas.translate(0, -pullingDownOffset - transitionOffset);
super.drawChild(canvas, videoPlayerContainer, drawingTime);
if (drawLaterRoundProgressCell != null) {
canvas.save();
canvas.translate(drawLaterRoundProgressCell.getX(), drawLaterRoundProgressCell.getTop() + chatListView.getY());
if (isRoundVideo) {
drawLaterRoundProgressCell.drawRoundProgress(canvas);
invalidate();
drawLaterRoundProgressCell.invalidate();
} else {
drawLaterRoundProgressCell.drawOverlays(canvas);
if (drawLaterRoundProgressCell.needDrawTime()) {
drawLaterRoundProgressCell.drawTime(canvas, drawLaterRoundProgressCell.getAlpha(), true);
}
}
canvas.restore();
}
canvas.restore();
}
}
if (child == actionBar && parentLayout != null) {
parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? (int) actionBar.getTranslationY() + actionBar.getMeasuredHeight() + (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) : 0);
}
return result;
}
@Override
protected boolean isActionBarVisible() {
return actionBar.getVisibility() == VISIBLE;
}
private void drawChildElement(Canvas canvas, float listTop, ChatMessageCell cell, int type) {
canvas.save();
float canvasOffsetX = chatListView.getLeft() + cell.getLeft();
float canvasOffsetY = chatListView.getY() + cell.getY();
float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
canvas.clipRect(chatListView.getLeft(), listTop, chatListView.getRight(), chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset);
canvas.translate(canvasOffsetX, canvasOffsetY);
cell.setInvalidatesParent(true);
if (type == 0) {
cell.drawTime(canvas, alpha, true);
} else if (type == 1) {
cell.drawNamesLayout(canvas, alpha);
} else {
cell.drawCaptionLayout(canvas, cell.getCurrentPosition() != null && (cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_LEFT) == 0, alpha);
}
cell.setInvalidatesParent(false);
canvas.restore();
}
@Override
protected void dispatchDraw(Canvas canvas) {
chatActivityEnterView.checkAnimation();
updateChatListViewTopPadding();
if (invalidateMessagesVisiblePart || (chatListItemAnimator != null && chatListItemAnimator.isRunning())) {
invalidateMessagesVisiblePart = false;
updateMessagesVisiblePart(false);
}
updateTextureViewPosition(false);
updatePagedownButtonsPosition();
super.dispatchDraw(canvas);
if (fragmentContextView != null && fragmentContextView.isCallStyle()) {
float alpha = (blurredView != null && blurredView.getVisibility() == View.VISIBLE) ? 1f - blurredView.getAlpha() : 1f;
if (alpha > 0) {
if (alpha == 1f) {
canvas.save();
} else {
canvas.saveLayerAlpha(fragmentContextView.getX(), fragmentContextView.getY() - AndroidUtilities.dp(30), fragmentContextView.getX() + fragmentContextView.getMeasuredWidth(), fragmentContextView.getY() + fragmentContextView.getMeasuredHeight(), (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
}
canvas.translate(fragmentContextView.getX(), fragmentContextView.getY());
fragmentContextView.setDrawOverlay(true);
fragmentContextView.draw(canvas);
fragmentContextView.setDrawOverlay(false);
canvas.restore();
}
}
if (chatActivityEnterView != null) {
if (chatActivityEnterView.pannelAniamationInProgress() && chatActivityEnterView.getEmojiPadding() < bottomPanelTranslationY) {
int color = getThemedColor(Theme.key_chat_emojiPanelBackground);
if (backgroundPaint == null) {
backgroundPaint = new Paint();
}
if (backgroundColor != color) {
backgroundPaint.setColor(backgroundColor = color);
}
int offset = (int) (bottomPanelTranslationY - chatActivityEnterView.getEmojiPadding()) + 3;
canvas.drawRect(0, getMeasuredHeight() - offset, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
setFragmentPanTranslationOffset(chatActivityEnterView.getEmojiPadding());
}
}
for (int a = 0, N = animateSendingViews.size(); a < N; a++) {
ChatMessageCell cell = animateSendingViews.get(a);
MessageObject.SendAnimationData data = cell.getMessageObject().sendAnimationData;
if (data != null) {
canvas.save();
ImageReceiver imageReceiver = cell.getPhotoImage();
canvas.translate(data.currentX, data.currentY);
canvas.scale(data.currentScale, data.currentScale);
canvas.translate(-imageReceiver.getCenterX(), -imageReceiver.getCenterY());
cell.setTimeAlpha(data.timeAlpha);
animateSendingViews.get(a).draw(canvas);
canvas.restore();
}
}
if (scrimViewReaction == null || scrimView == null) {
scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (scrimView != null ? scrimViewAlpha : 1f)));
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
}
if (scrimView != null) {
if (scrimView == reactionsMentiondownButton || scrimView == mentiondownButton) {
if (scrimViewAlpha < 1f) {
scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
}
} else if (scrimView instanceof ImageView) {
int c = canvas.save();
if (scrimViewAlpha < 1f) {
canvas.saveLayerAlpha(scrimView.getLeft(), scrimView.getTop(), scrimView.getRight(), scrimView.getBottom(), (int) (255 * scrimViewAlpha), Canvas.ALL_SAVE_FLAG);
}
canvas.translate(scrimView.getLeft(), scrimView.getTop());
if (scrimView == actionBar.getBackButton()) {
int r = Math.max(scrimView.getMeasuredWidth(), scrimView.getMeasuredHeight()) / 2;
canvas.drawCircle(r, r, r * 0.8f, actionBarBackgroundPaint);
}
scrimView.draw(canvas);
canvas.restoreToCount(c);
if (scrimViewAlpha < 1f) {
scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
}
} else {
float listTop = chatListView.getY() + chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
MessageObject.GroupedMessages scrimGroup;
if (scrimView instanceof ChatMessageCell) {
scrimGroup = ((ChatMessageCell) scrimView).getCurrentMessagesGroup();
} else {
scrimGroup = null;
}
boolean groupedBackgroundWasDraw = false;
int count = chatListView.getChildCount();
for (int num = 0; num < count; num++) {
View child = chatListView.getChildAt(num);
MessageObject.GroupedMessages group;
MessageObject.GroupedMessagePosition position;
ChatMessageCell cell;
if (child instanceof ChatMessageCell) {
cell = (ChatMessageCell) child;
group = cell.getCurrentMessagesGroup();
position = cell.getCurrentPosition();
} else {
position = null;
group = null;
cell = null;
}
if (child != scrimView && (scrimGroup == null || scrimGroup != group) || child.getAlpha() == 0f) {
continue;
}
if (!groupedBackgroundWasDraw && cell != null && scrimGroup != null && scrimGroup.transitionParams.cell != null) {
float x = scrimGroup.transitionParams.cell.getNonAnimationTranslationX(true);
float l = (scrimGroup.transitionParams.left + x + scrimGroup.transitionParams.offsetLeft);
float t = (scrimGroup.transitionParams.top + scrimGroup.transitionParams.offsetTop);
float r = (scrimGroup.transitionParams.right + x + scrimGroup.transitionParams.offsetRight);
float b = (scrimGroup.transitionParams.bottom + scrimGroup.transitionParams.offsetBottom);
if (!scrimGroup.transitionParams.backgroundChangeBounds) {
t += scrimGroup.transitionParams.cell.getTranslationY();
b += scrimGroup.transitionParams.cell.getTranslationY();
}
if (t < chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20)) {
t = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20);
}
if (b > chatListView.getMeasuredHeight() + AndroidUtilities.dp(20)) {
b = chatListView.getMeasuredHeight() + AndroidUtilities.dp(20);
}
boolean selected = true;
for (int a = 0, N = scrimGroup.messages.size(); a < N; a++) {
MessageObject object = scrimGroup.messages.get(a);
int index = object.getDialogId() == dialog_id ? 0 : 1;
if (selectedMessagesIds[index].indexOfKey(object.getId()) < 0) {
selected = false;
break;
}
}
canvas.save();
canvas.clipRect(0, listTop, getMeasuredWidth(), chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset);
canvas.translate(0, chatListView.getY());
scrimGroup.transitionParams.cell.drawBackground(canvas, (int) l, (int) t, (int) r, (int) b, scrimGroup.transitionParams.pinnedTop, scrimGroup.transitionParams.pinnedBotton, selected, contentView.getKeyboardHeight());
canvas.restore();
groupedBackgroundWasDraw = true;
}
if (cell != null && cell.getPhotoImage().isAnimationRunning()) {
invalidate();
}
float viewClipLeft = chatListView.getLeft();
float viewClipTop = listTop;
float viewClipRight = chatListView.getRight();
float viewClipBottom = chatListView.getY() + chatListView.getMeasuredHeight() - blurredViewBottomOffset;
if (cell == null || !cell.getTransitionParams().animateBackgroundBoundsInner) {
viewClipLeft = Math.max(viewClipLeft, chatListView.getLeft() + child.getX());
viewClipTop = Math.max(viewClipTop, chatListView.getTop() + child.getY());
viewClipRight = Math.min(viewClipRight, chatListView.getLeft() + child.getX() + child.getMeasuredWidth());
viewClipBottom = Math.min(viewClipBottom, chatListView.getY() + child.getY() + child.getMeasuredHeight());
}
if (viewClipTop < viewClipBottom) {
if (child.getAlpha() != 1f) {
canvas.saveLayerAlpha(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom, (int) (255 * child.getAlpha()), Canvas.ALL_SAVE_FLAG);
} else {
canvas.save();
}
if (cell != null) {
cell.setInvalidatesParent(true);
cell.setScrimReaction(scrimViewReaction);
}
canvas.clipRect(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom);
canvas.translate(chatListView.getLeft() + child.getX(), chatListView.getY() + child.getY());
if (cell != null && scrimGroup == null && cell.drawBackgroundInParent()) {
cell.drawBackgroundInternal(canvas, true);
}
child.draw(canvas);
if (cell != null && cell.hasOutboundsContent()) {
cell.drawOutboundsContent(canvas);
}
canvas.restore();
if (cell != null) {
cell.setInvalidatesParent(false);
cell.setScrimReaction(null);
}
}
if (position != null || (cell != null && cell.getTransitionParams().animateBackgroundBoundsInner)) {
if (position == null || position.last || position.minX == 0 && position.minY == 0) {
if (position == null || position.last) {
drawTimeAfter.add(cell);
}
if (position == null || (position.minX == 0 && position.minY == 0 && cell.hasNameLayout())) {
drawNamesAfter.add(cell);
}
}
if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
drawCaptionAfter.add(cell);
}
}
if (scrimViewReaction != null && cell != null) {
scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * scrimViewAlpha));
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
if (viewClipTop < viewClipBottom) {
float alpha = child.getAlpha() * scrimViewAlpha;
if (alpha < 1f) {
canvas.saveLayerAlpha(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom, (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
} else {
canvas.save();
}
canvas.clipRect(viewClipLeft, viewClipTop, viewClipRight, viewClipBottom);
canvas.translate(chatListView.getLeft() + child.getX(), chatListView.getY() + child.getY());
cell.drawScrimReaction(canvas, scrimViewReaction);
canvas.restore();
}
}
}
int size = drawTimeAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
drawChildElement(canvas, listTop, drawTimeAfter.get(a), 0);
}
drawTimeAfter.clear();
}
size = drawNamesAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
drawChildElement(canvas, listTop, drawNamesAfter.get(a), 1);
}
drawNamesAfter.clear();
}
size = drawCaptionAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
ChatMessageCell cell = drawCaptionAfter.get(a);
if (cell.getCurrentPosition() == null && !cell.getTransitionParams().animateBackgroundBoundsInner) {
continue;
}
drawChildElement(canvas, listTop, cell, 2);
}
drawCaptionAfter.clear();
}
}
if (scrimViewReaction == null && scrimViewAlpha < 1f) {
scrimPaint.setAlpha((int) (255 * scrimPaintAlpha * (1f - scrimViewAlpha)));
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), scrimPaint);
}
}
if (scrimView != null || messageEnterTransitionContainer.isRunning()) {
if (pagedownButton != null && pagedownButton.getTag() != null) {
super.drawChild(canvas, pagedownButton, SystemClock.uptimeMillis());
}
if (mentiondownButton != null && mentiondownButton.getTag() != null) {
super.drawChild(canvas, mentiondownButton, SystemClock.uptimeMillis());
}
if (reactionsMentiondownButton != null && reactionsMentiondownButton.getTag() != null) {
super.drawChild(canvas, reactionsMentiondownButton, SystemClock.uptimeMillis());
}
if (floatingDateView != null && floatingDateView.getTag() != null) {
super.drawChild(canvas, floatingDateView, SystemClock.uptimeMillis());
}
if (fireworksOverlay != null) {
super.drawChild(canvas, fireworksOverlay, SystemClock.uptimeMillis());
}
if (gifHintTextView != null) {
super.drawChild(canvas, gifHintTextView, SystemClock.uptimeMillis());
}
}
if (fixedKeyboardHeight > 0 && keyboardHeight < AndroidUtilities.dp(20)) {
int color = getThemedColor(Theme.key_windowBackgroundWhite);
if (backgroundPaint == null) {
backgroundPaint = new Paint();
}
if (backgroundColor != color) {
backgroundPaint.setColor(backgroundColor = color);
}
canvas.drawRect(0, getMeasuredHeight() - fixedKeyboardHeight, getMeasuredWidth(), getMeasuredHeight(), backgroundPaint);
}
if (pullingDownDrawable != null && pullingDownDrawable.needDrawBottomPanel()) {
int top, bottom;
if (chatActivityEnterView != null && chatActivityEnterView.getVisibility() == View.VISIBLE) {
top = chatActivityEnterView.getTop() + AndroidUtilities.dp2(2);
bottom = chatActivityEnterView.getBottom();
} else {
top = bottomOverlayChat.getTop() + AndroidUtilities.dp2(2);
bottom = bottomOverlayChat.getBottom();
}
pullingDownDrawable.drawBottomPanel(canvas, top, bottom, getMeasuredWidth());
}
if (pullingDownAnimateToActivity != null) {
canvas.saveLayerAlpha(0, 0, getMeasuredWidth(), getMeasuredHeight(), (int) (255 * pullingDownAnimateProgress), Canvas.ALL_SAVE_FLAG);
pullingDownAnimateToActivity.fragmentView.draw(canvas);
canvas.restore();
}
emojiAnimationsOverlay.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int allHeight;
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = allHeight = MeasureSpec.getSize(heightMeasureSpec);
if (lastWidth != widthSize) {
globalIgnoreLayout = true;
lastWidth = widthMeasureSpec;
if (!inPreviewMode && currentUser != null && currentUser.self) {
SimpleTextView textView = avatarContainer.getTitleTextView();
int textWidth = (int) textView.getPaint().measureText(textView.getText(), 0, textView.getText().length());
if (widthSize - AndroidUtilities.dp(96 + 56) > textWidth + AndroidUtilities.dp(10)) {
showSearchAsIcon = !showAudioCallAsIcon;
} else {
showSearchAsIcon = false;
}
} else {
showSearchAsIcon = false;
}
if (showSearchAsIcon || showAudioCallAsIcon) {
if (avatarContainer != null && avatarContainer.getLayoutParams() != null) {
((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(96);
}
} else {
if (avatarContainer != null && avatarContainer.getLayoutParams() != null) {
((MarginLayoutParams) avatarContainer.getLayoutParams()).rightMargin = AndroidUtilities.dp(40);
}
}
if (showSearchAsIcon) {
if (!actionBar.isSearchFieldVisible() && searchIconItem != null) {
searchIconItem.setVisibility(View.VISIBLE);
}
if (headerItem != null) {
headerItem.hideSubItem(search);
}
} else {
if (headerItem != null) {
headerItem.showSubItem(search);
}
if (searchIconItem != null) {
searchIconItem.setVisibility(View.GONE);
}
}
if (!actionBar.isSearchFieldVisible() && audioCallIconItem != null) {
audioCallIconItem.setVisibility((showAudioCallAsIcon && !showSearchAsIcon) ? View.VISIBLE : View.GONE);
}
if (headerItem != null) {
TLRPC.UserFull userInfo = getCurrentUserInfo();
if (showAudioCallAsIcon) {
headerItem.hideSubItem(call);
} else if (userInfo != null && userInfo.phone_calls_available) {
headerItem.showSubItem(call);
}
}
globalIgnoreLayout = false;
}
setMeasuredDimension(widthSize, heightSize);
heightSize -= getPaddingTop();
measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
int actionBarHeight = actionBar.getMeasuredHeight();
if (actionBar.getVisibility() == VISIBLE) {
heightSize -= actionBarHeight;
}
int keyboardHeightOld = keyboardHeight + chatEmojiViewPadding;
boolean keyboardVisibleOld = keyboardHeight + chatEmojiViewPadding >= AndroidUtilities.dp(20);
if (lastHeight != allHeight) {
measureKeyboardHeight();
}
int keyboardSize = getKeyboardHeight();
if (fixedKeyboardHeight > 0 && keyboardSize <= AndroidUtilities.dp(20)) {
chatEmojiViewPadding = fixedKeyboardHeight;
} else {
if (keyboardSize <= AndroidUtilities.dp(20)) {
chatEmojiViewPadding = chatActivityEnterView.isPopupShowing() ? chatActivityEnterView.getEmojiPadding() : 0;
} else {
chatEmojiViewPadding = 0;
}
}
setEmojiKeyboardHeight(chatEmojiViewPadding);
boolean keyboardVisible = keyboardHeight + chatEmojiViewPadding >= AndroidUtilities.dp(20);
boolean waitingChatListItemAnimator = false;
if (MediaController.getInstance().getPlayingMessageObject() != null && MediaController.getInstance().getPlayingMessageObject().isRoundVideo() && keyboardVisibleOld != keyboardVisible) {
for (int i = 0; i < chatListView.getChildCount(); i++) {
View child = chatListView.getChildAt(i);
if (child instanceof ChatMessageCell) {
MessageObject messageObject = ((ChatMessageCell) child).getMessageObject();
if (messageObject.isRoundVideo() && MediaController.getInstance().isPlayingMessage(messageObject)) {
int p = chatListView.getChildAdapterPosition(child);
if (p >= 0) {
chatLayoutManager.scrollToPositionWithOffset(p, (int) ((chatListView.getMeasuredHeight() - chatListViewPaddingTop + (keyboardHeight + chatEmojiViewPadding - keyboardHeightOld) - (keyboardVisible ? AndroidUtilities.roundMessageSize : AndroidUtilities.roundPlayingMessageSize)) / 2), false);
chatAdapter.notifyItemChanged(p);
adjustPanLayoutHelper.delayAnimation();
waitingChatListItemAnimator = true;
break;
}
}
}
}
}
if (!waitingChatListItemAnimator) {
chatActivityEnterView.runEmojiPanelAnimation();
}
int childCount = getChildCount();
measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
int listViewTopHeight;
if (inPreviewMode) {
inputFieldHeight = 0;
listViewTopHeight = 0;
} else {
inputFieldHeight = chatActivityEnterView.getMeasuredHeight();
listViewTopHeight = AndroidUtilities.dp(49);
}
blurredViewTopOffset = 0;
blurredViewBottomOffset = 0;
if (SharedConfig.chatBlurEnabled()) {
blurredViewTopOffset = actionBarHeight;
blurredViewBottomOffset = AndroidUtilities.dp(203);
}
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView || child == actionBar) {
continue;
}
if (child == backgroundView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == blurredView) {
int h = allHeight;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
h += keyboardSize;
}
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == chatListView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int h = heightSize - listViewTopHeight - (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) + blurredViewTopOffset + blurredViewBottomOffset;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
h += keyboardSize;
}
int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), h), MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == progressView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(Math.max(AndroidUtilities.dp(10), heightSize - inputFieldHeight - (inPreviewMode && Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0) + AndroidUtilities.dp(2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))), MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == instantCameraView || child == overlayView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight - inputFieldHeight - chatEmojiViewPadding + AndroidUtilities.dp(3), MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == emptyViewContainer) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (child == messagesSearchListView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int contentHeightSpec = MeasureSpec.makeMeasureSpec(allHeight - actionBarHeight - AndroidUtilities.dp(48), MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (chatActivityEnterView.isPopupView(child)) {
if (inBubbleMode) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - inputFieldHeight + actionBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
} else if (AndroidUtilities.isInMultiwindow) {
if (AndroidUtilities.isTablet()) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320), heightSize - inputFieldHeight + actionBarHeight - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - inputFieldHeight + actionBarHeight - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
}
} else {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
}
} else if (child == mentionContainer) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer.getLayoutParams();
if (mentionsAdapter.isBannedInline()) {
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST));
} else {
int height;
mentionListViewIgnoreLayout = true;
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
int size = mentionGridLayoutManager.getRowsCount(widthSize);
int maxHeight = size * 102;
if (mentionsAdapter.isBotContext()) {
if (mentionsAdapter.getBotContextSwitch() != null) {
maxHeight += 34;
}
}
height = heightSize - chatActivityEnterView.getMeasuredHeight() + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
int padding = Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f)));
if (mentionLayoutManager.getReverseLayout()) {
mentionListView.setPadding(0, 0, 0, padding);
} else {
mentionListView.setPadding(0, padding, 0, 0);
}
} else {
int size = mentionsAdapter.getItemCount();
int maxHeight = 0;
if (mentionsAdapter.isBotContext()) {
if (mentionsAdapter.getBotContextSwitch() != null) {
maxHeight += 36;
size -= 1;
}
maxHeight += size * 68;
} else {
maxHeight += size * 36;
}
height = heightSize - chatActivityEnterView.getMeasuredHeight() + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
int padding = Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f)));
if (mentionLayoutManager.getReverseLayout()) {
mentionListView.setPadding(0, 0, 0, padding);
} else {
mentionListView.setPadding(0, padding, 0, 0);
}
}
layoutParams.height = height;
layoutParams.topMargin = 0;
mentionListViewIgnoreLayout = false;
child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
}
} else if (child == textSelectionHelper.getOverlayView(context)) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int h = heightSize + blurredViewTopOffset;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
h += keyboardSize;
textSelectionHelper.setKeyboardSize(keyboardSize);
} else {
textSelectionHelper.setKeyboardSize(0);
}
child.measure(contentWidthSpec, MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY));
} else if (child == forwardingPreviewView) {
int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
int h = allHeight - AndroidUtilities.statusBarHeight;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
h += keyboardSize;
}
int contentHeightSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
}
if (fixPaddingsInLayout) {
globalIgnoreLayout = true;
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
fixPaddingsInLayout = false;
chatListView.measure(MeasureSpec.makeMeasureSpec(chatListView.getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(chatListView.getMeasuredHeight(), MeasureSpec.EXACTLY));
globalIgnoreLayout = false;
}
if (scrollToPositionOnRecreate != -1) {
final int scrollTo = scrollToPositionOnRecreate;
AndroidUtilities.runOnUIThread(() -> chatLayoutManager.scrollToPositionWithOffset(scrollTo, scrollToOffsetOnRecreate));
scrollToPositionOnRecreate = -1;
}
updateBulletinLayout();
lastHeight = allHeight;
}
@Override
public void requestLayout() {
if (globalIgnoreLayout) {
return;
}
super.requestLayout();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int keyboardSize = getKeyboardHeight();
int paddingBottom;
if (fixedKeyboardHeight > 0 && keyboardSize <= AndroidUtilities.dp(20)) {
paddingBottom = fixedKeyboardHeight;
} else {
paddingBottom = keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !inBubbleMode ? chatActivityEnterView.getEmojiPadding() : 0;
}
if (!SharedConfig.smoothKeyboard) {
setBottomClip(paddingBottom);
}
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child == null || child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.LEFT;
}
final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = r - width - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = lp.leftMargin;
}
switch(verticalGravity) {
case Gravity.TOP:
childTop = lp.topMargin + getPaddingTop();
if (child != actionBar && actionBar.getVisibility() == VISIBLE) {
childTop += actionBar.getMeasuredHeight();
if (inPreviewMode && Build.VERSION.SDK_INT >= 21) {
childTop += AndroidUtilities.statusBarHeight;
}
}
break;
case Gravity.CENTER_VERTICAL:
childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
break;
default:
childTop = lp.topMargin;
}
if (child == blurredView || child == backgroundView) {
childTop = 0;
} else if (child instanceof HintView || child instanceof ChecksHintView) {
childTop = 0;
} else if (child == mentionContainer) {
childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
} else if (child == pagedownButton || child == mentiondownButton || child == reactionsMentiondownButton) {
if (!inPreviewMode) {
childTop -= chatActivityEnterView.getMeasuredHeight();
}
} else if (child == emptyViewContainer) {
childTop -= inputFieldHeight / 2 - (actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() / 2 : 0);
} else if (chatActivityEnterView.isPopupView(child)) {
if (AndroidUtilities.isInMultiwindow || inBubbleMode) {
childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight() + AndroidUtilities.dp(1);
} else {
childTop = chatActivityEnterView.getBottom();
}
} else if (child == gifHintTextView || child == voiceHintTextView || child == mediaBanTooltip) {
childTop -= inputFieldHeight;
} else if (child == chatListView || child == floatingDateView || child == infoTopView) {
childTop -= blurredViewTopOffset;
if (!inPreviewMode) {
childTop -= (inputFieldHeight - AndroidUtilities.dp(51));
}
childTop -= paddingBottom;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
childTop -= keyboardSize;
}
} else if (child == progressView) {
if (chatActivityEnterView.isTopViewVisible()) {
childTop -= AndroidUtilities.dp(48);
}
} else if (child == actionBar) {
if (inPreviewMode && Build.VERSION.SDK_INT >= 21) {
childTop += AndroidUtilities.statusBarHeight;
}
childTop -= getPaddingTop();
} else if (child == videoPlayerContainer) {
childTop = actionBar.getMeasuredHeight();
childTop -= paddingBottom;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
childTop -= keyboardSize;
}
} else if (child == instantCameraView || child == overlayView || child == animatingImageView) {
childTop = 0;
} else if (child == textSelectionHelper.getOverlayView(context)) {
childTop -= paddingBottom;
if (keyboardSize > AndroidUtilities.dp(20) && getLayoutParams().height < 0) {
childTop -= keyboardSize;
}
childTop -= blurredViewTopOffset;
} else if (chatActivityEnterView != null && child == chatActivityEnterView.botCommandsMenuContainer) {
childTop -= inputFieldHeight;
} else if (child == forwardingPreviewView) {
childTop = AndroidUtilities.statusBarHeight;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
updateTextureViewPosition(false);
if (!scrollingChatListView) {
checkAutoDownloadMessages(false);
}
notifyHeightChanged();
}
private void setNonNoveTranslation(float y) {
contentView.setTranslationY(y);
actionBar.setTranslationY(0);
emptyViewContainer.setTranslationY(0);
progressView.setTranslationY(0);
contentPanTranslation = 0;
contentView.setBackgroundTranslation(0);
instantCameraView.onPanTranslationUpdate(0);
if (blurredView != null) {
blurredView.drawable.onPanTranslationUpdate(0);
}
setFragmentPanTranslationOffset(0);
invalidateChatListViewTopPadding();
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
contentPaddingTop = top;
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == 1 && forwardingPreviewView != null && forwardingPreviewView.isShowing()) {
forwardingPreviewView.dismiss(true);
return true;
}
return super.dispatchKeyEvent(event);
}
protected Drawable getNewDrawable() {
Drawable drawable = themeDelegate.getWallpaperDrawable();
return drawable != null ? drawable : super.getNewDrawable();
}
};
contentView = (SizeNotifierFrameLayout) fragmentView;
contentView.needBlur = true;
if (inBubbleMode) {
contentView.setOccupyStatusBar(false);
}
contentView.setBackgroundImage(Theme.getCachedWallpaper(), Theme.isWallpaperMotion());
emptyViewContainer = new FrameLayout(context);
emptyViewContainer.setVisibility(View.INVISIBLE);
contentView.addView(emptyViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
emptyViewContainer.setOnTouchListener((v, event) -> true);
int distance = getArguments().getInt("nearby_distance", -1);
if ((distance >= 0 || preloadedGreetingsSticker != null) && currentUser != null && !userBlocked) {
greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate);
greetingsViewContainer.setListener((sticker) -> {
animatingDocuments.put(sticker, 0);
SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0);
});
greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0));
} else if (currentEncryptedChat == null) {
if (!isThreadChat() && chatMode == 0 && (currentUser != null && currentUser.self || currentChat != null && currentChat.creator)) {
bigEmptyView = new ChatBigEmptyView(context, contentView, currentChat != null ? ChatBigEmptyView.EMPTY_VIEW_TYPE_GROUP : ChatBigEmptyView.EMPTY_VIEW_TYPE_SAVED, themeDelegate);
emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
if (currentChat != null) {
bigEmptyView.setStatusText(AndroidUtilities.replaceTags(LocaleController.getString("GroupEmptyTitle1", R.string.GroupEmptyTitle1)));
}
} else {
String emptyMessage = null;
if (isThreadChat()) {
if (isComments) {
emptyMessage = LocaleController.getString("NoComments", R.string.NoComments);
} else {
emptyMessage = LocaleController.getString("NoReplies", R.string.NoReplies);
}
} else if (chatMode == MODE_SCHEDULED) {
emptyMessage = LocaleController.getString("NoScheduledMessages", R.string.NoScheduledMessages);
} else if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000 && currentUser.id != 4244000 && MessagesController.isSupportUser(currentUser)) {
emptyMessage = LocaleController.getString("GotAQuestion", R.string.GotAQuestion);
} else if (currentUser == null || currentUser.self || currentUser.deleted || userBlocked) {
emptyMessage = LocaleController.getString("NoMessages", R.string.NoMessages);
}
if (emptyMessage == null) {
greetingsViewContainer = new ChatGreetingsView(context, currentUser, distance, currentAccount, preloadedGreetingsSticker, themeDelegate);
greetingsViewContainer.setListener((sticker) -> {
animatingDocuments.put(sticker, 0);
SendMessagesHelper.getInstance(currentAccount).sendSticker(sticker, null, dialog_id, null, null, null, null, true, 0);
});
greetingsViewContainer.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(10), greetingsViewContainer, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
emptyViewContainer.addView(greetingsViewContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 68, 0, 68, 0));
} else {
emptyView = new TextView(context);
emptyView.setText(emptyMessage);
emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
emptyView.setGravity(Gravity.CENTER);
emptyView.setTextColor(getThemedColor(Theme.key_chat_serviceText));
emptyView.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(6), emptyView, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10), AndroidUtilities.dp(3));
emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
}
}
} else {
bigEmptyView = new ChatBigEmptyView(context, contentView, ChatBigEmptyView.EMPTY_VIEW_TYPE_SECRET, themeDelegate);
if (currentEncryptedChat.admin_id == getUserConfig().getClientUserId()) {
bigEmptyView.setStatusText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, UserObject.getFirstName(currentUser)));
} else {
bigEmptyView.setStatusText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming", R.string.EncryptedPlaceholderTitleIncoming, UserObject.getFirstName(currentUser)));
}
emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
}
CharSequence oldMessage;
if (chatActivityEnterView != null) {
chatActivityEnterView.onDestroy();
if (!chatActivityEnterView.isEditingMessage()) {
oldMessage = chatActivityEnterView.getFieldText();
} else {
oldMessage = null;
}
} else {
oldMessage = null;
}
if (mentionsAdapter != null) {
mentionsAdapter.onDestroy();
}
chatListView = new RecyclerListView(context, themeDelegate) {
private int lastWidth;
private final ArrayList<ChatMessageCell> drawTimeAfter = new ArrayList<>();
private final ArrayList<ChatMessageCell> drawNamesAfter = new ArrayList<>();
private final ArrayList<ChatMessageCell> drawCaptionAfter = new ArrayList<>();
private final ArrayList<MessageObject.GroupedMessages> drawingGroups = new ArrayList<>(10);
private boolean slideAnimationInProgress;
private int startedTrackingX;
private int startedTrackingY;
private int startedTrackingPointerId;
private long lastTrackingAnimationTime;
private float trackAnimationProgress;
private float endTrackingX;
private boolean wasTrackingVibrate;
private float replyButtonProgress;
private long lastReplyButtonAnimationTime;
private boolean ignoreLayout;
int lastH = 0;
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
@Override
public void setTranslationY(float translationY) {
if (translationY != getTranslationY()) {
super.setTranslationY(translationY);
if (emptyViewContainer != null) {
if (chatActivityEnterView != null && chatActivityEnterView.pannelAniamationInProgress()) {
emptyViewContainer.setTranslationY(translationY / 2f);
} else {
emptyViewContainer.setTranslationY(translationY / 1.7f);
}
}
if (chatActivityEnterView != null && chatActivityEnterView.botCommandsMenuContainer != null) {
chatActivityEnterView.botCommandsMenuContainer.setTranslationY(translationY);
}
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (lastWidth != r - l) {
lastWidth = r - l;
hideHints(false);
}
int height = getMeasuredHeight();
if (lastH != height) {
ignoreLayout = true;
if (chatListItemAnimator != null) {
chatListItemAnimator.endAnimations();
}
chatScrollHelper.cancel();
ignoreLayout = false;
lastH = height;
}
forceScrollToTop = false;
if (textSelectionHelper != null && textSelectionHelper.isSelectionMode()) {
textSelectionHelper.invalidate();
}
}
private void setGroupTranslationX(ChatMessageCell view, float dx) {
MessageObject.GroupedMessages group = view.getCurrentMessagesGroup();
if (group == null) {
return;
}
int count = getChildCount();
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
if (child == view || !(child instanceof ChatMessageCell)) {
continue;
}
ChatMessageCell cell = (ChatMessageCell) child;
if (cell.getCurrentMessagesGroup() == group) {
cell.setSlidingOffset(dx);
cell.invalidate();
}
}
invalidate();
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
if (scrimPopupWindow != null) {
return false;
}
return super.requestChildRectangleOnScreen(child, rect, immediate);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
textSelectionHelper.checkSelectionCancel(e);
if (isFastScrollAnimationRunning()) {
return false;
}
boolean result = super.onInterceptTouchEvent(e);
if (actionBar.isActionModeShowed() || reportType >= 0) {
return result;
}
processTouchEvent(e);
return result;
}
@Override
public void setItemAnimator(ItemAnimator animator) {
if (isFastScrollAnimationRunning()) {
return;
}
super.setItemAnimator(animator);
}
private void drawReplyButton(Canvas canvas) {
if (slidingView == null) {
return;
}
float translationX = slidingView.getNonAnimationTranslationX(false);
long newTime = System.currentTimeMillis();
long dt = Math.min(17, newTime - lastReplyButtonAnimationTime);
lastReplyButtonAnimationTime = newTime;
boolean showing;
if (showing = (translationX <= -AndroidUtilities.dp(50))) {
if (replyButtonProgress < 1.0f) {
replyButtonProgress += dt / 180.0f;
if (replyButtonProgress > 1.0f) {
replyButtonProgress = 1.0f;
} else {
invalidate();
}
}
} else {
if (replyButtonProgress > 0.0f) {
replyButtonProgress -= dt / 180.0f;
if (replyButtonProgress < 0.0f) {
replyButtonProgress = 0;
} else {
invalidate();
}
}
}
int alpha;
int alpha2;
Paint chatActionBackgroundPaint = getThemedPaint(Theme.key_paint_chatActionBackground);
int oldAlpha = chatActionBackgroundPaint.getAlpha();
float scale;
if (showing) {
if (replyButtonProgress <= 0.8f) {
scale = 1.2f * (replyButtonProgress / 0.8f);
} else {
scale = 1.2f - 0.2f * ((replyButtonProgress - 0.8f) / 0.2f);
}
alpha = (int) Math.min(255, 255 * (replyButtonProgress / 0.8f));
alpha2 = (int) Math.min(oldAlpha, oldAlpha * (replyButtonProgress / 0.8f));
} else {
scale = replyButtonProgress;
alpha = (int) Math.min(255, 255 * replyButtonProgress);
alpha2 = (int) Math.min(oldAlpha, oldAlpha * replyButtonProgress);
}
chatActionBackgroundPaint.setAlpha(alpha2);
float x = getMeasuredWidth() + slidingView.getNonAnimationTranslationX(false) / 2;
float y = slidingView.getTop() + slidingView.getMeasuredHeight() / 2;
AndroidUtilities.rectTmp.set((int) (x - AndroidUtilities.dp(16) * scale), (int) (y - AndroidUtilities.dp(16) * scale), (int) (x + AndroidUtilities.dp(16) * scale), (int) (y + AndroidUtilities.dp(16) * scale));
Theme.applyServiceShaderMatrix(getMeasuredWidth(), AndroidUtilities.displaySize.y, 0, getY() + AndroidUtilities.rectTmp.top);
canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), chatActionBackgroundPaint);
if (themeDelegate.hasGradientService()) {
canvas.drawRoundRect(AndroidUtilities.rectTmp, AndroidUtilities.dp(16), AndroidUtilities.dp(16), Theme.chat_actionBackgroundGradientDarkenPaint);
}
chatActionBackgroundPaint.setAlpha(oldAlpha);
Drawable replyIconDrawable = getThemedDrawable(Theme.key_drawable_replyIcon);
replyIconDrawable.setAlpha(alpha);
replyIconDrawable.setBounds((int) (x - AndroidUtilities.dp(7) * scale), (int) (y - AndroidUtilities.dp(6) * scale), (int) (x + AndroidUtilities.dp(7) * scale), (int) (y + AndroidUtilities.dp(5) * scale));
replyIconDrawable.draw(canvas);
replyIconDrawable.setAlpha(255);
}
private void processTouchEvent(MotionEvent e) {
if (e != null) {
wasManualScroll = true;
}
if (e != null && e.getAction() == MotionEvent.ACTION_DOWN && !startedTrackingSlidingView && !maybeStartTrackingSlidingView && slidingView == null && !inPreviewMode) {
View view = getPressedChildView();
if (view instanceof ChatMessageCell) {
if (slidingView != null) {
slidingView.setSlidingOffset(0);
}
slidingView = (ChatMessageCell) view;
MessageObject message = slidingView.getMessageObject();
if (chatMode != 0 || threadMessageObjects != null && threadMessageObjects.contains(message) || getMessageType(message) == 1 && (message.getDialogId() == mergeDialogId || message.needDrawBluredPreview()) || currentEncryptedChat == null && message.getId() < 0 || bottomOverlayChat != null && bottomOverlayChat.getVisibility() == View.VISIBLE || currentChat != null && (ChatObject.isNotInChat(currentChat) && !isThreadChat() || ChatObject.isChannel(currentChat) && !ChatObject.canPost(currentChat) && !currentChat.megagroup || !ChatObject.canSendMessages(currentChat)) || textSelectionHelper.isSelectionMode()) {
slidingView.setSlidingOffset(0);
slidingView = null;
return;
}
startedTrackingPointerId = e.getPointerId(0);
maybeStartTrackingSlidingView = true;
startedTrackingX = (int) e.getX();
startedTrackingY = (int) e.getY();
}
} else if (slidingView != null && e != null && e.getAction() == MotionEvent.ACTION_MOVE && e.getPointerId(0) == startedTrackingPointerId) {
int dx = Math.max(AndroidUtilities.dp(-80), Math.min(0, (int) (e.getX() - startedTrackingX)));
int dy = Math.abs((int) e.getY() - startedTrackingY);
if (getScrollState() == SCROLL_STATE_IDLE && maybeStartTrackingSlidingView && !startedTrackingSlidingView && dx <= -AndroidUtilities.getPixelsInCM(0.4f, true) && Math.abs(dx) / 3 > dy) {
MotionEvent event = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
slidingView.onTouchEvent(event);
super.onInterceptTouchEvent(event);
event.recycle();
chatLayoutManager.setCanScrollVertically(false);
maybeStartTrackingSlidingView = false;
startedTrackingSlidingView = true;
startedTrackingX = (int) e.getX();
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
} else if (startedTrackingSlidingView) {
if (Math.abs(dx) >= AndroidUtilities.dp(50)) {
if (!wasTrackingVibrate) {
try {
performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
} catch (Exception ignore) {
}
wasTrackingVibrate = true;
}
} else {
wasTrackingVibrate = false;
}
slidingView.setSlidingOffset(dx);
MessageObject messageObject = slidingView.getMessageObject();
if (messageObject.isRoundVideo() || messageObject.isVideo()) {
updateTextureViewPosition(false);
}
setGroupTranslationX(slidingView, dx);
invalidate();
}
} else if (slidingView != null && (e == null || e.getPointerId(0) == startedTrackingPointerId && (e.getAction() == MotionEvent.ACTION_CANCEL || e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_POINTER_UP))) {
if (e != null && e.getAction() != MotionEvent.ACTION_CANCEL && Math.abs(slidingView.getNonAnimationTranslationX(false)) >= AndroidUtilities.dp(50)) {
showFieldPanelForReply(slidingView.getMessageObject());
}
endTrackingX = slidingView.getSlidingOffsetX();
if (endTrackingX == 0) {
slidingView = null;
}
lastTrackingAnimationTime = System.currentTimeMillis();
trackAnimationProgress = 0.0f;
invalidate();
maybeStartTrackingSlidingView = false;
startedTrackingSlidingView = false;
chatLayoutManager.setCanScrollVertically(true);
}
}
@Override
public boolean onTouchEvent(MotionEvent e) {
textSelectionHelper.checkSelectionCancel(e);
if (e.getAction() == MotionEvent.ACTION_DOWN) {
scrollByTouch = true;
}
if (pullingDownOffset != 0 && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
float progress = Math.min(1f, pullingDownOffset / AndroidUtilities.dp(110));
if (e.getAction() == MotionEvent.ACTION_UP && progress == 1 && pullingDownDrawable != null && !pullingDownDrawable.emptyStub) {
if (pullingDownDrawable.animationIsRunning()) {
ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, pullingDownOffset + AndroidUtilities.dp(8));
pullingDownBackAnimator = animator;
animator.addUpdateListener(valueAnimator -> {
pullingDownOffset = (float) valueAnimator.getAnimatedValue();
chatListView.invalidate();
});
animator.setDuration(200);
animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
animator.start();
pullingDownDrawable.runOnAnimationFinish(() -> {
animateToNextChat();
});
} else {
animateToNextChat();
}
} else {
if (pullingDownDrawable != null && pullingDownDrawable.emptyStub && (System.currentTimeMillis() - pullingDownDrawable.lastShowingReleaseTime) < 500 && pullingDownDrawable.animateSwipeToRelease) {
AnimatorSet animatorSet = new AnimatorSet();
pullingDownBackAnimator = animatorSet;
if (pullingDownDrawable != null) {
pullingDownDrawable.showBottomPanel(false);
}
ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, AndroidUtilities.dp(111));
animator.addUpdateListener(valueAnimator -> {
pullingDownOffset = (float) valueAnimator.getAnimatedValue();
chatListView.invalidate();
});
animator.setDuration(400);
animator.setInterpolator(CubicBezierInterpolator.DEFAULT);
ValueAnimator animator2 = ValueAnimator.ofFloat(AndroidUtilities.dp(111), 0);
animator2.addUpdateListener(valueAnimator -> {
pullingDownOffset = (float) valueAnimator.getAnimatedValue();
chatListView.invalidate();
});
animator2.setStartDelay(600);
animator2.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
animator2.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
animatorSet.playSequentially(animator, animator2);
animatorSet.start();
} else {
ValueAnimator animator = ValueAnimator.ofFloat(pullingDownOffset, 0);
pullingDownBackAnimator = animator;
if (pullingDownDrawable != null) {
pullingDownDrawable.showBottomPanel(false);
}
animator.addUpdateListener(valueAnimator -> {
pullingDownOffset = (float) valueAnimator.getAnimatedValue();
chatListView.invalidate();
});
animator.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
animator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
animator.start();
}
}
}
if (isFastScrollAnimationRunning()) {
return false;
}
boolean result = super.onTouchEvent(e);
if (actionBar.isActionModeShowed() || reportType >= 0) {
return result;
}
processTouchEvent(e);
return startedTrackingSlidingView || result;
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
super.requestDisallowInterceptTouchEvent(disallowIntercept);
if (slidingView != null) {
processTouchEvent(null);
}
}
@Override
protected void onChildPressed(View child, float x, float y, boolean pressed) {
super.onChildPressed(child, x, y, pressed);
if (child instanceof ChatMessageCell) {
ChatMessageCell chatMessageCell = (ChatMessageCell) child;
MessageObject object = chatMessageCell.getMessageObject();
if (object.isMusic() || object.isDocument()) {
return;
}
MessageObject.GroupedMessages groupedMessages = chatMessageCell.getCurrentMessagesGroup();
if (groupedMessages != null) {
int count = getChildCount();
for (int a = 0; a < count; a++) {
View item = getChildAt(a);
if (item == child || !(item instanceof ChatMessageCell)) {
continue;
}
ChatMessageCell cell = (ChatMessageCell) item;
if (cell.getCurrentMessagesGroup() == groupedMessages) {
cell.setPressed(pressed);
}
}
}
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
if (slidingView != null) {
float translationX = slidingView.getSlidingOffsetX();
if (!maybeStartTrackingSlidingView && !startedTrackingSlidingView && endTrackingX != 0 && translationX != 0) {
long newTime = System.currentTimeMillis();
long dt = newTime - lastTrackingAnimationTime;
trackAnimationProgress += dt / 180.0f;
if (trackAnimationProgress > 1.0f) {
trackAnimationProgress = 1.0f;
}
lastTrackingAnimationTime = newTime;
translationX = endTrackingX * (1.0f - AndroidUtilities.decelerateInterpolator.getInterpolation(trackAnimationProgress));
if (translationX == 0) {
endTrackingX = 0;
}
setGroupTranslationX(slidingView, translationX);
slidingView.setSlidingOffset(translationX);
MessageObject messageObject = slidingView.getMessageObject();
if (messageObject.isRoundVideo() || messageObject.isVideo()) {
updateTextureViewPosition(false);
}
if (trackAnimationProgress == 1f || trackAnimationProgress == 0f) {
slidingView.setSlidingOffset(0);
slidingView = null;
}
invalidate();
}
drawReplyButton(c);
}
if (pullingDownOffset != 0) {
c.save();
float transitionOffset = 0;
if (pullingDownAnimateProgress != 0) {
transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
}
c.translate(0, getMeasuredHeight() - blurredViewBottomOffset - transitionOffset);
if (pullingDownDrawable == null) {
pullingDownDrawable = new ChatPullingDownDrawable(currentAccount, fragmentView, dialog_id, dialogFolderId, dialogFilterId, themeDelegate);
pullingDownDrawable.onAttach();
}
pullingDownDrawable.setWidth(getMeasuredWidth());
float progress = Math.min(1f, pullingDownOffset / AndroidUtilities.dp(110));
pullingDownDrawable.draw(c, chatListView, progress, 1f - pullingDownAnimateProgress);
c.restore();
if (pullingDownAnimateToActivity != null) {
c.saveLayerAlpha(0, 0, pullingDownAnimateToActivity.chatListView.getMeasuredWidth(), pullingDownAnimateToActivity.chatListView.getMeasuredHeight(), (int) (255 * pullingDownAnimateProgress), Canvas.ALL_SAVE_FLAG);
c.translate(0, getMeasuredHeight() - pullingDownOffset - transitionOffset);
pullingDownAnimateToActivity.chatListView.draw(c);
c.restore();
}
} else if (pullingDownDrawable != null) {
pullingDownDrawable.reset();
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
drawLaterRoundProgressCell = null;
canvas.save();
canvas.clipRect(0, chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4), getMeasuredWidth(), getMeasuredHeight() - blurredViewBottomOffset);
selectorRect.setEmpty();
if (pullingDownOffset != 0) {
canvas.save();
float transitionOffset = 0;
if (pullingDownAnimateProgress != 0) {
transitionOffset = (chatListView.getMeasuredHeight() - pullingDownOffset) * pullingDownAnimateProgress;
}
canvas.translate(0, drawingChatLisViewYoffset = -pullingDownOffset - transitionOffset);
drawChatBackgroundElements(canvas);
super.dispatchDraw(canvas);
canvas.restore();
} else {
drawChatBackgroundElements(canvas);
super.dispatchDraw(canvas);
}
canvas.restore();
}
private void drawChatBackgroundElements(Canvas canvas) {
int count = getChildCount();
MessageObject.GroupedMessages lastDrawnGroup = null;
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
if (chatAdapter.isBot && child instanceof BotHelpCell) {
BotHelpCell botCell = (BotHelpCell) child;
float top = getMeasuredHeight() / 2 - child.getMeasuredHeight() / 2 + chatListViewPaddingTop;
if (!botCell.animating() && !chatListView.fastScrollAnimationRunning) {
if (child.getTop() > top) {
child.setTranslationY(top - child.getTop());
} else {
child.setTranslationY(0);
}
}
break;
} else if (child instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) child;
MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
if (group == null || group != lastDrawnGroup) {
lastDrawnGroup = group;
MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
MessageBackgroundDrawable backgroundDrawable = cell.getBackgroundDrawable();
if ((backgroundDrawable.isAnimationInProgress() || cell.isDrawingSelectionBackground()) && (position == null || (position.flags & MessageObject.POSITION_FLAG_RIGHT) != 0)) {
if (cell.isHighlighted() || cell.isHighlightedAnimated()) {
if (position == null) {
Paint backgroundPaint = getThemedPaint(Theme.key_paint_chatMessageBackgroundSelected);
if (themeDelegate.isDark || backgroundPaint == null) {
backgroundPaint = Theme.chat_replyLinePaint;
backgroundPaint.setColor(getThemedColor(Theme.key_chat_selectedBackground));
}
canvas.save();
canvas.translate(0, cell.getTranslationY());
int wasAlpha = backgroundPaint.getAlpha();
backgroundPaint.setAlpha((int) (wasAlpha * cell.getHightlightAlpha() * cell.getAlpha()));
if (themeDelegate != null) {
themeDelegate.applyServiceShaderMatrix(getMeasuredWidth(), cell.getHeight(), 0, cell.getTop());
} else {
Theme.applyServiceShaderMatrix(getMeasuredWidth(), cell.getHeight(), 0, cell.getTop());
}
canvas.drawRect(0, cell.getTop(), getMeasuredWidth(), cell.getBottom(), backgroundPaint);
backgroundPaint.setAlpha(wasAlpha);
canvas.restore();
}
} else {
int y = (int) cell.getY();
int height;
canvas.save();
if (position == null) {
height = cell.getMeasuredHeight();
} else {
height = y + cell.getMeasuredHeight();
long time = 0;
float touchX = 0;
float touchY = 0;
for (int i = 0; i < count; i++) {
View inner = getChildAt(i);
if (inner instanceof ChatMessageCell) {
ChatMessageCell innerCell = (ChatMessageCell) inner;
MessageObject.GroupedMessages innerGroup = innerCell.getCurrentMessagesGroup();
if (innerGroup == group) {
MessageBackgroundDrawable drawable = innerCell.getBackgroundDrawable();
y = Math.min(y, (int) innerCell.getY());
height = Math.max(height, (int) innerCell.getY() + innerCell.getMeasuredHeight());
long touchTime = drawable.getLastTouchTime();
if (touchTime > time) {
touchX = drawable.getTouchX() + innerCell.getX();
touchY = drawable.getTouchY() + innerCell.getY();
time = touchTime;
}
}
}
}
backgroundDrawable.setTouchCoordsOverride(touchX, touchY - y);
height -= y;
}
canvas.clipRect(0, y, getMeasuredWidth(), y + height);
Paint selectedBackgroundPaint = getThemedPaint(Theme.key_paint_chatMessageBackgroundSelected);
if (!themeDelegate.isDark && selectedBackgroundPaint != null) {
backgroundDrawable.setCustomPaint(selectedBackgroundPaint);
if (themeDelegate != null) {
themeDelegate.applyServiceShaderMatrix(getMeasuredWidth(), height, 0, 0);
} else {
Theme.applyServiceShaderMatrix(getMeasuredWidth(), height, 0, 0);
}
} else {
backgroundDrawable.setCustomPaint(null);
backgroundDrawable.setColor(getThemedColor(Theme.key_chat_selectedBackground));
}
backgroundDrawable.setBounds(0, y, getMeasuredWidth(), y + height);
backgroundDrawable.draw(canvas);
canvas.restore();
}
}
}
if (scrimView != cell && group == null && cell.drawBackgroundInParent()) {
canvas.save();
canvas.translate(cell.getX(), cell.getY());
if (cell.getScaleX() != 1f) {
canvas.scale(cell.getScaleX(), cell.getScaleY(), cell.getPivotX(), (cell.getHeight() >> 1));
}
cell.drawBackgroundInternal(canvas, true);
canvas.restore();
}
} else if (child instanceof ChatActionCell) {
ChatActionCell cell = (ChatActionCell) child;
if (cell.hasGradientService()) {
canvas.save();
canvas.translate(cell.getX(), cell.getY());
canvas.scale(cell.getScaleX(), cell.getScaleY(), cell.getMeasuredWidth() / 2f, cell.getMeasuredHeight() / 2f);
cell.drawBackground(canvas, true);
canvas.restore();
}
}
}
MessageObject.GroupedMessages scrimGroup = null;
if (scrimView instanceof ChatMessageCell) {
scrimGroup = ((ChatMessageCell) scrimView).getCurrentMessagesGroup();
}
for (int k = 0; k < 3; k++) {
drawingGroups.clear();
if (k == 2 && !chatListView.isFastScrollAnimationRunning()) {
continue;
}
for (int i = 0; i < count; i++) {
View child = chatListView.getChildAt(i);
if (child instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) child;
if (child.getY() > chatListView.getHeight() || child.getY() + child.getHeight() < 0) {
continue;
}
MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
if (group == null || (k == 0 && group.messages.size() == 1) || (k == 1 && !group.transitionParams.drawBackgroundForDeletedItems)) {
continue;
}
if ((k == 0 && cell.getMessageObject().deleted) || (k == 1 && !cell.getMessageObject().deleted)) {
continue;
}
if ((k == 2 && !cell.willRemovedAfterAnimation()) || (k != 2 && cell.willRemovedAfterAnimation())) {
continue;
}
if (!drawingGroups.contains(group)) {
group.transitionParams.left = 0;
group.transitionParams.top = 0;
group.transitionParams.right = 0;
group.transitionParams.bottom = 0;
group.transitionParams.pinnedBotton = false;
group.transitionParams.pinnedTop = false;
group.transitionParams.cell = cell;
drawingGroups.add(group);
}
group.transitionParams.pinnedTop = cell.isPinnedTop();
group.transitionParams.pinnedBotton = cell.isPinnedBottom();
int left = (cell.getLeft() + cell.getBackgroundDrawableLeft());
int right = (cell.getLeft() + cell.getBackgroundDrawableRight());
int top = (cell.getTop() + cell.getBackgroundDrawableTop());
int bottom = (cell.getTop() + cell.getBackgroundDrawableBottom());
if ((cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_TOP) == 0) {
top -= AndroidUtilities.dp(10);
}
if ((cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
bottom += AndroidUtilities.dp(10);
}
if (cell.willRemovedAfterAnimation()) {
group.transitionParams.cell = cell;
}
if (group.transitionParams.top == 0 || top < group.transitionParams.top) {
group.transitionParams.top = top;
}
if (group.transitionParams.bottom == 0 || bottom > group.transitionParams.bottom) {
group.transitionParams.bottom = bottom;
}
if (group.transitionParams.left == 0 || left < group.transitionParams.left) {
group.transitionParams.left = left;
}
if (group.transitionParams.right == 0 || right > group.transitionParams.right) {
group.transitionParams.right = right;
}
}
}
for (int i = 0; i < drawingGroups.size(); i++) {
MessageObject.GroupedMessages group = drawingGroups.get(i);
if (group == scrimGroup) {
continue;
}
float x = group.transitionParams.cell.getNonAnimationTranslationX(true);
float l = (group.transitionParams.left + x + group.transitionParams.offsetLeft);
float t = (group.transitionParams.top + group.transitionParams.offsetTop);
float r = (group.transitionParams.right + x + group.transitionParams.offsetRight);
float b = (group.transitionParams.bottom + group.transitionParams.offsetBottom);
if (!group.transitionParams.backgroundChangeBounds) {
t += group.transitionParams.cell.getTranslationY();
b += group.transitionParams.cell.getTranslationY();
}
if (t < chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20)) {
t = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(20);
}
if (b > chatListView.getMeasuredHeight() + AndroidUtilities.dp(20)) {
b = chatListView.getMeasuredHeight() + AndroidUtilities.dp(20);
}
boolean useScale = group.transitionParams.cell.getScaleX() != 1f || group.transitionParams.cell.getScaleY() != 1f;
if (useScale) {
canvas.save();
canvas.scale(group.transitionParams.cell.getScaleX(), group.transitionParams.cell.getScaleY(), l + (r - l) / 2, t + (b - t) / 2);
}
boolean selected = true;
for (int a = 0, N = group.messages.size(); a < N; a++) {
MessageObject object = group.messages.get(a);
int index = object.getDialogId() == dialog_id ? 0 : 1;
if (selectedMessagesIds[index].indexOfKey(object.getId()) < 0) {
selected = false;
break;
}
}
group.transitionParams.cell.drawBackground(canvas, (int) l, (int) t, (int) r, (int) b, group.transitionParams.pinnedTop, group.transitionParams.pinnedBotton, selected, contentView.getKeyboardHeight());
group.transitionParams.cell = null;
group.transitionParams.drawCaptionLayout = group.hasCaption;
if (useScale) {
canvas.restore();
for (int ii = 0; ii < count; ii++) {
View child = chatListView.getChildAt(ii);
if (child instanceof ChatMessageCell && ((ChatMessageCell) child).getCurrentMessagesGroup() == group) {
ChatMessageCell cell = ((ChatMessageCell) child);
int left = cell.getLeft();
int top = cell.getTop();
child.setPivotX(l - left + (r - l) / 2);
child.setPivotY(t - top + (b - t) / 2);
}
}
}
}
}
}
@Override
public boolean drawChild(Canvas canvas, View child, long drawingTime) {
int clipLeft = 0;
int clipBottom = 0;
boolean skipDraw = child == scrimView;
ChatMessageCell cell;
float cilpTop = chatListViewPaddingTop - chatListViewPaddingVisibleOffset - AndroidUtilities.dp(4);
if (child.getY() > getMeasuredHeight() || child.getY() + child.getMeasuredHeight() < cilpTop) {
skipDraw = true;
}
MessageObject.GroupedMessages group = null;
if (child instanceof ChatMessageCell) {
cell = (ChatMessageCell) child;
if (animateSendingViews.contains(cell)) {
skipDraw = true;
}
MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
group = cell.getCurrentMessagesGroup();
if (position != null) {
if (position.pw != position.spanSize && position.spanSize == 1000 && position.siblingHeights == null && group.hasSibling) {
clipLeft = cell.getBackgroundDrawableLeft();
} else if (position.siblingHeights != null) {
clipBottom = child.getBottom() - AndroidUtilities.dp(1 + (cell.isPinnedBottom() ? 1 : 0));
}
}
if (cell.needDelayRoundProgressDraw()) {
drawLaterRoundProgressCell = cell;
}
if (!skipDraw && scrimView instanceof ChatMessageCell) {
ChatMessageCell cell2 = (ChatMessageCell) scrimView;
if (cell2.getCurrentMessagesGroup() != null && cell2.getCurrentMessagesGroup() == group) {
skipDraw = true;
}
}
if (skipDraw) {
cell.getPhotoImage().skipDraw();
}
} else {
cell = null;
}
if (clipLeft != 0) {
canvas.save();
} else if (clipBottom != 0) {
canvas.save();
}
boolean result;
if (!skipDraw) {
boolean clipToGroupBounds = group != null && group.transitionParams.backgroundChangeBounds;
if (clipToGroupBounds) {
canvas.save();
float x = cell.getNonAnimationTranslationX(true);
float l = (group.transitionParams.left + x + group.transitionParams.offsetLeft);
float t = (group.transitionParams.top + group.transitionParams.offsetTop);
float r = (group.transitionParams.right + x + group.transitionParams.offsetRight);
float b = (group.transitionParams.bottom + group.transitionParams.offsetBottom);
canvas.clipRect(l + AndroidUtilities.dp(4), t + AndroidUtilities.dp(4), r - AndroidUtilities.dp(4), b - AndroidUtilities.dp(4));
}
if (cell != null && clipToGroupBounds) {
cell.clipToGroupBounds = true;
result = super.drawChild(canvas, child, drawingTime);
cell.clipToGroupBounds = false;
} else {
result = super.drawChild(canvas, child, drawingTime);
}
if (clipToGroupBounds) {
canvas.restore();
}
if (cell != null && cell.hasOutboundsContent()) {
canvas.save();
canvas.translate(cell.getX(), cell.getY());
cell.drawOutboundsContent(canvas);
canvas.restore();
}
} else {
result = false;
}
if (clipLeft != 0 || clipBottom != 0) {
canvas.restore();
}
if (child.getTranslationY() != 0) {
canvas.save();
canvas.translate(0, child.getTranslationY());
}
if (cell != null) {
cell.drawCheckBox(canvas);
}
if (child.getTranslationY() != 0) {
canvas.restore();
}
int num = 0;
int count = getChildCount();
for (int a = 0; a < count; a++) {
if (getChildAt(a) == child) {
num = a;
break;
}
}
if (num == count - 1) {
int size = drawTimeAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
cell = drawTimeAfter.get(a);
canvas.save();
canvas.translate(cell.getLeft() + cell.getNonAnimationTranslationX(false), cell.getY());
cell.drawTime(canvas, cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f, true);
canvas.restore();
}
drawTimeAfter.clear();
}
size = drawNamesAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
cell = drawNamesAfter.get(a);
float canvasOffsetX = cell.getLeft() + cell.getNonAnimationTranslationX(false);
float canvasOffsetY = cell.getY();
float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
canvas.save();
canvas.translate(canvasOffsetX, canvasOffsetY);
cell.setInvalidatesParent(true);
cell.drawNamesLayout(canvas, alpha);
cell.setInvalidatesParent(false);
canvas.restore();
}
drawNamesAfter.clear();
}
size = drawCaptionAfter.size();
if (size > 0) {
for (int a = 0; a < size; a++) {
cell = drawCaptionAfter.get(a);
boolean selectionOnly = false;
if (cell.getCurrentPosition() != null) {
selectionOnly = (cell.getCurrentPosition().flags & MessageObject.POSITION_FLAG_LEFT) == 0;
}
float alpha = cell.shouldDrawAlphaLayer() ? cell.getAlpha() : 1f;
float canvasOffsetX = cell.getLeft() + cell.getNonAnimationTranslationX(false);
float canvasOffsetY = cell.getY();
canvas.save();
MessageObject.GroupedMessages groupedMessages = cell.getCurrentMessagesGroup();
if (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds) {
float x = cell.getNonAnimationTranslationX(true);
float l = (groupedMessages.transitionParams.left + x + groupedMessages.transitionParams.offsetLeft);
float t = (groupedMessages.transitionParams.top + groupedMessages.transitionParams.offsetTop);
float r = (groupedMessages.transitionParams.right + x + groupedMessages.transitionParams.offsetRight);
float b = (groupedMessages.transitionParams.bottom + groupedMessages.transitionParams.offsetBottom);
if (!groupedMessages.transitionParams.backgroundChangeBounds) {
t += cell.getTranslationY();
b += cell.getTranslationY();
}
canvas.clipRect(l + AndroidUtilities.dp(8), t + AndroidUtilities.dp(8), r - AndroidUtilities.dp(8), b - AndroidUtilities.dp(8));
}
canvas.translate(canvasOffsetX, canvasOffsetY);
cell.setInvalidatesParent(true);
cell.drawCaptionLayout(canvas, selectionOnly, alpha);
cell.setInvalidatesParent(false);
canvas.restore();
}
drawCaptionAfter.clear();
}
}
if (child.getTranslationY() != 0) {
canvas.save();
canvas.translate(0, child.getTranslationY());
}
if (child instanceof ChatMessageCell) {
ChatMessageCell chatMessageCell = (ChatMessageCell) child;
MessageObject.GroupedMessagePosition position = chatMessageCell.getCurrentPosition();
if (position != null || chatMessageCell.getTransitionParams().animateBackgroundBoundsInner) {
if (position == null || (position.last || position.minX == 0 && position.minY == 0)) {
if (num == count - 1) {
float alpha = chatMessageCell.shouldDrawAlphaLayer() ? chatMessageCell.getAlpha() : 1f;
float canvasOffsetX = chatMessageCell.getLeft() + chatMessageCell.getNonAnimationTranslationX(false);
float canvasOffsetY = chatMessageCell.getTop();
canvas.save();
canvas.translate(canvasOffsetX, canvasOffsetY);
cell.setInvalidatesParent(true);
if (position == null || position.last) {
chatMessageCell.drawTime(canvas, alpha, true);
}
if (position == null || (position.minX == 0 && position.minY == 0)) {
chatMessageCell.drawNamesLayout(canvas, alpha);
}
cell.setInvalidatesParent(false);
canvas.restore();
} else {
if (position == null || position.last) {
drawTimeAfter.add(chatMessageCell);
}
if ((position == null || (position.minX == 0 && position.minY == 0)) && chatMessageCell.hasNameLayout()) {
drawNamesAfter.add(chatMessageCell);
}
}
}
if (position != null || chatMessageCell.getTransitionParams().transformGroupToSingleMessage || chatMessageCell.getTransitionParams().animateBackgroundBoundsInner) {
if (num == count - 1) {
float alpha = chatMessageCell.shouldDrawAlphaLayer() ? chatMessageCell.getAlpha() : 1f;
float canvasOffsetX = chatMessageCell.getLeft() + chatMessageCell.getNonAnimationTranslationX(false);
float canvasOffsetY = chatMessageCell.getTop();
canvas.save();
MessageObject.GroupedMessages groupedMessages = chatMessageCell.getCurrentMessagesGroup();
if (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds) {
float x = chatMessageCell.getNonAnimationTranslationX(true);
float l = (groupedMessages.transitionParams.left + x + groupedMessages.transitionParams.offsetLeft);
float t = (groupedMessages.transitionParams.top + groupedMessages.transitionParams.offsetTop);
float r = (groupedMessages.transitionParams.right + x + groupedMessages.transitionParams.offsetRight);
float b = (groupedMessages.transitionParams.bottom + groupedMessages.transitionParams.offsetBottom);
if (groupedMessages.transitionParams.backgroundChangeBounds) {
t -= chatMessageCell.getTranslationY();
b -= chatMessageCell.getTranslationY();
}
canvas.clipRect(l + AndroidUtilities.dp(8), t + AndroidUtilities.dp(8), r - AndroidUtilities.dp(8), b - AndroidUtilities.dp(8));
}
canvas.translate(canvasOffsetX, canvasOffsetY);
if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
boolean selectionOnly = position != null && (position.flags & MessageObject.POSITION_FLAG_LEFT) == 0;
chatMessageCell.setInvalidatesParent(true);
chatMessageCell.drawCaptionLayout(canvas, selectionOnly, alpha);
chatMessageCell.setInvalidatesParent(false);
}
canvas.restore();
} else {
if (position == null || (position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
drawCaptionAfter.add(chatMessageCell);
}
}
}
}
MessageObject message = chatMessageCell.getMessageObject();
if (videoPlayerContainer != null && (message.isRoundVideo() || message.isVideo()) && MediaController.getInstance().isPlayingMessage(message)) {
ImageReceiver imageReceiver = chatMessageCell.getPhotoImage();
float newX = imageReceiver.getImageX() + chatMessageCell.getX();
float newY = chatMessageCell.getY() + imageReceiver.getImageY() + chatListView.getY() - videoPlayerContainer.getTop();
if (videoPlayerContainer.getTranslationX() != newX || videoPlayerContainer.getTranslationY() != newY) {
videoPlayerContainer.setTranslationX(newX);
videoPlayerContainer.setTranslationY(newY);
fragmentView.invalidate();
videoPlayerContainer.invalidate();
}
}
ImageReceiver imageReceiver = chatMessageCell.getAvatarImage();
if (imageReceiver != null) {
MessageObject.GroupedMessages groupedMessages = getValidGroupedMessage(message);
if (chatMessageCell.getMessageObject().deleted) {
if (child.getTranslationY() != 0) {
canvas.restore();
}
imageReceiver.setVisible(false, false);
return result;
}
boolean replaceAnimation = chatListView.isFastScrollAnimationRunning() || (groupedMessages != null && groupedMessages.transitionParams.backgroundChangeBounds);
int top = replaceAnimation ? child.getTop() : (int) child.getY();
if (chatMessageCell.drawPinnedBottom()) {
int p;
if (chatMessageCell.willRemovedAfterAnimation()) {
p = chatScrollHelper.positionToOldView.indexOfValue(child);
if (p >= 0) {
p = chatScrollHelper.positionToOldView.keyAt(p);
}
} else {
ViewHolder holder = chatListView.getChildViewHolder(child);
p = holder.getAdapterPosition();
}
if (p >= 0) {
int nextPosition;
if (groupedMessages != null && position != null) {
int idx = groupedMessages.posArray.indexOf(position);
int size = groupedMessages.posArray.size();
if ((position.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
nextPosition = p - size + idx;
} else {
nextPosition = p - 1;
for (int a = idx + 1; a < size; a++) {
if (groupedMessages.posArray.get(a).minY > position.maxY) {
break;
} else {
nextPosition--;
}
}
}
} else {
nextPosition = p - 1;
}
if (chatMessageCell.willRemovedAfterAnimation()) {
View view = chatScrollHelper.positionToOldView.get(nextPosition);
if (view != null) {
if (child.getTranslationY() != 0) {
canvas.restore();
}
imageReceiver.setVisible(false, false);
return result;
}
} else {
ViewHolder holder = chatListView.findViewHolderForAdapterPosition(nextPosition);
if (holder != null) {
if (child.getTranslationY() != 0) {
canvas.restore();
}
imageReceiver.setVisible(false, false);
return result;
}
}
}
}
float tx = chatMessageCell.getSlidingOffsetX() + chatMessageCell.getCheckBoxTranslation();
int y = (int) ((replaceAnimation ? child.getTop() : child.getY()) + chatMessageCell.getLayoutHeight() + chatMessageCell.getTransitionParams().deltaBottom);
int maxY = chatListView.getMeasuredHeight() - chatListView.getPaddingBottom();
if (chatMessageCell.isPlayingRound() || chatMessageCell.getTransitionParams().animatePlayingRound) {
if (chatMessageCell.getTransitionParams().animatePlayingRound) {
float progressLocal = chatMessageCell.getTransitionParams().animateChangeProgress;
if (!chatMessageCell.isPlayingRound()) {
progressLocal = 1f - progressLocal;
}
int fromY = y;
int toY = Math.min(y, maxY);
y = (int) (fromY * progressLocal + toY * (1f - progressLocal));
}
} else {
if (y > maxY) {
y = maxY;
}
}
if (!replaceAnimation && child.getTranslationY() != 0) {
canvas.restore();
}
if (chatMessageCell.drawPinnedTop()) {
int p;
if (chatMessageCell.willRemovedAfterAnimation()) {
p = chatScrollHelper.positionToOldView.indexOfValue(child);
if (p >= 0) {
p = chatScrollHelper.positionToOldView.keyAt(p);
}
} else {
ViewHolder holder = chatListView.getChildViewHolder(child);
p = holder.getAdapterPosition();
}
if (p >= 0) {
int tries = 0;
while (true) {
if (tries >= 20) {
break;
}
tries++;
int prevPosition;
if (groupedMessages != null && position != null) {
int idx = groupedMessages.posArray.indexOf(position);
if (idx < 0) {
break;
}
int size = groupedMessages.posArray.size();
if ((position.flags & MessageObject.POSITION_FLAG_TOP) != 0) {
prevPosition = p + idx + 1;
} else {
prevPosition = p + 1;
for (int a = idx - 1; a >= 0; a--) {
if (groupedMessages.posArray.get(a).maxY < position.minY) {
break;
} else {
prevPosition++;
}
}
}
} else {
prevPosition = p + 1;
}
if (chatMessageCell.willRemovedAfterAnimation()) {
View view = chatScrollHelper.positionToOldView.get(prevPosition);
if (view != null) {
top = view.getTop();
if (view instanceof ChatMessageCell) {
cell = (ChatMessageCell) view;
if (!cell.drawPinnedTop()) {
break;
} else {
p = prevPosition;
}
} else {
break;
}
} else {
break;
}
} else {
ViewHolder holder = chatListView.findViewHolderForAdapterPosition(prevPosition);
if (holder != null) {
top = holder.itemView.getTop();
if (holder.itemView instanceof ChatMessageCell) {
cell = (ChatMessageCell) holder.itemView;
if (!cell.drawPinnedTop()) {
break;
} else {
p = prevPosition;
}
} else {
break;
}
} else {
break;
}
}
}
}
}
if (y - AndroidUtilities.dp(48) < top) {
y = top + AndroidUtilities.dp(48);
}
if (!chatMessageCell.drawPinnedBottom()) {
int cellBottom = replaceAnimation ? chatMessageCell.getBottom() : (int) (chatMessageCell.getY() + chatMessageCell.getMeasuredHeight() + chatMessageCell.getTransitionParams().deltaBottom);
if (y > cellBottom) {
y = cellBottom;
}
}
canvas.save();
if (tx != 0) {
canvas.translate(tx, 0);
}
if (chatMessageCell.getCurrentMessagesGroup() != null) {
if (chatMessageCell.getCurrentMessagesGroup().transitionParams.backgroundChangeBounds) {
y -= chatMessageCell.getTranslationY();
}
}
imageReceiver.setImageY(y - AndroidUtilities.dp(44));
if (cell.shouldDrawAlphaLayer()) {
imageReceiver.setAlpha(cell.getAlpha());
canvas.scale(chatMessageCell.getScaleX(), chatMessageCell.getScaleY(), chatMessageCell.getX() + chatMessageCell.getPivotX(), chatMessageCell.getY() + (chatMessageCell.getHeight() >> 1));
} else {
imageReceiver.setAlpha(1f);
}
imageReceiver.setVisible(true, false);
imageReceiver.draw(canvas);
canvas.restore();
if (!replaceAnimation && child.getTranslationY() != 0) {
canvas.save();
}
}
}
if (child.getTranslationY() != 0) {
canvas.restore();
}
return result;
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
if (currentEncryptedChat != null) {
return;
}
super.onInitializeAccessibilityNodeInfo(info);
if (Build.VERSION.SDK_INT >= 19) {
AccessibilityNodeInfo.CollectionInfo collection = info.getCollectionInfo();
if (collection != null) {
info.setCollectionInfo(AccessibilityNodeInfo.CollectionInfo.obtain(collection.getRowCount(), 1, false));
}
}
}
@Override
public AccessibilityNodeInfo createAccessibilityNodeInfo() {
if (currentEncryptedChat != null) {
return null;
}
return super.createAccessibilityNodeInfo();
}
@Override
public void invalidate() {
super.invalidate();
contentView.invalidateBlur();
}
};
if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 19) {
chatListView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
chatListView.setAccessibilityEnabled(false);
chatListView.setNestedScrollingEnabled(false);
chatListView.setInstantClick(true);
chatListView.setDisableHighlightState(true);
chatListView.setTag(1);
chatListView.setVerticalScrollBarEnabled(true);
chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
chatListView.setClipToPadding(false);
chatListView.setAnimateEmptyView(true, 1);
chatListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
chatListViewPaddingTop = 0;
invalidateChatListViewTopPadding();
if (MessagesController.getGlobalMainSettings().getBoolean("view_animations", true)) {
chatListItemAnimator = new ChatListItemAnimator(this, chatListView, themeDelegate) {
Runnable finishRunnable;
@Override
public void checkIsRunning() {
if (scrollAnimationIndex == -1) {
scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, allowedNotificationsDuringChatListAnimations, false);
}
}
@Override
public void onAnimationStart() {
if (scrollAnimationIndex == -1) {
scrollAnimationIndex = getNotificationCenter().setAnimationInProgress(scrollAnimationIndex, allowedNotificationsDuringChatListAnimations, false);
}
if (finishRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(finishRunnable);
finishRunnable = null;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("chatItemAnimator disable notifications");
}
chatActivityEnterView.getAdjustPanLayoutHelper().runDelayedAnimation();
chatActivityEnterView.runEmojiPanelAnimation();
}
@Override
protected void onAllAnimationsDone() {
super.onAllAnimationsDone();
if (finishRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(finishRunnable);
}
AndroidUtilities.runOnUIThread(finishRunnable = () -> {
if (scrollAnimationIndex != -1) {
getNotificationCenter().onAnimationFinish(scrollAnimationIndex);
scrollAnimationIndex = -1;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("chatItemAnimator enable notifications");
}
});
}
@Override
public void endAnimations() {
super.endAnimations();
if (finishRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(finishRunnable);
}
AndroidUtilities.runOnUIThread(finishRunnable = () -> {
if (scrollAnimationIndex != -1) {
getNotificationCenter().onAnimationFinish(scrollAnimationIndex);
scrollAnimationIndex = -1;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("chatItemAnimator enable notifications");
}
});
}
};
}
chatLayoutManager = new GridLayoutManagerFixed(context, 1000, LinearLayoutManager.VERTICAL, true) {
boolean computingScroll;
@Override
public int getStarForFixGap() {
int padding = (int) chatListViewPaddingTop;
if (isThreadChat() && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
}
return padding;
}
@Override
protected int getParentStart() {
if (computingScroll) {
return (int) chatListViewPaddingTop;
}
return 0;
}
@Override
public int getStartAfterPadding() {
if (computingScroll) {
return (int) chatListViewPaddingTop;
}
return super.getStartAfterPadding();
}
@Override
public int getTotalSpace() {
if (computingScroll) {
return (int) (getHeight() - chatListViewPaddingTop - getPaddingBottom());
}
return super.getTotalSpace();
}
@Override
public int computeVerticalScrollExtent(RecyclerView.State state) {
computingScroll = true;
int r = super.computeVerticalScrollExtent(state);
computingScroll = false;
return r;
}
@Override
public int computeVerticalScrollOffset(RecyclerView.State state) {
computingScroll = true;
int r = super.computeVerticalScrollOffset(state);
computingScroll = false;
return r;
}
@Override
public int computeVerticalScrollRange(RecyclerView.State state) {
computingScroll = true;
int r = super.computeVerticalScrollRange(state);
computingScroll = false;
return r;
}
@Override
public void scrollToPositionWithOffset(int position, int offset, boolean bottom) {
if (!bottom) {
offset = (int) (offset - getPaddingTop() + chatListViewPaddingTop);
}
super.scrollToPositionWithOffset(position, offset, bottom);
}
@Override
public boolean supportsPredictiveItemAnimations() {
return true;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
scrollByTouch = false;
LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE);
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
@Override
public boolean shouldLayoutChildFromOpositeSide(View child) {
if (child instanceof ChatMessageCell) {
return !((ChatMessageCell) child).getMessageObject().isOutOwner();
}
return false;
}
@Override
protected boolean hasSiblingChild(int position) {
if (position >= chatAdapter.messagesStartRow && position < chatAdapter.messagesEndRow) {
int index = position - chatAdapter.messagesStartRow;
if (index >= 0 && index < messages.size()) {
MessageObject message = messages.get(index);
MessageObject.GroupedMessages group = getValidGroupedMessage(message);
if (group != null) {
MessageObject.GroupedMessagePosition pos = group.positions.get(message);
if (pos.minX == pos.maxX || pos.minY != pos.maxY || pos.minY == 0) {
return false;
}
int count = group.posArray.size();
for (int a = 0; a < count; a++) {
MessageObject.GroupedMessagePosition p = group.posArray.get(a);
if (p == pos) {
continue;
}
if (p.minY <= pos.minY && p.maxY >= pos.minY) {
return true;
}
}
}
}
}
return false;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
super.onLayoutChildren(recycler, state);
} else {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
FileLog.e(e);
AndroidUtilities.runOnUIThread(() -> chatAdapter.notifyDataSetChanged(false));
}
}
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (dy < 0 && pullingDownOffset != 0) {
pullingDownOffset += dy;
if (pullingDownOffset < 0) {
dy = (int) pullingDownOffset;
pullingDownOffset = 0;
chatListView.invalidate();
} else {
dy = 0;
}
}
int n = chatListView.getChildCount();
int scrolled = 0;
boolean foundTopView = false;
for (int i = 0; i < n; i++) {
View child = chatListView.getChildAt(i);
float padding = chatListViewPaddingTop;
if (isThreadChat() && pinnedMessageView != null && pinnedMessageView.getVisibility() == View.VISIBLE) {
padding -= Math.max(0, AndroidUtilities.dp(48) + pinnedMessageEnterOffset);
}
if (chatListView.getChildAdapterPosition(child) == chatAdapter.getItemCount() - 1) {
int dyLocal = dy;
if (child.getTop() - dy > padding) {
dyLocal = (int) (child.getTop() - padding);
}
scrolled = super.scrollVerticallyBy(dyLocal, recycler, state);
foundTopView = true;
break;
}
}
if (!foundTopView) {
scrolled = super.scrollVerticallyBy(dy, recycler, state);
}
if (dy > 0 && scrolled == 0 && ChatObject.isChannel(currentChat) && !currentChat.megagroup && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING && !chatListView.isFastScrollAnimationRunning() && !chatListView.isMultiselect()) {
if (pullingDownOffset == 0 && pullingDownDrawable != null) {
pullingDownDrawable.updateDialog();
}
if (pullingDownBackAnimator != null) {
pullingDownBackAnimator.removeAllListeners();
pullingDownBackAnimator.cancel();
}
float k;
if (pullingDownOffset < AndroidUtilities.dp(110)) {
float progress = pullingDownOffset / AndroidUtilities.dp(110);
k = 0.65f * (1f - progress) + 0.45f * progress;
} else if (pullingDownOffset < AndroidUtilities.dp(160)) {
float progress = (pullingDownOffset - AndroidUtilities.dp(110)) / AndroidUtilities.dp(50);
k = 0.45f * (1f - progress) + 0.05f * progress;
} else {
k = 0.05f;
}
pullingDownOffset += dy * k;
ReactionsEffectOverlay.onScrolled((int) (dy * k));
chatListView.invalidate();
}
if (pullingDownOffset == 0) {
chatListView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
} else {
chatListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
}
if (pullingDownDrawable != null) {
pullingDownDrawable.showBottomPanel(pullingDownOffset > 0 && chatListView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING);
}
return scrolled;
}
};
chatLayoutManager.setSpanSizeLookup(new GridLayoutManagerFixed.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position >= chatAdapter.messagesStartRow && position < chatAdapter.messagesEndRow) {
int idx = position - chatAdapter.messagesStartRow;
if (idx >= 0 && idx < messages.size()) {
MessageObject message = messages.get(idx);
MessageObject.GroupedMessages groupedMessages = getValidGroupedMessage(message);
if (groupedMessages != null) {
return groupedMessages.positions.get(message).spanSize;
}
}
}
return 1000;
}
});
chatListView.setLayoutManager(chatLayoutManager);
chatListView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.bottom = 0;
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
MessageObject.GroupedMessages group = cell.getCurrentMessagesGroup();
if (group != null) {
MessageObject.GroupedMessagePosition position = cell.getCurrentPosition();
if (position != null && position.siblingHeights != null) {
float maxHeight = Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.5f;
int h = cell.getExtraInsetHeight();
for (int a = 0; a < position.siblingHeights.length; a++) {
h += (int) Math.ceil(maxHeight * position.siblingHeights[a]);
}
h += (position.maxY - position.minY) * Math.round(7 * AndroidUtilities.density);
int count = group.posArray.size();
for (int a = 0; a < count; a++) {
MessageObject.GroupedMessagePosition pos = group.posArray.get(a);
if (pos.minY != position.minY || pos.minX == position.minX && pos.maxX == position.maxX && pos.minY == position.minY && pos.maxY == position.maxY) {
continue;
}
if (pos.minY == position.minY) {
h -= (int) Math.ceil(maxHeight * pos.ph) - AndroidUtilities.dp(4);
break;
}
}
outRect.bottom = -h;
}
}
}
}
});
contentView.addView(chatListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
chatListView.setOnItemLongClickListener(onItemLongClickListener);
chatListView.setOnItemClickListener(onItemClickListener);
chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {
private float totalDy = 0;
private boolean scrollUp;
private final int scrollValue = AndroidUtilities.dp(100);
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
if (pollHintCell != null) {
pollHintView.showForMessageCell(pollHintCell, -1, pollHintX, pollHintY, true);
pollHintCell = null;
}
scrollingFloatingDate = false;
scrollingChatListView = false;
checkTextureViewPosition = false;
hideFloatingDateView(true);
checkAutoDownloadMessages(scrollUp);
if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startAllHeavyOperations, 512);
}
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.startSpoilers);
chatListView.setOverScrollMode(RecyclerView.OVER_SCROLL_ALWAYS);
textSelectionHelper.stopScrolling();
updateVisibleRows();
scrollByTouch = false;
} else {
if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
wasManualScroll = true;
scrollingChatListView = true;
} else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
pollHintCell = null;
wasManualScroll = true;
scrollingFloatingDate = true;
checkTextureViewPosition = true;
scrollingChatListView = true;
}
if (SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW) {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopAllHeavyOperations, 512);
}
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.stopSpoilers);
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
chatListView.invalidate();
scrollUp = dy < 0;
int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
if (dy != 0 && (scrollByTouch && recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_SETTLING) || recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
if (forceNextPinnedMessageId != 0) {
if ((!scrollUp || forceScrollToFirst)) {
forceNextPinnedMessageId = 0;
} else if (!chatListView.isFastScrollAnimationRunning() && firstVisibleItem != RecyclerView.NO_POSITION) {
int lastVisibleItem = chatLayoutManager.findLastVisibleItemPosition();
MessageObject messageObject = null;
boolean foundForceNextPinnedView = false;
for (int i = lastVisibleItem; i >= firstVisibleItem; i--) {
View view = chatLayoutManager.findViewByPosition(i);
if (view instanceof ChatMessageCell) {
messageObject = ((ChatMessageCell) view).getMessageObject();
} else if (view instanceof ChatActionCell) {
messageObject = ((ChatActionCell) view).getMessageObject();
}
if (messageObject != null) {
if (forceNextPinnedMessageId == messageObject.getId()) {
foundForceNextPinnedView = true;
break;
}
}
}
if (!foundForceNextPinnedView && messageObject != null && messageObject.getId() < forceNextPinnedMessageId) {
forceNextPinnedMessageId = 0;
}
}
}
}
if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
forceScrollToFirst = false;
if (!wasManualScroll && dy != 0) {
wasManualScroll = true;
}
}
if (dy != 0) {
hideHints(true);
}
if (dy != 0 && scrollingFloatingDate && !currentFloatingTopIsNotMessage) {
if (highlightMessageId != Integer.MAX_VALUE) {
removeSelectedMessageHighlight();
updateVisibleRows();
}
showFloatingDateView(true);
}
checkScrollForLoad(true);
if (firstVisibleItem != RecyclerView.NO_POSITION) {
int totalItemCount = chatAdapter.getItemCount();
if (firstVisibleItem == 0 && forwardEndReached[0]) {
if (dy >= 0) {
canShowPagedownButton = false;
updatePagedownButtonVisibility(true);
}
} else {
if (dy > 0) {
if (pagedownButton.getTag() == null) {
totalDy += dy;
if (totalDy > scrollValue) {
totalDy = 0;
canShowPagedownButton = true;
updatePagedownButtonVisibility(true);
pagedownButtonShowedByScroll = true;
}
}
} else {
if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
totalDy += dy;
if (totalDy < -scrollValue) {
canShowPagedownButton = false;
updatePagedownButtonVisibility(true);
totalDy = 0;
}
}
}
}
}
invalidateMessagesVisiblePart();
textSelectionHelper.onParentScrolled();
emojiAnimationsOverlay.onScrolled(dy);
ReactionsEffectOverlay.onScrolled(dy);
}
});
animatingImageView = new ClippingImageView(context);
animatingImageView.setVisibility(View.GONE);
contentView.addView(animatingImageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
progressView = new FrameLayout(context);
progressView.setVisibility(View.INVISIBLE);
contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
progressView2 = new View(context);
progressView2.setBackground(Theme.createServiceDrawable(AndroidUtilities.dp(18), progressView2, contentView, getThemedPaint(Theme.key_paint_chatActionBackground)));
progressView.addView(progressView2, LayoutHelper.createFrame(36, 36, Gravity.CENTER));
progressBar = new RadialProgressView(context, themeDelegate);
progressBar.setSize(AndroidUtilities.dp(28));
progressBar.setProgressColor(getThemedColor(Theme.key_chat_serviceText));
progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));
floatingDateView = new ChatActionCell(context, false, themeDelegate) {
@Override
public void setTranslationY(float translationY) {
if (getTranslationY() != translationY) {
invalidate();
}
super.setTranslationY(translationY);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
return false;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
return false;
}
return super.onTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
float clipTop = chatListView.getY() + chatListViewPaddingTop - getY();
clipTop -= AndroidUtilities.dp(4);
if (clipTop > 0) {
if (clipTop < getMeasuredHeight()) {
canvas.save();
canvas.clipRect(0, clipTop, getMeasuredWidth(), getMeasuredHeight());
super.onDraw(canvas);
canvas.restore();
}
} else {
super.onDraw(canvas);
}
}
};
floatingDateView.setCustomDate((int) (System.currentTimeMillis() / 1000), false, false);
floatingDateView.setAlpha(0.0f);
floatingDateView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
floatingDateView.setInvalidateColors(true);
contentView.addView(floatingDateView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 4, 0, 0));
floatingDateView.setOnClickListener(view -> {
if (floatingDateView.getAlpha() == 0 || actionBar.isActionModeShowed() || reportType >= 0) {
return;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis((long) floatingDateView.getCustomDate() * 1000);
int year = calendar.get(Calendar.YEAR);
int monthOfYear = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(year, monthOfYear, dayOfMonth);
jumpToDate((int) (calendar.getTime().getTime() / 1000));
});
if (currentChat != null) {
pendingRequestsDelegate = new ChatActivityMemberRequestsDelegate(this, currentChat, this::invalidateChatListViewTopPadding);
pendingRequestsDelegate.setChatInfo(chatInfo, false);
contentView.addView(pendingRequestsDelegate.getView(), ViewGroup.LayoutParams.MATCH_PARENT, pendingRequestsDelegate.getViewHeight());
}
if (currentEncryptedChat == null) {
pinnedMessageView = new ChatBlurredFrameLayout(context, ChatActivity.this) {
float lastY;
float startY;
{
setOnLongClickListener(v -> {
if (AndroidUtilities.isTablet() || isThreadChat()) {
return false;
}
startY = lastY;
openPinnedMessagesList(true);
return true;
});
}
@Override
public boolean onTouchEvent(MotionEvent event) {
lastY = event.getY();
if (event.getAction() == MotionEvent.ACTION_UP) {
finishPreviewFragment();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float dy = startY - lastY;
movePreviewFragment(dy);
if (dy < 0) {
startY = lastY;
}
}
return super.onTouchEvent(event);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (setPinnedTextTranslationX) {
for (int a = 0; a < pinnedNextAnimation.length; a++) {
if (pinnedNextAnimation[a] != null) {
pinnedNextAnimation[a].start();
}
}
setPinnedTextTranslationX = false;
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (child == pinnedLineView) {
canvas.save();
canvas.clipRect(0, 0, getMeasuredWidth(), AndroidUtilities.dp(48));
}
boolean result;
if (child == pinnedMessageTextView[0] || child == pinnedMessageTextView[1]) {
canvas.save();
canvas.clipRect(0, 0, getMeasuredWidth() - AndroidUtilities.dp(38), getMeasuredHeight());
result = super.drawChild(canvas, child, drawingTime);
canvas.restore();
} else {
result = super.drawChild(canvas, child, drawingTime);
if (child == pinnedLineView) {
canvas.restore();
}
}
return result;
}
};
pinnedMessageView.setTag(1);
pinnedMessageEnterOffset = -AndroidUtilities.dp(50);
pinnedMessageView.setVisibility(View.GONE);
pinnedMessageView.setBackgroundResource(R.drawable.blockpanel);
pinnedMessageView.backgroundColor = getThemedColor(Theme.key_chat_topPanelBackground);
pinnedMessageView.backgroundPaddingBottom = AndroidUtilities.dp(2);
pinnedMessageView.getBackground().mutate().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
contentView.addView(pinnedMessageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
pinnedMessageView.setOnClickListener(v -> {
wasManualScroll = true;
if (isThreadChat()) {
scrollToMessageId(threadMessageId, 0, true, 0, true, 0);
} else if (currentPinnedMessageId != 0) {
int currentPinned = currentPinnedMessageId;
int forceNextPinnedMessageId = 0;
if (!pinnedMessageIds.isEmpty()) {
if (currentPinned == pinnedMessageIds.get(pinnedMessageIds.size() - 1)) {
forceNextPinnedMessageId = pinnedMessageIds.get(0) + 1;
forceScrollToFirst = true;
} else {
forceNextPinnedMessageId = currentPinned - 1;
forceScrollToFirst = false;
}
}
this.forceNextPinnedMessageId = forceNextPinnedMessageId;
if (!forceScrollToFirst) {
forceNextPinnedMessageId = -forceNextPinnedMessageId;
}
scrollToMessageId(currentPinned, 0, true, 0, true, forceNextPinnedMessageId);
updateMessagesVisiblePart(false);
}
});
View selector = new View(context);
selector.setBackground(Theme.getSelectorDrawable(false));
pinnedMessageView.addView(selector, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 2));
pinnedLineView = new PinnedLineView(context, themeDelegate);
pinnedMessageView.addView(pinnedLineView, LayoutHelper.createFrame(2, 48, Gravity.LEFT | Gravity.TOP, 8, 0, 0, 0));
pinnedCounterTextView = new NumberTextView(context);
pinnedCounterTextView.setAddNumber();
pinnedCounterTextView.setTextSize(14);
pinnedCounterTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
pinnedCounterTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
pinnedMessageView.addView(pinnedCounterTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7, 44, 0));
for (int a = 0; a < 2; a++) {
pinnedNameTextView[a] = new SimpleTextView(context) {
@Override
protected boolean createLayout(int width) {
boolean result = super.createLayout(width);
if (this == pinnedNameTextView[0] && pinnedCounterTextView != null) {
int newX = getTextWidth() + AndroidUtilities.dp(4);
if (newX != pinnedCounterTextViewX) {
pinnedCounterTextView.setTranslationX(pinnedCounterTextViewX = newX);
}
}
return result;
}
};
pinnedNameTextView[a].setTextSize(14);
pinnedNameTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
pinnedNameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
pinnedMessageView.addView(pinnedNameTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 7.3f, 44, 0));
pinnedMessageTextView[a] = new SimpleTextView(context) {
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
if (this == pinnedMessageTextView[0] && pinnedNextAnimation[1] != null) {
if (forceScrollToFirst && translationY < 0) {
pinnedLineView.setTranslationY(translationY / 2);
} else {
pinnedLineView.setTranslationY(0);
}
}
}
};
pinnedMessageTextView[a].setTextSize(14);
pinnedMessageTextView[a].setTextColor(getThemedColor(Theme.key_chat_topPanelMessage));
pinnedMessageView.addView(pinnedMessageTextView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 18, 25.3f, 44, 0));
pinnedMessageImageView[a] = new BackupImageView(context);
pinnedMessageImageView[a].setRoundRadius(AndroidUtilities.dp(2));
pinnedMessageView.addView(pinnedMessageImageView[a], LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));
if (a == 1) {
pinnedMessageTextView[a].setVisibility(View.INVISIBLE);
pinnedNameTextView[a].setVisibility(View.INVISIBLE);
pinnedMessageImageView[a].setVisibility(View.INVISIBLE);
}
}
pinnedListButton = new ImageView(context);
pinnedListButton.setImageResource(R.drawable.menu_pinnedlist);
pinnedListButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
pinnedListButton.setScaleType(ImageView.ScaleType.CENTER);
pinnedListButton.setContentDescription(LocaleController.getString("AccPinnedMessagesList", R.string.AccPinnedMessagesList));
pinnedListButton.setVisibility(View.INVISIBLE);
pinnedListButton.setAlpha(0.0f);
pinnedListButton.setScaleX(0.4f);
pinnedListButton.setScaleY(0.4f);
if (Build.VERSION.SDK_INT >= 21) {
pinnedListButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff));
}
pinnedMessageView.addView(pinnedListButton, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 7, 0));
pinnedListButton.setOnClickListener(v -> openPinnedMessagesList(false));
closePinned = new ImageView(context);
closePinned.setImageResource(R.drawable.miniplayer_close);
closePinned.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
closePinned.setScaleType(ImageView.ScaleType.CENTER);
closePinned.setContentDescription(LocaleController.getString("Close", R.string.Close));
pinnedProgress = new RadialProgressView(context, themeDelegate);
pinnedProgress.setVisibility(View.GONE);
pinnedProgress.setSize(AndroidUtilities.dp(16));
pinnedProgress.setStrokeWidth(2f);
pinnedProgress.setProgressColor(getThemedColor(Theme.key_chat_topPanelLine));
pinnedMessageView.addView(pinnedProgress, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
if (threadMessageId != 0) {
closePinned.setVisibility(View.GONE);
}
if (Build.VERSION.SDK_INT >= 21) {
closePinned.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(14)));
}
pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
closePinned.setOnClickListener(v -> {
if (getParentActivity() == null) {
return;
}
boolean allowPin;
if (currentChat != null) {
allowPin = ChatObject.canPinMessages(currentChat);
} else if (currentEncryptedChat == null) {
if (userInfo != null) {
allowPin = userInfo.can_pin_message;
} else {
allowPin = false;
}
} else {
allowPin = false;
}
if (allowPin) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("UnpinMessageAlertTitle", R.string.UnpinMessageAlertTitle));
builder.setMessage(LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert));
builder.setPositiveButton(LocaleController.getString("UnpinMessage", R.string.UnpinMessage), (dialogInterface, i) -> {
MessageObject messageObject = pinnedMessageObjects.get(currentPinnedMessageId);
if (messageObject == null) {
messageObject = messagesDict[0].get(currentPinnedMessageId);
}
unpinMessage(messageObject);
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (!pinnedMessageIds.isEmpty()) {
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
preferences.edit().putInt("pin_" + dialog_id, pinnedMessageIds.get(0)).commit();
updatePinnedMessageView(true);
}
});
}
topChatPanelView = new ChatBlurredFrameLayout(context, this) {
private boolean ignoreLayout;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE && reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
width = (width - AndroidUtilities.dp(31)) / 2;
}
ignoreLayout = true;
if (reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) reportSpamButton.getLayoutParams();
layoutParams.width = width;
if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE) {
reportSpamButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
layoutParams.leftMargin = width;
layoutParams.width -= AndroidUtilities.dp(15);
} else {
reportSpamButton.setPadding(AndroidUtilities.dp(48), 0, AndroidUtilities.dp(48), 0);
layoutParams.leftMargin = 0;
}
}
if (addToContactsButton != null && addToContactsButton.getVisibility() == VISIBLE) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) addToContactsButton.getLayoutParams();
layoutParams.width = width;
if (reportSpamButton != null && reportSpamButton.getVisibility() == VISIBLE) {
addToContactsButton.setPadding(AndroidUtilities.dp(11), 0, AndroidUtilities.dp(4), 0);
} else {
addToContactsButton.setPadding(AndroidUtilities.dp(48), 0, AndroidUtilities.dp(48), 0);
layoutParams.leftMargin = 0;
}
}
ignoreLayout = false;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
};
topChatPanelView.backgroundColor = getThemedColor(Theme.key_chat_topPanelBackground);
topChatPanelView.backgroundPaddingBottom = AndroidUtilities.dp(2);
topChatPanelView.setTag(1);
topChatPanelViewOffset = -AndroidUtilities.dp(50);
invalidateChatListViewTopPadding();
topChatPanelView.setVisibility(View.GONE);
topChatPanelView.setBackgroundResource(R.drawable.blockpanel);
topChatPanelView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
contentView.addView(topChatPanelView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
reportSpamButton = new TextView(context);
reportSpamButton.setTextColor(getThemedColor(Theme.key_chat_reportSpam));
if (Build.VERSION.SDK_INT >= 21) {
reportSpamButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_reportSpam) & 0x19ffffff, 2));
}
reportSpamButton.setTag(Theme.key_chat_reportSpam);
reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
reportSpamButton.setSingleLine(true);
reportSpamButton.setMaxLines(1);
reportSpamButton.setGravity(Gravity.CENTER);
topChatPanelView.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 1));
reportSpamButton.setOnClickListener(v2 -> AlertsCreator.showBlockReportSpamAlert(ChatActivity.this, dialog_id, currentUser, currentChat, currentEncryptedChat, reportSpamButton.getTag(R.id.object_tag) != null, chatInfo, param -> {
if (param == 0) {
updateTopPanel(true);
} else {
finishFragment();
}
}, themeDelegate));
addToContactsButton = new TextView(context);
addToContactsButton.setTextColor(getThemedColor(Theme.key_chat_addContact));
addToContactsButton.setVisibility(View.GONE);
addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addToContactsButton.setSingleLine(true);
addToContactsButton.setMaxLines(1);
addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
addToContactsButton.setGravity(Gravity.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
addToContactsButton.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_addContact) & 0x19ffffff, 2));
}
topChatPanelView.addView(addToContactsButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 1));
addToContactsButton.setOnClickListener(v -> {
if (addToContactsButtonArchive) {
getMessagesController().addDialogToFolder(dialog_id, 0, 0, 0);
undoView.showWithAction(dialog_id, UndoView.ACTION_CHAT_UNARCHIVED, null);
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("dialog_bar_archived" + dialog_id, false);
editor.putBoolean("dialog_bar_block" + dialog_id, false);
editor.putBoolean("dialog_bar_report" + dialog_id, false);
editor.commit();
updateTopPanel(false);
getNotificationsController().clearDialogNotificationsSettings(dialog_id);
} else if (addToContactsButton.getTag() != null && (Integer) addToContactsButton.getTag() == 4) {
if (chatInfo != null && chatInfo.participants != null) {
LongSparseArray<TLObject> users = new LongSparseArray<>();
for (int a = 0; a < chatInfo.participants.participants.size(); a++) {
users.put(chatInfo.participants.participants.get(a).user_id, null);
}
long chatId = chatInfo.id;
InviteMembersBottomSheet bottomSheet = new InviteMembersBottomSheet(context, currentAccount, users, chatInfo.id, ChatActivity.this, themeDelegate);
bottomSheet.setDelegate((users1, fwdCount) -> {
for (int a = 0, N = users1.size(); a < N; a++) {
TLRPC.User user = users1.get(a);
getMessagesController().addUserToChat(chatId, user, fwdCount, null, ChatActivity.this, null);
}
getMessagesController().hidePeerSettingsBar(dialog_id, currentUser, currentChat);
updateTopPanel(true);
updateInfoTopView(true);
});
bottomSheet.show();
}
} else if (addToContactsButton.getTag() != null) {
shareMyContact(1, null);
} else {
Bundle args = new Bundle();
args.putLong("user_id", currentUser.id);
args.putBoolean("addContact", true);
ContactAddActivity activity = new ContactAddActivity(args);
activity.setDelegate(() -> undoView.showWithAction(dialog_id, UndoView.ACTION_CONTACT_ADDED, currentUser));
presentFragment(activity);
}
});
closeReportSpam = new ImageView(context);
closeReportSpam.setImageResource(R.drawable.miniplayer_close);
closeReportSpam.setContentDescription(LocaleController.getString("Close", R.string.Close));
if (Build.VERSION.SDK_INT >= 21) {
closeReportSpam.setBackground(Theme.createSelectorDrawable(getThemedColor(Theme.key_chat_topPanelClose) & 0x19ffffff));
}
closeReportSpam.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelClose), PorterDuff.Mode.MULTIPLY));
closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
topChatPanelView.addView(closeReportSpam, LayoutHelper.createFrame(36, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 2, 0));
closeReportSpam.setOnClickListener(v -> {
long did = dialog_id;
if (currentEncryptedChat != null) {
did = currentUser.id;
}
getMessagesController().hidePeerSettingsBar(did, currentUser, currentChat);
updateTopPanel(true);
updateInfoTopView(true);
});
alertView = new FrameLayout(context);
alertView.setTag(1);
alertView.setVisibility(View.GONE);
alertView.setBackgroundResource(R.drawable.blockpanel);
alertView.getBackground().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_topPanelBackground), PorterDuff.Mode.MULTIPLY));
contentView.addView(alertView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
alertNameTextView = new TextView(context);
alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
alertNameTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelTitle));
alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
alertNameTextView.setSingleLine(true);
alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
alertNameTextView.setMaxLines(1);
alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));
alertTextView = new TextView(context);
alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
alertTextView.setTextColor(getThemedColor(Theme.key_chat_topPanelMessage));
alertTextView.setSingleLine(true);
alertTextView.setEllipsize(TextUtils.TruncateAt.END);
alertTextView.setMaxLines(1);
alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));
pagedownButton = new FrameLayout(context);
pagedownButton.setVisibility(View.INVISIBLE);
contentView.addView(pagedownButton, LayoutHelper.createFrame(66, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -3, 5));
pagedownButton.setOnClickListener(view -> {
wasManualScroll = true;
textSelectionHelper.cancelTextSelectionRunnable();
if (createUnreadMessageAfterId != 0) {
scrollToMessageId(createUnreadMessageAfterId, 0, false, returnToLoadIndex, true, 0);
} else if (returnToMessageId > 0) {
scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex, true, 0);
} else {
scrollToLastMessage(false);
if (!pinnedMessageIds.isEmpty()) {
forceScrollToFirst = true;
forceNextPinnedMessageId = pinnedMessageIds.get(0);
}
}
});
mentiondownButton = new FrameLayout(context);
mentiondownButton.setVisibility(View.INVISIBLE);
contentView.addView(mentiondownButton, LayoutHelper.createFrame(46, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
mentiondownButton.setOnClickListener(new View.OnClickListener() {
private void loadLastUnreadMention() {
wasManualScroll = true;
if (hasAllMentionsLocal) {
getMessagesStorage().getUnreadMention(dialog_id, param -> {
if (param == 0) {
hasAllMentionsLocal = false;
loadLastUnreadMention();
} else {
scrollToMessageId(param, 0, false, 0, true, 0);
}
});
} else {
final MessagesStorage messagesStorage = getMessagesStorage();
TLRPC.TL_messages_getUnreadMentions req = new TLRPC.TL_messages_getUnreadMentions();
req.peer = getMessagesController().getInputPeer(dialog_id);
req.limit = 1;
req.add_offset = newMentionsCount - 1;
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
if (error != null || res.messages.isEmpty()) {
if (res != null) {
newMentionsCount = res.count;
} else {
newMentionsCount = 0;
}
messagesStorage.resetMentionsCount(dialog_id, newMentionsCount);
if (newMentionsCount == 0) {
hasAllMentionsLocal = true;
showMentionDownButton(false, true);
} else {
mentiondownButtonCounter.setText(String.format("%d", newMentionsCount));
loadLastUnreadMention();
}
} else {
int id = res.messages.get(0).id;
MessageObject object = messagesDict[0].get(id);
messagesStorage.markMessageAsMention(dialog_id, id);
if (object != null) {
object.messageOwner.media_unread = true;
object.messageOwner.mentioned = true;
}
scrollToMessageId(id, 0, false, 0, true, 0);
}
}));
}
}
@Override
public void onClick(View view) {
loadLastUnreadMention();
}
});
mentiondownButton.setOnLongClickListener(view -> {
scrimPopupWindow = ReadAllMentionsMenu.show(ReadAllMentionsMenu.TYPE_MENTIONS, getParentActivity(), contentView, view, getResourceProvider(), () -> {
for (int a = 0; a < messages.size(); a++) {
MessageObject messageObject = messages.get(a);
if (messageObject.messageOwner.mentioned && !messageObject.isContentUnread()) {
messageObject.setContentIsRead();
}
}
newMentionsCount = 0;
getMessagesController().markMentionsAsRead(dialog_id);
hasAllMentionsLocal = true;
showMentionDownButton(false, true);
if (scrimPopupWindow != null) {
scrimPopupWindow.dismiss();
}
});
dimBehindView(mentiondownButton, true);
scrimPopupWindow.setOnDismissListener(() -> {
scrimPopupWindow = null;
menuDeleteItem = null;
scrimPopupWindowItems = null;
chatLayoutManager.setCanScrollVertically(true);
dimBehindView(false);
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setAllowDrawCursor(true);
}
});
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return true;
});
mentionContainer = new FrameLayout(context) {
private Rect padding;
@Override
public void onDraw(Canvas canvas) {
if (mentionListView.getChildCount() <= 0) {
return;
}
if (mentionLayoutManager.getReverseLayout()) {
float top = mentionListView.getY() + mentionListViewScrollOffsetY + AndroidUtilities.dp(2);
float bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
Theme.chat_composeShadowDrawable.setBounds(0, (int) bottom, getMeasuredWidth(), (int) top);
Theme.chat_composeShadowDrawable.draw(canvas);
canvas.drawRect(0, 0, getMeasuredWidth(), top, getThemedPaint(Theme.key_paint_chatComposeBackground));
} else {
int top = (int) mentionListView.getY();
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout() && mentionsAdapter.getBotContextSwitch() == null) {
top += mentionListViewScrollOffsetY - AndroidUtilities.dp(4);
} else {
top += mentionListViewScrollOffsetY - AndroidUtilities.dp(2);
}
if (mentionsAdapter.isMediaLayout()) {
if (padding == null) {
padding = new Rect();
Theme.chat_composeShadowRoundDrawable.getPadding(padding);
}
int bottom = top + Theme.chat_composeShadowRoundDrawable.getIntrinsicHeight();
Theme.chat_composeShadowRoundDrawable.setBounds(-padding.left, top - padding.top - AndroidUtilities.dp(8), getMeasuredWidth() + padding.right, (int) (bottomPanelTranslationYReverse + getMeasuredHeight()));
Theme.chat_composeShadowRoundDrawable.draw(canvas);
} else {
int bottom = top + Theme.chat_composeShadowDrawable.getIntrinsicHeight();
Theme.chat_composeShadowDrawable.setBounds(0, top, getMeasuredWidth(), bottom);
Theme.chat_composeShadowDrawable.draw(canvas);
canvas.drawRect(0, bottom, getMeasuredWidth(), bottomPanelTranslationYReverse + getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
}
}
}
@Override
public void requestLayout() {
if (mentionListViewIgnoreLayout) {
return;
}
super.requestLayout();
}
};
mentionContainer.setVisibility(View.GONE);
updateMessageListAccessibilityVisibility();
mentionContainer.setWillNotDraw(false);
contentView.addView(mentionContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));
final ContentPreviewViewer.ContentPreviewViewerDelegate contentPreviewViewerDelegate = new ContentPreviewViewer.ContentPreviewViewerDelegate() {
@Override
public void sendSticker(TLRPC.Document sticker, String query, Object parent, boolean notify, int scheduleDate) {
chatActivityEnterView.onStickerSelected(sticker, query, parent, null, true, notify, scheduleDate);
}
@Override
public boolean needSend() {
return false;
}
@Override
public boolean canSchedule() {
return ChatActivity.this.canScheduleMessage();
}
@Override
public boolean isInScheduleMode() {
return chatMode == MODE_SCHEDULED;
}
@Override
public void openSet(TLRPC.InputStickerSet set, boolean clearsInputField) {
if (set == null || getParentActivity() == null) {
return;
}
TLRPC.TL_inputStickerSetID inputStickerSet = new TLRPC.TL_inputStickerSetID();
inputStickerSet.access_hash = set.access_hash;
inputStickerSet.id = set.id;
StickersAlert alert = new StickersAlert(getParentActivity(), ChatActivity.this, inputStickerSet, null, chatActivityEnterView, themeDelegate);
alert.setCalcMandatoryInsets(isKeyboardVisible());
alert.setClearsInputField(clearsInputField);
showDialog(alert);
}
@Override
public long getDialogId() {
return dialog_id;
}
};
mentionListView = new RecyclerListView(context, themeDelegate) {
private int lastWidth;
private int lastHeight;
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mentionLayoutManager.getReverseLayout()) {
if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() > mentionListViewScrollOffsetY) {
return false;
}
} else {
if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() < mentionListViewScrollOffsetY) {
return false;
}
}
boolean result = !mentionListViewIsScrolling && ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, mentionListView, 0, null, themeDelegate);
if (mentionsAdapter.isStickers() && event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
mentionsAdapter.doSomeStickersAction();
}
return super.onInterceptTouchEvent(event) || result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mentionLayoutManager.getReverseLayout()) {
if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() > mentionListViewScrollOffsetY) {
return false;
}
} else {
if (!mentionListViewIsDragging && mentionListViewScrollOffsetY != 0 && event.getY() < mentionListViewScrollOffsetY) {
return false;
}
}
// supress warning
return super.onTouchEvent(event);
}
@Override
public void requestLayout() {
if (mentionListViewIgnoreLayout) {
return;
}
super.requestLayout();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
int newPosition = -1;
int newTop = 0;
if (!mentionLayoutManager.getReverseLayout() && mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth && height - lastHeight != 0) {
newPosition = mentionListViewLastViewPosition;
newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
}
super.onLayout(changed, l, t, r, b);
if (newPosition != -1) {
mentionListViewIgnoreLayout = true;
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
} else {
mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
}
super.onLayout(false, l, t, r, b);
mentionListViewIgnoreLayout = false;
}
lastHeight = height;
lastWidth = width;
mentionListViewUpdateLayout();
}
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
mentionContainer.invalidate();
}
};
mentionListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, mentionListView, 0, mentionsOnItemClickListener, mentionsAdapter.isStickers() ? contentPreviewViewerDelegate : null, themeDelegate));
mentionListView.setTag(2);
mentionLayoutManager = new LinearLayoutManager(context) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
@Override
public void setReverseLayout(boolean reverseLayout) {
super.setReverseLayout(reverseLayout);
invalidateChatListViewTopPadding();
}
};
mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {
private Size size = new Size();
@Override
protected Size getSizeForItem(int i) {
if (mentionsAdapter.getBotContextSwitch() != null) {
i++;
}
size.width = 0;
size.height = 0;
Object object = mentionsAdapter.getItem(i);
if (object instanceof TLRPC.BotInlineResult) {
TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
if (inlineResult.document != null) {
TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(inlineResult.document.thumbs, 90);
size.width = thumb != null ? thumb.w : 100;
size.height = thumb != null ? thumb.h : 100;
for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
size.width = attribute.w;
size.height = attribute.h;
break;
}
}
} else if (inlineResult.content != null) {
for (int b = 0; b < inlineResult.content.attributes.size(); b++) {
TLRPC.DocumentAttribute attribute = inlineResult.content.attributes.get(b);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
size.width = attribute.w;
size.height = attribute.h;
break;
}
}
} else if (inlineResult.thumb != null) {
for (int b = 0; b < inlineResult.thumb.attributes.size(); b++) {
TLRPC.DocumentAttribute attribute = inlineResult.thumb.attributes.get(b);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
size.width = attribute.w;
size.height = attribute.h;
break;
}
}
} else if (inlineResult.photo != null) {
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(inlineResult.photo.sizes, AndroidUtilities.photoSize);
if (photoSize != null) {
size.width = photoSize.w;
size.height = photoSize.h;
}
}
}
return size;
}
@Override
protected int getFlowItemCount() {
if (mentionsAdapter.getBotContextSwitch() != null) {
return getItemCount() - 1;
}
return super.getFlowItemCount();
}
};
mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
Object object = mentionsAdapter.getItem(position);
if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
return 100;
} else if (object instanceof TLRPC.Document) {
return 20;
} else {
if (mentionsAdapter.getBotContextSwitch() != null) {
position--;
}
return mentionGridLayoutManager.getSpanSizeForItem(position);
}
}
});
mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = 0;
outRect.right = 0;
outRect.top = 0;
outRect.bottom = 0;
if (parent.getLayoutManager() == mentionGridLayoutManager) {
int position = parent.getChildAdapterPosition(view);
if (mentionsAdapter.isStickers()) {
return;
} else if (mentionsAdapter.getBotContextSwitch() != null) {
if (position == 0) {
return;
}
position--;
if (!mentionGridLayoutManager.isFirstRow(position)) {
outRect.top = AndroidUtilities.dp(2);
}
} else {
outRect.top = AndroidUtilities.dp(2);
}
outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
}
}
});
mentionListView.setItemAnimator(null);
mentionListView.setLayoutAnimation(null);
mentionListView.setClipToPadding(false);
mentionListView.setLayoutManager(mentionLayoutManager);
mentionListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
mentionContainer.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id, threadMessageId, new MentionsAdapter.MentionsAdapterDelegate() {
@Override
public void needChangePanelVisibility(boolean show) {
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
mentionListView.setLayoutManager(mentionGridLayoutManager);
} else {
mentionListView.setLayoutManager(mentionLayoutManager);
}
if (show && bottomOverlay.getVisibility() == View.VISIBLE && !searchingForUser) {
show = false;
}
if (show) {
if (mentionListAnimation != null) {
mentionListAnimation.cancel();
mentionListAnimation = null;
}
if (mentionContainer.getVisibility() == View.VISIBLE) {
mentionContainer.setAlpha(1.0f);
return;
}
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
} else if (!mentionLayoutManager.getReverseLayout()) {
mentionLayoutManager.scrollToPositionWithOffset(0, mentionLayoutManager.getReverseLayout() ? -10000 : 10000);
}
if (allowStickersPanel && (!mentionsAdapter.isBotContext() || (allowContextBotPanel || allowContextBotPanelSecond))) {
if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
if (!preferences.getBoolean("secretbot", false)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("SecretChatContextBotAlert", R.string.SecretChatContextBotAlert));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showDialog(builder.create());
preferences.edit().putBoolean("secretbot", true).commit();
}
}
mentionContainer.setVisibility(View.VISIBLE);
updateMessageListAccessibilityVisibility();
mentionContainer.setTag(null);
mentionListAnimation = new AnimatorSet();
mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionContainer, View.ALPHA, 0.0f, 1.0f));
mentionListAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionListAnimation = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionListAnimation = null;
}
}
});
mentionListAnimation.setDuration(200);
mentionListAnimation.start();
} else {
mentionContainer.setAlpha(1.0f);
mentionContainer.setVisibility(View.INVISIBLE);
updateMessageListAccessibilityVisibility();
}
} else {
if (mentionListAnimation != null) {
mentionListAnimation.cancel();
mentionListAnimation = null;
}
if (mentionContainer.getVisibility() == View.GONE) {
return;
}
if (allowStickersPanel) {
mentionListAnimation = new AnimatorSet();
mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionContainer, View.ALPHA, 0.0f));
mentionListAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionContainer.setVisibility(View.GONE);
mentionContainer.setTag(null);
updateMessageListAccessibilityVisibility();
mentionListAnimation = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionListAnimation = null;
}
}
});
mentionListAnimation.setDuration(200);
mentionListAnimation.start();
} else {
mentionContainer.setTag(null);
mentionContainer.setVisibility(View.GONE);
updateMessageListAccessibilityVisibility();
}
}
}
@Override
public void onContextSearch(boolean searching) {
if (chatActivityEnterView != null) {
chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
chatActivityEnterView.showContextProgress(searching);
}
}
@Override
public void onContextClick(TLRPC.BotInlineResult result) {
if (getParentActivity() == null || result.content == null) {
return;
}
if (result.type.equals("video") || result.type.equals("web_player_video")) {
int[] size = MessageObject.getInlineResultWidthAndHeight(result);
EmbedBottomSheet.show(getParentActivity(), null, botContextProvider, result.title != null ? result.title : "", result.description, result.content.url, result.content.url, size[0], size[1], isKeyboardVisible());
} else {
processExternalUrl(0, result.content.url, false);
}
}
}, themeDelegate));
if (!ChatObject.isChannel(currentChat) || currentChat.megagroup) {
mentionsAdapter.setBotInfo(botInfo);
}
mentionsAdapter.setParentFragment(this);
mentionsAdapter.setChatInfo(chatInfo);
mentionsAdapter.setNeedUsernames(currentChat != null);
mentionsAdapter.setNeedBotContext(true);
mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
mentionListView.setOnItemClickListener(mentionsOnItemClickListener = (view, position) -> {
if (mentionsAdapter.isBannedInline()) {
return;
}
Object object = mentionsAdapter.getItem(position);
int start = mentionsAdapter.getResultStartPosition();
int len = mentionsAdapter.getResultLength();
if (object instanceof TLRPC.TL_document) {
if (chatMode == 0 && checkSlowMode(view)) {
return;
}
MessageObject.SendAnimationData sendAnimationData = null;
if (view instanceof StickerCell) {
sendAnimationData = ((StickerCell) view).getSendAnimationData();
}
TLRPC.TL_document document = (TLRPC.TL_document) object;
Object parent = mentionsAdapter.getItemParent(position);
if (chatMode == MODE_SCHEDULED) {
String query = stickersAdapter.getQuery();
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> SendMessagesHelper.getInstance(currentAccount).sendSticker(document, query, dialog_id, replyingMessageObject, getThreadMessage(), parent, null, notify, scheduleDate), themeDelegate);
} else {
getSendMessagesHelper().sendSticker(document, stickersAdapter.getQuery(), dialog_id, replyingMessageObject, getThreadMessage(), parent, sendAnimationData, true, 0);
}
hideFieldPanel(false);
chatActivityEnterView.addStickerToRecent(document);
chatActivityEnterView.setFieldText("");
} else if (object instanceof TLRPC.Chat) {
TLRPC.Chat chat = (TLRPC.Chat) object;
if (searchingForUser && searchContainer.getVisibility() == View.VISIBLE) {
searchUserMessages(null, chat);
} else {
if (chat.username != null) {
chatActivityEnterView.replaceWithText(start, len, "@" + chat.username + " ", false);
}
}
} else if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
if (searchingForUser && searchContainer.getVisibility() == View.VISIBLE) {
searchUserMessages(user, null);
} else {
if (user.username != null) {
chatActivityEnterView.replaceWithText(start, len, "@" + user.username + " ", false);
} else {
String name = UserObject.getFirstName(user, false);
Spannable spannable = new SpannableString(name + " ");
spannable.setSpan(new URLSpanUserMention("" + user.id, 3), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
chatActivityEnterView.replaceWithText(start, len, spannable, false);
}
}
} else if (object instanceof String) {
if (mentionsAdapter.isBotCommands()) {
if (chatMode == MODE_SCHEDULED) {
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> {
getSendMessagesHelper().sendMessage((String) object, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, notify, scheduleDate, null);
chatActivityEnterView.setFieldText("");
hideFieldPanel(false);
}, themeDelegate);
} else {
if (checkSlowMode(view)) {
return;
}
getSendMessagesHelper().sendMessage((String) object, dialog_id, replyingMessageObject, getThreadMessage(), null, false, null, null, null, true, 0, null);
chatActivityEnterView.setFieldText("");
hideFieldPanel(false);
}
} else {
chatActivityEnterView.replaceWithText(start, len, object + " ", false);
}
} else if (object instanceof TLRPC.BotInlineResult) {
if (chatActivityEnterView.getFieldText() == null || chatMode != MODE_SCHEDULED && checkSlowMode(view)) {
return;
}
TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
if (currentEncryptedChat != null) {
int error = 0;
if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaAuto && "game".equals(result.type)) {
error = 1;
} else if (result.send_message instanceof TLRPC.TL_botInlineMessageMediaInvoice) {
error = 2;
}
if (error != 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("SendMessageTitle", R.string.SendMessageTitle));
if (error == 1) {
builder.setMessage(LocaleController.getString("GameCantSendSecretChat", R.string.GameCantSendSecretChat));
} else {
builder.setMessage(LocaleController.getString("InvoiceCantSendSecretChat", R.string.InvoiceCantSendSecretChat));
}
builder.setNegativeButton(LocaleController.getString("OK", R.string.OK), null);
showDialog(builder.create());
return;
}
}
if ((result.type.equals("photo") && (result.photo != null || result.content != null) || result.type.equals("gif") && (result.document != null || result.content != null) || result.type.equals("video") && (result.document != null))) {
ArrayList<Object> arrayList = botContextResults = new ArrayList<>(mentionsAdapter.getSearchResultBotContext());
PhotoViewer.getInstance().setParentActivity(getParentActivity(), themeDelegate);
PhotoViewer.getInstance().openPhotoForSelect(arrayList, mentionsAdapter.getItemPosition(position), 3, false, botContextProvider, ChatActivity.this);
} else {
if (chatMode == MODE_SCHEDULED) {
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), dialog_id, (notify, scheduleDate) -> sendBotInlineResult(result, notify, scheduleDate), themeDelegate);
} else {
sendBotInlineResult(result, true, 0);
}
}
} else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
} else if (object instanceof MediaDataController.KeywordResult) {
String code = ((MediaDataController.KeywordResult) object).emoji;
chatActivityEnterView.addEmojiToRecent(code);
chatActivityEnterView.replaceWithText(start, len, code, true);
}
});
mentionListView.setOnItemLongClickListener((view, position) -> {
if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
return false;
}
Object object = mentionsAdapter.getItem(position);
if (object instanceof String) {
if (mentionsAdapter.isBotCommands()) {
if (URLSpanBotCommand.enabled) {
chatActivityEnterView.setFieldText("");
chatActivityEnterView.setCommand(null, (String) object, true, currentChat != null && currentChat.megagroup);
return true;
}
return false;
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch));
builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> mentionsAdapter.clearRecentHashtags());
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
return true;
}
}
return false;
});
mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
mentionListViewIsScrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
mentionListViewIsDragging = newState == RecyclerView.SCROLL_STATE_DRAGGING;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int lastVisibleItem;
if ((mentionsAdapter.isStickers() || mentionsAdapter.isBotContext()) && mentionsAdapter.isMediaLayout()) {
lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
} else {
lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
}
int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
mentionsAdapter.searchForContextBotForNextOffset();
}
mentionListViewUpdateLayout();
}
});
pagedownButtonImage = new ImageView(context);
pagedownButtonImage.setImageResource(R.drawable.pagedown);
pagedownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
pagedownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
pagedownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0);
Drawable drawable;
if (Build.VERSION.SDK_INT >= 21) {
pagedownButtonImage.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
}
});
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
} else {
drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
}
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
drawable = combinedDrawable;
pagedownButtonImage.setBackgroundDrawable(drawable);
pagedownButton.addView(pagedownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM));
pagedownButton.setContentDescription(LocaleController.getString("AccDescrPageDown", R.string.AccDescrPageDown));
pagedownButtonCounter = new CounterView(context, themeDelegate) {
@Override
public void invalidate() {
if (isInOutAnimation()) {
contentView.invalidate();
}
super.invalidate();
}
};
pagedownButtonCounter.setReverse(true);
pagedownButton.addView(pagedownButtonCounter, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP | Gravity.LEFT));
mentiondownButtonImage = new ImageView(context);
mentiondownButtonImage.setImageResource(R.drawable.mentionbutton);
mentiondownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
mentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
mentiondownButtonImage.setPadding(0, AndroidUtilities.dp(2), 0, 0);
if (Build.VERSION.SDK_INT >= 21) {
pagedownButtonImage.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
}
});
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
} else {
drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
}
shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
drawable = combinedDrawable;
mentiondownButtonImage.setBackgroundDrawable(drawable);
mentiondownButton.addView(mentiondownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));
mentiondownButtonCounter = new SimpleTextView(context);
mentiondownButtonCounter.setVisibility(View.INVISIBLE);
mentiondownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
mentiondownButtonCounter.setTextSize(13);
mentiondownButtonCounter.setTextColor(getThemedColor(Theme.key_chat_goDownButtonCounter));
mentiondownButtonCounter.setGravity(Gravity.CENTER);
mentiondownButtonCounter.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(11.5f), getThemedColor(Theme.key_chat_goDownButtonCounterBackground)));
mentiondownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
mentiondownButtonCounter.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(1), AndroidUtilities.dp(8), 0);
mentiondownButton.addView(mentiondownButtonCounter, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
mentiondownButton.setContentDescription(LocaleController.getString("AccDescrMentionDown", R.string.AccDescrMentionDown));
reactionsMentiondownButton = new FrameLayout(context);
reactionsMentiondownButton.setOnClickListener(view -> {
wasManualScroll = true;
getMessagesController().getNextReactionMention(dialog_id, reactionsMentionCount, (messageId) -> {
if (messageId == 0) {
reactionsMentionCount = 0;
updateReactionsMentionButton(true);
getMessagesController().markReactionsAsRead(dialog_id);
} else {
updateReactionsMentionButton(true);
scrollToMessageId(messageId, 0, false, 0, true, 0);
}
});
});
reactionsMentiondownButton.setOnLongClickListener(view -> {
scrimPopupWindow = ReadAllMentionsMenu.show(ReadAllMentionsMenu.TYPE_REACTIONS, getParentActivity(), contentView, view, getResourceProvider(), () -> {
for (int i = 0; i < messages.size(); i++) {
messages.get(i).markReactionsAsRead();
}
reactionsMentionCount = 0;
updateReactionsMentionButton(true);
getMessagesController().markReactionsAsRead(dialog_id);
if (scrimPopupWindow != null) {
scrimPopupWindow.dismiss();
}
});
dimBehindView(reactionsMentiondownButton, true);
scrimPopupWindow.setOnDismissListener(() -> {
scrimPopupWindow = null;
menuDeleteItem = null;
scrimPopupWindowItems = null;
chatLayoutManager.setCanScrollVertically(true);
dimBehindView(false);
if (chatActivityEnterView != null) {
chatActivityEnterView.getEditField().setAllowDrawCursor(true);
}
});
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return false;
});
contentView.addView(reactionsMentiondownButton, LayoutHelper.createFrame(46, 61, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
reactionsMentiondownButtonImage = new ImageView(context);
reactionsMentiondownButtonImage.setImageResource(R.drawable.reactionbutton);
reactionsMentiondownButtonImage.setScaleType(ImageView.ScaleType.CENTER);
reactionsMentiondownButtonImage.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonIcon), PorterDuff.Mode.MULTIPLY));
if (Build.VERSION.SDK_INT >= 21) {
reactionsMentiondownButtonImage.setOutlineProvider(new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(42), AndroidUtilities.dp(42));
}
});
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton), getThemedColor(Theme.key_listSelector));
} else {
drawable = Theme.createCircleDrawable(AndroidUtilities.dp(42), getThemedColor(Theme.key_chat_goDownButton));
}
shadowDrawable = context.getResources().getDrawable(R.drawable.pagedown_shadow).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_goDownButtonShadow), PorterDuff.Mode.MULTIPLY));
combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(42), AndroidUtilities.dp(42));
drawable = combinedDrawable;
reactionsMentiondownButtonImage.setBackgroundDrawable(drawable);
reactionsMentiondownButton.addView(reactionsMentiondownButtonImage, LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));
reactionsMentiondownButtonCounter = new CounterView(context, themeDelegate);
reactionsMentiondownButton.addView(reactionsMentiondownButtonCounter, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 28, Gravity.TOP | Gravity.LEFT));
reactionsMentiondownButton.setContentDescription(LocaleController.getString("AccDescrReactionMentionDown", R.string.AccDescrReactionMentionDown));
if (!inMenuMode) {
fragmentLocationContextView = new FragmentContextView(context, this, true, themeDelegate);
fragmentContextView = new FragmentContextView(context, this, false, themeDelegate) {
@Override
protected void playbackSpeedChanged(float value) {
if (Math.abs(value - 1.0f) < 0.001f || Math.abs(value - 1.8f) < 0.001f) {
undoView.showWithAction(0, Math.abs(value - 1.0f) > 0.001f ? UndoView.ACTION_PLAYBACK_SPEED_ENABLED : UndoView.ACTION_PLAYBACK_SPEED_DISABLED, value, null, null);
}
}
};
contentView.addView(fragmentLocationContextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
contentView.addView(fragmentContextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
fragmentContextView.setAdditionalContextView(fragmentLocationContextView);
fragmentLocationContextView.setAdditionalContextView(fragmentContextView);
}
if (chatMode != 0) {
fragmentContextView.setSupportsCalls(false);
}
messagesSearchListView = new RecyclerListView(context, themeDelegate);
messagesSearchListView.setBackgroundColor(getThemedColor(Theme.key_windowBackgroundWhite));
LinearLayoutManager messagesSearchLayoutManager = new LinearLayoutManager(context);
messagesSearchLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
messagesSearchListView.setLayoutManager(messagesSearchLayoutManager);
messagesSearchListView.setVisibility(View.GONE);
messagesSearchListView.setAlpha(0.0f);
messagesSearchListView.setAdapter(messagesSearchAdapter = new MessagesSearchAdapter(context, themeDelegate));
contentView.addView(messagesSearchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48));
messagesSearchListView.setOnItemClickListener((view, position) -> {
getMediaDataController().jumpToSearchedMessage(classGuid, position);
showMessagesSearchListView(false);
});
messagesSearchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int lastVisibleItem = messagesSearchLayoutManager.findLastVisibleItemPosition();
int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
if (visibleItemCount > 0 && lastVisibleItem > messagesSearchLayoutManager.getItemCount() - 5) {
getMediaDataController().loadMoreSearchMessages();
}
}
});
topUndoView = new UndoView(context, this, true, themeDelegate) {
@Override
public void didPressUrl(CharacterStyle span) {
didPressMessageUrl(span, false, null, null);
}
@Override
public void showWithAction(long did, int action, Object infoObject, Object infoObject2, Runnable actionRunnable, Runnable cancelRunnable) {
setAdditionalTranslationY(fragmentContextView != null && fragmentContextView.isCallTypeVisible() ? AndroidUtilities.dp(fragmentContextView.getStyleHeight()) : 0);
super.showWithAction(did, action, infoObject, infoObject2, actionRunnable, cancelRunnable);
}
};
contentView.addView(topUndoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 8, 8, 0));
contentView.addView(actionBar);
overlayView = new View(context);
overlayView.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
checkRecordLocked(false);
}
overlayView.getParent().requestDisallowInterceptTouchEvent(true);
return true;
});
contentView.addView(overlayView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
overlayView.setVisibility(View.GONE);
contentView.setClipChildren(false);
instantCameraView = new InstantCameraView(context, this, themeDelegate);
contentView.addView(instantCameraView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
bottomMessagesActionContainer = new FrameLayout(context) {
@Override
public void onDraw(Canvas canvas) {
int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
Theme.chat_composeShadowDrawable.draw(canvas);
canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
}
};
bottomMessagesActionContainer.setVisibility(View.INVISIBLE);
bottomMessagesActionContainer.setWillNotDraw(false);
bottomMessagesActionContainer.setPadding(0, AndroidUtilities.dp(2), 0, 0);
contentView.addView(bottomMessagesActionContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
bottomMessagesActionContainer.setOnTouchListener((v, event) -> true);
chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true, themeDelegate) {
int lastContentViewHeight;
int messageEditTextPredrawHeigth;
int messageEditTextPredrawScrollY;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getAlpha() != 1.0f) {
return false;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (getAlpha() != 1.0f) {
return false;
}
return super.onTouchEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (getAlpha() != 1.0f) {
return false;
}
return super.dispatchTouchEvent(ev);
}
@Override
protected boolean pannelAnimationEnabled() {
if (!openAnimationEnded) {
return false;
}
return true;
}
@Override
public void checkAnimation() {
if (actionBar.isActionModeShowed() || reportType >= 0) {
if (messageEditTextAnimator != null) {
messageEditTextAnimator.cancel();
}
if (changeBoundAnimator != null) {
changeBoundAnimator.cancel();
}
chatActivityEnterViewAnimateFromTop = 0;
shouldAnimateEditTextWithBounds = false;
} else {
int t = getBackgroundTop();
if (chatActivityEnterViewAnimateFromTop != 0 && t != chatActivityEnterViewAnimateFromTop && lastContentViewHeight == contentView.getMeasuredHeight()) {
int dy = animatedTop + chatActivityEnterViewAnimateFromTop - t;
animatedTop = dy;
if (changeBoundAnimator != null) {
changeBoundAnimator.removeAllListeners();
changeBoundAnimator.cancel();
}
chatListView.setTranslationY(dy);
if (topView != null && topView.getVisibility() == View.VISIBLE) {
topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
if (topLineView != null) {
topLineView.setTranslationY(animatedTop);
}
}
changeBoundAnimator = ValueAnimator.ofFloat(1f, 0);
changeBoundAnimator.addUpdateListener(a -> {
int v = (int) (dy * (float) a.getAnimatedValue());
animatedTop = v;
if (topView != null && topView.getVisibility() == View.VISIBLE) {
topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
if (topLineView != null) {
topLineView.setTranslationY(animatedTop);
}
} else {
if (mentionContainer != null) {
mentionContainer.setTranslationY(v);
}
chatListView.setTranslationY(v);
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
}
invalidate();
});
changeBoundAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animatedTop = 0;
if (topView != null && topView.getVisibility() == View.VISIBLE) {
topView.setTranslationY(animatedTop + (1f - topViewEnterProgress) * topView.getLayoutParams().height);
if (topLineView != null) {
topLineView.setTranslationY(animatedTop);
}
} else {
chatListView.setTranslationY(0);
}
changeBoundAnimator = null;
}
});
changeBoundAnimator.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
changeBoundAnimator.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
if (!waitingForSendingMessageLoad) {
changeBoundAnimator.start();
}
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
chatActivityEnterViewAnimateFromTop = 0;
} else if (lastContentViewHeight != contentView.getMeasuredHeight()) {
chatActivityEnterViewAnimateFromTop = 0;
}
if (shouldAnimateEditTextWithBounds) {
float dy = (messageEditTextPredrawHeigth - messageEditText.getMeasuredHeight()) + (messageEditTextPredrawScrollY - messageEditText.getScrollY());
messageEditText.setOffsetY(messageEditText.getOffsetY() - dy);
ValueAnimator a = ValueAnimator.ofFloat(messageEditText.getOffsetY(), 0);
a.addUpdateListener(animation -> messageEditText.setOffsetY((float) animation.getAnimatedValue()));
if (messageEditTextAnimator != null) {
messageEditTextAnimator.cancel();
}
messageEditTextAnimator = a;
a.setDuration(ChatListItemAnimator.DEFAULT_DURATION);
// a.setStartDelay(chatActivityEnterViewAnimateBeforeSending ? 20 : 0);
a.setInterpolator(ChatListItemAnimator.DEFAULT_INTERPOLATOR);
a.start();
shouldAnimateEditTextWithBounds = false;
}
lastContentViewHeight = contentView.getMeasuredHeight();
chatActivityEnterViewAnimateBeforeSending = false;
}
}
@Override
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
if (chatActivityEnterView != null) {
shouldAnimateEditTextWithBounds = true;
messageEditTextPredrawHeigth = messageEditText.getMeasuredHeight();
messageEditTextPredrawScrollY = messageEditText.getScrollY();
contentView.invalidate();
chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
}
}
};
chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
int lastSize;
@Override
public int getContentViewHeight() {
return contentView.getHeight();
}
@Override
public int measureKeyboardHeight() {
return contentView.measureKeyboardHeight();
}
@Override
public TLRPC.TL_channels_sendAsPeers getSendAsPeers() {
return sendAsPeersObj;
}
@Override
public void onMessageSend(CharSequence message, boolean notify, int scheduleDate) {
if (chatListItemAnimator != null) {
chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
if (chatActivityEnterViewAnimateFromTop != 0) {
chatActivityEnterViewAnimateBeforeSending = true;
}
}
if (mentionsAdapter != null) {
mentionsAdapter.addHashtagsFromMessage(message);
}
if (scheduleDate != 0) {
if (scheduledMessagesCount == -1) {
scheduledMessagesCount = 0;
}
if (message != null) {
scheduledMessagesCount++;
}
if (forwardingMessages != null && !forwardingMessages.messages.isEmpty()) {
scheduledMessagesCount += forwardingMessages.messages.size();
}
updateScheduledInterface(false);
}
hideFieldPanel(notify, scheduleDate, true);
if (chatActivityEnterView != null && chatActivityEnterView.getEmojiView() != null) {
chatActivityEnterView.getEmojiView().onMessageSend();
}
}
@Override
public void onSwitchRecordMode(boolean video) {
showVoiceHint(false, video);
}
@Override
public void onPreAudioVideoRecord() {
showVoiceHint(true, false);
}
@Override
public void onUpdateSlowModeButton(View button, boolean show, CharSequence time) {
showSlowModeHint(button, show, time);
if (headerItem != null && headerItem.getVisibility() != View.VISIBLE) {
headerItem.setVisibility(View.VISIBLE);
if (attachItem != null) {
attachItem.setVisibility(View.GONE);
}
}
}
@Override
public void onTextSelectionChanged(int start, int end) {
if (editTextItem == null) {
return;
}
if (end - start > 0) {
if (editTextItem.getTag() == null) {
editTextItem.setTag(1);
editTextItem.setVisibility(View.VISIBLE);
headerItem.setVisibility(View.GONE);
attachItem.setVisibility(View.GONE);
}
editTextStart = start;
editTextEnd = end;
} else {
if (editTextItem.getTag() != null) {
editTextItem.setTag(null);
editTextItem.setVisibility(View.GONE);
if (chatActivityEnterView.hasText() && TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer())) {
headerItem.setVisibility(View.GONE);
attachItem.setVisibility(View.VISIBLE);
} else {
headerItem.setVisibility(View.VISIBLE);
attachItem.setVisibility(View.GONE);
}
}
}
}
@Override
public void onTextChanged(final CharSequence text, boolean bigChange) {
MediaController.getInstance().setInputFieldHasText(!TextUtils.isEmpty(text) || chatActivityEnterView.isEditingMessage());
if (stickersAdapter != null && chatActivityEnterView != null && chatActivityEnterView.getVisibility() == View.VISIBLE && (bottomOverlay == null || bottomOverlay.getVisibility() != View.VISIBLE)) {
stickersAdapter.searchEmojiByKeyword(text);
}
if (mentionsAdapter != null) {
mentionsAdapter.searchUsernameOrHashtag(text.toString(), chatActivityEnterView.getCursorPosition(), messages, false, false);
}
if (waitingForCharaterEnterRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
waitingForCharaterEnterRunnable = null;
}
if ((currentChat == null || ChatObject.canSendEmbed(currentChat)) && chatActivityEnterView.isMessageWebPageSearchEnabled() && (!chatActivityEnterView.isEditingMessage() || !chatActivityEnterView.isEditingCaption())) {
if (bigChange) {
searchLinks(text, true);
} else {
waitingForCharaterEnterRunnable = new Runnable() {
@Override
public void run() {
if (this == waitingForCharaterEnterRunnable) {
searchLinks(text, false);
waitingForCharaterEnterRunnable = null;
}
}
};
AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable, AndroidUtilities.WEB_URL == null ? 3000 : 1000);
}
}
}
@Override
public void onTextSpansChanged(CharSequence text) {
searchLinks(text, true);
}
@Override
public void needSendTyping() {
getMessagesController().sendTyping(dialog_id, threadMessageId, 0, classGuid);
}
@Override
public void onAttachButtonHidden() {
if (actionBar.isSearchFieldVisible()) {
return;
}
if (editTextItem != null) {
editTextItem.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(chatActivityEnterView.getSlowModeTimer())) {
if (headerItem != null) {
headerItem.setVisibility(View.GONE);
}
if (attachItem != null) {
attachItem.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onAttachButtonShow() {
if (actionBar.isSearchFieldVisible()) {
return;
}
if (headerItem != null) {
headerItem.setVisibility(View.VISIBLE);
}
if (editTextItem != null) {
editTextItem.setVisibility(View.GONE);
}
if (attachItem != null) {
attachItem.setVisibility(View.GONE);
}
}
@Override
public void onMessageEditEnd(boolean loading) {
if (chatListItemAnimator != null) {
chatActivityEnterViewAnimateFromTop = chatActivityEnterView.getBackgroundTop();
if (chatActivityEnterViewAnimateFromTop != 0) {
chatActivityEnterViewAnimateBeforeSending = true;
}
}
if (!loading) {
mentionsAdapter.setNeedBotContext(true);
if (editingMessageObject != null) {
AndroidUtilities.runOnUIThread(() -> hideFieldPanel(true), 30);
}
boolean waitingForKeyboard = false;
if (chatActivityEnterView.isPopupShowing()) {
chatActivityEnterView.setFieldFocused();
waitingForKeyboard = true;
}
chatActivityEnterView.setAllowStickersAndGifs(true, true, waitingForKeyboard);
if (editingMessageObjectReqId != 0) {
getConnectionsManager().cancelRequest(editingMessageObjectReqId, true);
editingMessageObjectReqId = 0;
}
updatePinnedMessageView(true);
updateBottomOverlay();
updateVisibleRows();
}
}
@Override
public void onWindowSizeChanged(int size) {
if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
allowStickersPanel = false;
if (stickersPanel.getVisibility() == View.VISIBLE) {
stickersPanel.setVisibility(View.INVISIBLE);
}
if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
mentionContainer.setVisibility(View.INVISIBLE);
updateMessageListAccessibilityVisibility();
}
} else {
allowStickersPanel = true;
if (stickersPanel.getVisibility() == View.INVISIBLE) {
stickersPanel.setVisibility(View.VISIBLE);
}
if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE && (!mentionsAdapter.isBotContext() || (allowContextBotPanel || allowContextBotPanelSecond))) {
mentionContainer.setVisibility(View.VISIBLE);
mentionContainer.setTag(null);
updateMessageListAccessibilityVisibility();
}
}
allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
checkContextBotPanel();
int size2 = size + (chatActivityEnterView.isPopupShowing() ? 1 << 16 : 0);
if (lastSize != size2) {
chatActivityEnterViewAnimateFromTop = 0;
chatActivityEnterViewAnimateBeforeSending = false;
}
lastSize = size2;
}
@Override
public void onStickersTab(boolean opened) {
if (emojiButtonRed != null) {
emojiButtonRed.setVisibility(View.GONE);
}
allowContextBotPanelSecond = !opened;
checkContextBotPanel();
}
@Override
public void didPressAttachButton() {
if (chatAttachAlert != null) {
chatAttachAlert.setEditingMessageObject(null);
}
openAttachMenu();
}
@Override
public void needStartRecordVideo(int state, boolean notify, int scheduleDate) {
if (instantCameraView != null) {
if (state == 0) {
instantCameraView.showCamera();
chatListView.stopScroll();
chatAdapter.updateRowsSafe();
} else if (state == 1 || state == 3 || state == 4) {
instantCameraView.send(state, notify, scheduleDate);
} else if (state == 2 || state == 5) {
instantCameraView.cancel(state == 2);
}
}
}
@Override
public void needChangeVideoPreviewState(int state, float seekProgress) {
if (instantCameraView != null) {
instantCameraView.changeVideoPreviewState(state, seekProgress);
}
}
@Override
public void needStartRecordAudio(int state) {
int visibility = state == 0 ? View.GONE : View.VISIBLE;
if (overlayView.getVisibility() != visibility) {
overlayView.setVisibility(visibility);
}
}
@Override
public void needShowMediaBanHint() {
showMediaBannedHint();
}
@Override
public void onStickersExpandedChange() {
checkRaiseSensors();
if (chatActivityEnterView.isStickersExpanded()) {
AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid);
if (Bulletin.getVisibleBulletin() != null && Bulletin.getVisibleBulletin().isShowing()) {
Bulletin.getVisibleBulletin().hide();
}
} else {
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
}
}
@Override
public void scrollToSendingMessage() {
int id = getSendMessagesHelper().getSendingMessageId(dialog_id);
if (id != 0) {
scrollToMessageId(id, 0, true, 0, true, 0);
}
}
@Override
public boolean hasScheduledMessages() {
return scheduledMessagesCount > 0 && chatMode == 0;
}
@Override
public void onSendLongClick() {
if (scheduledOrNoSoundHint != null) {
scheduledOrNoSoundHint.hide();
}
}
@Override
public void openScheduledMessages() {
ChatActivity.this.openScheduledMessages();
}
@Override
public void onAudioVideoInterfaceUpdated() {
updatePagedownButtonVisibility(true);
}
@Override
public void bottomPanelTranslationYChanged(float translation) {
if (translation != 0) {
wasManualScroll = true;
}
bottomPanelTranslationY = chatActivityEnterView.pannelAniamationInProgress() ? chatActivityEnterView.getEmojiPadding() - translation : 0;
bottomPanelTranslationYReverse = chatActivityEnterView.pannelAniamationInProgress() ? translation : 0;
chatActivityEnterView.setTranslationY(translation);
contentView.setEmojiOffset(chatActivityEnterView.pannelAniamationInProgress(), bottomPanelTranslationY);
translation += chatActivityEnterView.getTopViewTranslation();
chatListView.setTranslationY(translation);
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
updateTextureViewPosition(false);
contentView.invalidate();
updateBulletinLayout();
}
@Override
public void prepareMessageSending() {
waitingForSendingMessageLoad = true;
}
@Override
public void onTrendingStickersShowed(boolean show) {
if (show) {
AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid);
fragmentView.requestLayout();
} else {
AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
}
}
@Override
public boolean hasForwardingMessages() {
return forwardingMessages != null && !forwardingMessages.messages.isEmpty();
}
});
chatActivityEnterView.setDialogId(dialog_id, currentAccount);
if (chatInfo != null) {
chatActivityEnterView.setChatInfo(chatInfo);
}
chatActivityEnterView.setId(id_chat_compose_panel);
chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands, false);
chatActivityEnterView.setMinimumHeight(AndroidUtilities.dp(51));
chatActivityEnterView.setAllowStickersAndGifs(true, currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
if (inPreviewMode) {
chatActivityEnterView.setVisibility(View.INVISIBLE);
}
if (!ChatObject.isChannel(currentChat) || currentChat.megagroup) {
chatActivityEnterView.setBotInfo(botInfo);
}
contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
chatActivityEnterTopView = new ChatActivityEnterTopView(context) {
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
if (chatActivityEnterView != null) {
chatActivityEnterView.invalidate();
}
if (getVisibility() != GONE) {
hideHints(true);
if (chatListView != null) {
chatListView.setTranslationY(translationY);
}
if (progressView != null) {
progressView.setTranslationY(translationY);
}
if (mentionContainer != null) {
mentionContainer.setTranslationY(translationY);
}
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
if (fragmentView != null) {
fragmentView.invalidate();
}
}
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility == GONE) {
if (chatListView != null) {
chatListView.setTranslationY(0);
}
if (progressView != null) {
progressView.setTranslationY(0);
}
if (mentionContainer != null) {
mentionContainer.setTranslationY(0);
}
}
}
};
replyLineView = new View(context);
replyLineView.setBackgroundColor(getThemedColor(Theme.key_chat_replyPanelLine));
chatActivityEnterView.addTopView(chatActivityEnterTopView, replyLineView, 48);
final FrameLayout replyLayout = new FrameLayout(context);
chatActivityEnterTopView.addReplyView(replyLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, 0, 52, 0));
replyLayout.setOnClickListener(v -> {
if (forwardingMessages != null && !forwardingMessages.messages.isEmpty()) {
SharedConfig.forwardingOptionsHintHintShowed();
openForwardingPreview();
} else if (replyingMessageObject != null && (!isThreadChat() || replyingMessageObject.getId() != threadMessageId)) {
scrollToMessageId(replyingMessageObject.getId(), 0, true, 0, true, 0);
} else if (editingMessageObject != null) {
if (editingMessageObject.canEditMedia() && editingMessageObjectReqId == 0) {
if (chatAttachAlert == null) {
createChatAttachView();
}
chatAttachAlert.setEditingMessageObject(editingMessageObject);
openAttachMenu();
} else {
scrollToMessageId(editingMessageObject.getId(), 0, true, 0, true, 0);
}
}
});
replyIconImageView = new ImageView(context);
replyIconImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelIcons), PorterDuff.Mode.MULTIPLY));
replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));
replyCloseImageView = new ImageView(context);
replyCloseImageView.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelClose), PorterDuff.Mode.MULTIPLY));
replyCloseImageView.setImageResource(R.drawable.input_clear);
replyCloseImageView.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
replyCloseImageView.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_inappPlayerClose) & 0x19ffffff, 1, AndroidUtilities.dp(18)));
}
chatActivityEnterTopView.addView(replyCloseImageView, LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
replyCloseImageView.setOnClickListener(v -> {
if (forwardingMessages == null || forwardingMessages.messages.isEmpty()) {
showFieldPanel(false, null, null, null, foundWebPage, true, 0, true, true);
} else {
openAnotherForward();
}
});
replyNameTextView = new SimpleTextView(context);
replyNameTextView.setTextSize(14);
replyNameTextView.setTextColor(getThemedColor(Theme.key_chat_replyPanelName));
replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
replyLayout.addView(replyNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));
replyObjectTextView = new SimpleTextView(context);
replyObjectTextView.setTextSize(14);
replyObjectTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
replyLayout.addView(replyObjectTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0));
replyObjectHintTextView = new SimpleTextView(context);
replyObjectHintTextView.setTextSize(14);
replyObjectHintTextView.setTextColor(getThemedColor(Theme.key_windowBackgroundWhiteGrayText));
replyObjectHintTextView.setText(LocaleController.getString("TapForForwardingOptions", R.string.TapForForwardingOptions));
replyObjectHintTextView.setAlpha(0f);
replyLayout.addView(replyObjectHintTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 0, 0));
replyImageView = new BackupImageView(context);
replyImageView.setRoundRadius(AndroidUtilities.dp(2));
replyLayout.addView(replyImageView, LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));
stickersPanel = new FrameLayout(context);
stickersPanel.setVisibility(View.GONE);
contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));
final ChatActivityEnterTopView.EditView editView = new ChatActivityEnterTopView.EditView(context);
editView.setMotionEventSplittingEnabled(false);
editView.setOrientation(LinearLayout.HORIZONTAL);
editView.setOnClickListener(v -> {
if (editingMessageObject != null) {
scrollToMessageId(editingMessageObject.getId(), 0, true, 0, true, 0);
}
});
chatActivityEnterTopView.addEditView(editView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, 0, 48, 0));
for (int i = 0; i < 2; i++) {
final boolean firstButton = i == 0;
final ChatActivityEnterTopView.EditViewButton button = new ChatActivityEnterTopView.EditViewButton(context) {
@Override
public void setEditButton(boolean editButton) {
super.setEditButton(editButton);
if (firstButton) {
getTextView().setMaxWidth(editButton ? AndroidUtilities.dp(116) : Integer.MAX_VALUE);
}
}
@Override
public void updateColors() {
final int leftInset = firstButton ? AndroidUtilities.dp(14) : 0;
setBackground(Theme.createCircleSelectorDrawable(getThemedColor(Theme.key_chat_replyPanelName) & 0x19ffffff, leftInset, 0));
getImageView().setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_replyPanelName), PorterDuff.Mode.MULTIPLY));
getTextView().setTextColor(getThemedColor(Theme.key_chat_replyPanelName));
}
};
button.setOrientation(LinearLayout.HORIZONTAL);
ViewHelper.setPadding(button, 10, 0, 10, 0);
editView.addButton(button, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
final ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(firstButton ? R.drawable.msg_photoeditor : R.drawable.msg_replace);
button.addImageView(imageView, LayoutHelper.createLinear(24, LayoutHelper.MATCH_PARENT));
button.addView(new Space(context), LayoutHelper.createLinear(10, LayoutHelper.MATCH_PARENT));
final TextView textView = new TextView(context);
textView.setMaxLines(1);
textView.setSingleLine(true);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
textView.setEllipsize(TextUtils.TruncateAt.END);
button.addTextView(textView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT));
button.updateColors();
button.setOnClickListener(v -> {
if (editingMessageObject == null || !editingMessageObject.canEditMedia() || editingMessageObjectReqId != 0) {
return;
}
if (button.isEditButton()) {
openEditingMessageInPhotoEditor();
} else {
replyLayout.callOnClick();
}
});
}
stickersListView = new RecyclerListView(context, themeDelegate) {
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = ContentPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView, 0, contentPreviewViewerDelegate, themeDelegate);
return super.onInterceptTouchEvent(event) || result;
}
};
stickersListView.setTag(3);
stickersListView.setOnTouchListener((v, event) -> ContentPreviewViewer.getInstance().onTouch(event, stickersListView, 0, stickersOnItemClickListener, contentPreviewViewerDelegate, themeDelegate));
stickersListView.setDisallowInterceptTouchEvents(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
stickersListView.setLayoutManager(layoutManager);
stickersListView.setClipToPadding(false);
stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
initStickers();
stickersPanelArrow = new ImageView(context);
stickersPanelArrow.setImageResource(R.drawable.stickers_back_arrow);
stickersPanelArrow.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_stickersHintPanel), PorterDuff.Mode.MULTIPLY));
stickersPanel.addView(stickersPanelArrow, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 53, 0));
searchContainer = new FrameLayout(context) {
@Override
public void onDraw(Canvas canvas) {
int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
if (chatActivityEnterView.getVisibility() != View.VISIBLE) {
Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
Theme.chat_composeShadowDrawable.draw(canvas);
}
canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
}
@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
if (child == searchCountText) {
int leftMargin = 14;
if (searchCalendarButton != null && searchCalendarButton.getVisibility() != GONE) {
leftMargin += 48;
}
if (searchUserButton != null && searchUserButton.getVisibility() != GONE) {
leftMargin += 48;
}
((MarginLayoutParams) child.getLayoutParams()).leftMargin = AndroidUtilities.dp(leftMargin);
}
super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
};
searchContainer.setWillNotDraw(false);
searchContainer.setVisibility(View.INVISIBLE);
searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
searchContainer.setClipToPadding(false);
searchAsListTogglerView = new View(context);
searchAsListTogglerView.setOnTouchListener((v, event) -> getMediaDataController().getFoundMessageObjects().size() <= 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
searchAsListTogglerView.setBackground(Theme.getSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), false));
}
searchAsListTogglerView.setOnClickListener(v -> {
if (getMediaDataController().getFoundMessageObjects().size() > 1) {
if (searchAsListHint != null) {
searchAsListHint.hide();
}
toggleMesagesSearchListView();
if (!SharedConfig.searchMessagesAsListUsed) {
SharedConfig.setSearchMessagesAsListUsed(true);
}
}
});
final float paddingTop = Theme.chat_composeShadowDrawable.getIntrinsicHeight() / AndroidUtilities.density - 3f;
searchContainer.addView(searchAsListTogglerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.NO_GRAVITY, 0, paddingTop, 0, 0));
searchUpButton = new ImageView(context);
searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
searchUpButton.setImageResource(R.drawable.msg_go_up);
searchUpButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0));
searchUpButton.setOnClickListener(view -> {
getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1, threadMessageId, searchingUserMessages, searchingChatMessages);
showMessagesSearchListView(false);
if (!SharedConfig.searchMessagesAsListUsed && SharedConfig.searchMessagesAsListHintShows < 3 && !searchAsListHintShown && Math.random() <= 0.25) {
showSearchAsListHint();
searchAsListHintShown = true;
SharedConfig.increaseSearchAsListHintShows();
}
});
searchUpButton.setContentDescription(LocaleController.getString("AccDescrSearchNext", R.string.AccDescrSearchNext));
searchDownButton = new ImageView(context);
searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
searchDownButton.setImageResource(R.drawable.msg_go_down);
searchDownButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchContainer.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0));
searchDownButton.setOnClickListener(view -> {
getMediaDataController().searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2, threadMessageId, searchingUserMessages, searchingChatMessages);
showMessagesSearchListView(false);
});
searchDownButton.setContentDescription(LocaleController.getString("AccDescrSearchPrev", R.string.AccDescrSearchPrev));
if (currentChat != null && (!ChatObject.isChannel(currentChat) || currentChat.megagroup)) {
searchUserButton = new ImageView(context);
searchUserButton.setScaleType(ImageView.ScaleType.CENTER);
searchUserButton.setImageResource(R.drawable.msg_usersearch);
searchUserButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
searchUserButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchContainer.addView(searchUserButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
searchUserButton.setOnClickListener(view -> {
mentionLayoutManager.setReverseLayout(true);
mentionsAdapter.setSearchingMentions(true);
searchCalendarButton.setVisibility(View.GONE);
searchUserButton.setVisibility(View.GONE);
searchingForUser = true;
searchingUserMessages = null;
searchingChatMessages = null;
searchItem.setSearchFieldHint(LocaleController.getString("SearchMembers", R.string.SearchMembers));
searchItem.setSearchFieldCaption(LocaleController.getString("SearchFrom", R.string.SearchFrom));
AndroidUtilities.showKeyboard(searchItem.getSearchField());
searchItem.clearSearchText();
});
searchUserButton.setContentDescription(LocaleController.getString("AccDescrSearchByUser", R.string.AccDescrSearchByUser));
}
searchCalendarButton = new ImageView(context);
searchCalendarButton.setScaleType(ImageView.ScaleType.CENTER);
searchCalendarButton.setImageResource(R.drawable.msg_calendar);
searchCalendarButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_chat_searchPanelIcons), PorterDuff.Mode.MULTIPLY));
searchCalendarButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchContainer.addView(searchCalendarButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP));
searchCalendarButton.setOnClickListener(view -> {
if (getParentActivity() == null) {
return;
}
AndroidUtilities.hideKeyboard(searchItem.getSearchField());
showDialog(AlertsCreator.createCalendarPickerDialog(getParentActivity(), 1375315200000L, new MessagesStorage.IntCallback() {
@Override
public void run(int param) {
jumpToDate(param);
}
}, themeDelegate).create());
});
searchCalendarButton.setContentDescription(LocaleController.getString("JumpToDate", R.string.JumpToDate));
searchCountText = new SearchCounterView(context, themeDelegate);
searchCountText.setGravity(Gravity.LEFT);
searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 0, 108, 0));
bottomOverlay = new FrameLayout(context) {
@Override
public void onDraw(Canvas canvas) {
int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
Theme.chat_composeShadowDrawable.draw(canvas);
canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
}
};
bottomOverlay.setWillNotDraw(false);
bottomOverlay.setVisibility(View.INVISIBLE);
bottomOverlay.setFocusable(true);
bottomOverlay.setFocusableInTouchMode(true);
bottomOverlay.setClickable(true);
bottomOverlay.setPadding(0, AndroidUtilities.dp(2), 0, 0);
contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
bottomOverlayText = new TextView(context);
bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
bottomOverlayText.setGravity(Gravity.CENTER);
bottomOverlayText.setMaxLines(2);
bottomOverlayText.setEllipsize(TextUtils.TruncateAt.END);
bottomOverlayText.setLineSpacing(AndroidUtilities.dp(2), 1);
bottomOverlayText.setTextColor(getThemedColor(Theme.key_chat_secretChatStatusText));
bottomOverlay.addView(bottomOverlayText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 14, 0, 14, 0));
bottomOverlayChat = new ChatBlurredFrameLayout(context, this) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int allWidth = MeasureSpec.getSize(widthMeasureSpec);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) bottomOverlayChatText.getLayoutParams();
layoutParams.width = allWidth;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
Theme.chat_composeShadowDrawable.draw(canvas);
if (SharedConfig.chatBlurEnabled()) {
if (backgroundPaint == null) {
backgroundPaint = new Paint();
}
backgroundPaint.setColor(getThemedColor(Theme.key_chat_messagePanelBackground));
AndroidUtilities.rectTmp2.set(0, bottom, getMeasuredWidth(), getMeasuredHeight());
contentView.drawBlur(canvas, getY(), AndroidUtilities.rectTmp2, backgroundPaint, false);
} else {
canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), getThemedPaint(Theme.key_paint_chatComposeBackground));
}
super.dispatchDraw(canvas);
}
};
bottomOverlayChat.isTopView = false;
bottomOverlayChat.drawBlur = false;
bottomOverlayChat.setWillNotDraw(false);
bottomOverlayChat.setPadding(0, AndroidUtilities.dp(1.5f), 0, 0);
bottomOverlayChat.setVisibility(View.INVISIBLE);
bottomOverlayChat.setClipChildren(false);
contentView.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
bottomOverlayChatText = new UnreadCounterTextView(context);
bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 0, 1.5f, 0, 0));
bottomOverlayChatText.setOnClickListener(view -> {
if (getParentActivity() == null || pullingDownOffset != 0) {
return;
}
if (reportType >= 0) {
showDialog(new ReportAlert(getParentActivity(), reportType) {
@Override
protected void onSend(int type, String message) {
ArrayList<Integer> ids = new ArrayList<>();
for (int b = 0; b < selectedMessagesIds[0].size(); b++) {
ids.add(selectedMessagesIds[0].keyAt(b));
}
TLRPC.InputPeer peer = currentUser != null ? MessagesController.getInputPeer(currentUser) : MessagesController.getInputPeer(currentChat);
AlertsCreator.sendReport(peer, reportType, message, ids);
finishFragment();
chatActivityDelegate.onReport();
}
});
} else if (chatMode == MODE_PINNED) {
finishFragment();
chatActivityDelegate.onUnpin(true, bottomOverlayChatText.getTag() == null);
} else if (currentUser != null && userBlocked) {
if (currentUser.bot) {
String botUserLast = botUser;
botUser = null;
getMessagesController().unblockPeer(currentUser.id);
if (botUserLast != null && botUserLast.length() != 0) {
getMessagesController().sendBotStart(currentUser, botUserLast);
} else {
getSendMessagesHelper().sendMessage("/start", dialog_id, null, null, null, false, null, null, null, true, 0, null);
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity(), themeDelegate);
builder.setMessage(LocaleController.getString("AreYouSureUnblockContact", R.string.AreYouSureUnblockContact));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> getMessagesController().unblockPeer(currentUser.id));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
} else if (UserObject.isReplyUser(currentUser)) {
toggleMute(true);
} else if (currentUser != null && currentUser.bot && botUser != null) {
if (botUser.length() != 0) {
getMessagesController().sendBotStart(currentUser, botUser);
} else {
getSendMessagesHelper().sendMessage("/start", dialog_id, null, null, null, false, null, null, null, true, 0, null);
}
botUser = null;
updateBottomOverlay();
} else {
if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
if (ChatObject.isNotInChat(currentChat)) {
if (chatInviteRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(chatInviteRunnable);
chatInviteRunnable = null;
}
showBottomOverlayProgress(true, true);
getMessagesController().addUserToChat(currentChat.id, getUserConfig().getCurrentUser(), 0, null, ChatActivity.this, null);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.closeSearchByActiveAction);
if (hasReportSpam() && reportSpamButton.getTag(R.id.object_tag) != null) {
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
preferences.edit().putInt("dialog_bar_vis3" + dialog_id, 3).commit();
getNotificationCenter().postNotificationName(NotificationCenter.peerSettingsDidLoad, dialog_id);
}
} else {
toggleMute(true);
}
} else {
AlertsCreator.createClearOrDeleteDialogAlert(ChatActivity.this, false, currentChat, currentUser, currentEncryptedChat != null, true, (param) -> {
getNotificationCenter().removeObserver(ChatActivity.this, NotificationCenter.closeChats);
getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
finishFragment();
getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, dialog_id, currentUser, currentChat, param);
}, themeDelegate);
}
}
});
bottomOverlayProgress = new RadialProgressView(context, themeDelegate);
bottomOverlayProgress.setSize(AndroidUtilities.dp(22));
bottomOverlayProgress.setProgressColor(getThemedColor(Theme.key_chat_fieldOverlayText));
bottomOverlayProgress.setVisibility(View.INVISIBLE);
bottomOverlayProgress.setScaleX(0.1f);
bottomOverlayProgress.setScaleY(0.1f);
bottomOverlayProgress.setAlpha(1.0f);
bottomOverlayChat.addView(bottomOverlayProgress, LayoutHelper.createFrame(30, 30, Gravity.CENTER));
bottomOverlayImage = new ImageView(context);
int color = getThemedColor(Theme.key_chat_fieldOverlayText);
bottomOverlayImage.setImageResource(R.drawable.log_info);
bottomOverlayImage.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
bottomOverlayImage.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
bottomOverlayImage.setBackgroundDrawable(Theme.createSelectorDrawable(Color.argb(24, Color.red(color), Color.green(color), Color.blue(color)), 1));
}
bottomOverlayChat.addView(bottomOverlayImage, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 3, 1.5f, 0, 0));
bottomOverlayImage.setContentDescription(LocaleController.getString("SettingsHelp", R.string.SettingsHelp));
bottomOverlayImage.setOnClickListener(v -> undoView.showWithAction(dialog_id, UndoView.ACTION_TEXT_INFO, LocaleController.getString("BroadcastGroupInfo", R.string.BroadcastGroupInfo)));
replyButton = new TextView(context);
replyButton.setText(LocaleController.getString("Reply", R.string.Reply));
replyButton.setGravity(Gravity.CENTER_VERTICAL);
replyButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
replyButton.setPadding(AndroidUtilities.dp(14), 0, AndroidUtilities.dp(21), 0);
replyButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3));
replyButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
replyButton.setCompoundDrawablePadding(AndroidUtilities.dp(7));
replyButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
Drawable image = context.getResources().getDrawable(R.drawable.input_reply).mutate();
image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY));
replyButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
replyButton.setOnClickListener(v -> {
MessageObject messageObject = null;
for (int a = 1; a >= 0; a--) {
if (messageObject == null && selectedMessagesIds[a].size() != 0) {
messageObject = messagesDict[a].get(selectedMessagesIds[a].keyAt(0));
}
selectedMessagesIds[a].clear();
selectedMessagesCanCopyIds[a].clear();
selectedMessagesCanStarIds[a].clear();
}
hideActionMode();
if (messageObject != null && (messageObject.messageOwner.id > 0 || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
showFieldPanelForReply(messageObject);
}
updatePinnedMessageView(true);
updateVisibleRows();
});
bottomMessagesActionContainer.addView(replyButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
forwardButton = new TextView(context);
forwardButton.setText(LocaleController.getString("Forward", R.string.Forward));
forwardButton.setGravity(Gravity.CENTER_VERTICAL);
forwardButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
forwardButton.setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
forwardButton.setCompoundDrawablePadding(AndroidUtilities.dp(6));
forwardButton.setBackgroundDrawable(Theme.createSelectorDrawable(getThemedColor(Theme.key_actionBarActionModeDefaultSelector), 3));
forwardButton.setTextColor(getThemedColor(Theme.key_actionBarActionModeDefaultIcon));
forwardButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
image = context.getResources().getDrawable(R.drawable.input_forward).mutate();
image.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_actionBarActionModeDefaultIcon), PorterDuff.Mode.MULTIPLY));
forwardButton.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
forwardButton.setOnClickListener(v -> openForward(false));
bottomMessagesActionContainer.addView(forwardButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP));
contentView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
contentView.addView(messageEnterTransitionContainer = new MessageEnterTransitionContainer(contentView, currentAccount));
undoView = new UndoView(context, this, false, themeDelegate);
undoView.setAdditionalTranslationY(AndroidUtilities.dp(51));
contentView.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
if (currentChat != null) {
slowModeHint = new HintView(getParentActivity(), 2, themeDelegate);
slowModeHint.setAlpha(0.0f);
slowModeHint.setVisibility(View.INVISIBLE);
contentView.addView(slowModeHint, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 19, 0, 19, 0));
}
chatAdapter.updateRowsSafe();
if (loading && messages.isEmpty()) {
showProgressView(chatAdapter.botInfoRow < 0);
chatListView.setEmptyView(null);
} else {
showProgressView(false);
chatListView.setEmptyView(emptyViewContainer);
}
checkBotKeyboard();
updateBottomOverlay();
updateSecretStatus();
updateTopPanel(false);
updatePinnedMessageView(false);
updateInfoTopView(false);
chatScrollHelper = new RecyclerAnimationScrollHelper(chatListView, chatLayoutManager);
chatScrollHelper.setScrollListener(this::invalidateMessagesVisiblePart);
chatScrollHelper.setAnimationCallback(chatScrollHelperCallback);
if (currentEncryptedChat != null && (SharedConfig.passcodeHash.length() == 0 || SharedConfig.allowScreenCapture)) {
unregisterFlagSecurePasscode = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
}
if (getMessagesController().isChatNoForwards(currentChat)) {
unregisterFlagSecureNoforwards = AndroidUtilities.registerFlagSecure(getParentActivity().getWindow());
}
if (oldMessage != null) {
chatActivityEnterView.setFieldText(oldMessage);
}
fixLayoutInternal();
textSelectionHelper.setCallback(new TextSelectionHelper.Callback() {
@Override
public void onStateChanged(boolean isSelected) {
swipeBackEnabled = !isSelected;
if (isSelected) {
if (slidingView != null) {
slidingView.setSlidingOffset(0);
slidingView = null;
}
maybeStartTrackingSlidingView = false;
startedTrackingSlidingView = false;
if (textSelectionHint != null) {
textSelectionHint.hide();
}
}
updatePagedownButtonVisibility(true);
}
@Override
public void onTextCopied() {
if (actionBar != null && actionBar.isActionModeShowed()) {
clearSelectionMode();
}
undoView.showWithAction(0, UndoView.ACTION_TEXT_COPIED, null);
}
});
contentView.addView(textSelectionHelper.getOverlayView(context));
fireworksOverlay = new FireworksOverlay(context);
contentView.addView(fireworksOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
textSelectionHelper.setParentView(chatListView);
long searchFromUserId = getArguments().getInt("search_from_user_id", 0);
long searchFromChatId = getArguments().getInt("search_from_chat_id", 0);
if (searchFromUserId != 0) {
TLRPC.User user = getMessagesController().getUser(searchFromUserId);
if (user != null) {
openSearchWithText("");
searchUserButton.callOnClick();
searchUserMessages(user, null);
}
} else if (searchFromChatId != 0) {
TLRPC.Chat chat = getMessagesController().getChat(searchFromChatId);
if (chat != null) {
openSearchWithText("");
searchUserButton.callOnClick();
searchUserMessages(null, chat);
}
}
if (replyingMessageObject != null) {
chatActivityEnterView.setReplyingMessageObject(replyingMessageObject);
}
ViewGroup decorView;
if (Build.VERSION.SDK_INT >= 21) {
decorView = (ViewGroup) getParentActivity().getWindow().getDecorView();
} else {
decorView = contentView;
}
pinchToZoomHelper = new PinchToZoomHelper(decorView, contentView) {
@Override
protected void drawOverlays(Canvas canvas, float alpha, float parentOffsetX, float parentOffsetY, float clipTop, float clipBottom) {
if (alpha > 0) {
View view = getChild();
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
int top = (int) Math.max(clipTop, parentOffsetY);
int bottom = (int) Math.min(clipBottom, parentOffsetY + cell.getMeasuredHeight());
AndroidUtilities.rectTmp.set(parentOffsetX, top, parentOffsetX + cell.getMeasuredWidth(), bottom);
canvas.saveLayerAlpha(AndroidUtilities.rectTmp, (int) (255 * alpha), Canvas.ALL_SAVE_FLAG);
canvas.translate(parentOffsetX, parentOffsetY);
cell.drawFromPinchToZoom = true;
cell.drawOverlays(canvas);
if (cell.shouldDrawTimeOnMedia() && cell.getCurrentMessagesGroup() == null) {
cell.drawTime(canvas, 1f, false);
}
cell.drawFromPinchToZoom = false;
canvas.restore();
}
}
}
};
pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {
@Override
public TextureView getCurrentTextureView() {
return videoTextureView;
}
@Override
public void onZoomStarted(MessageObject messageObject) {
chatListView.cancelClickRunnables(true);
chatListView.stopScroll();
if (MediaController.getInstance().isPlayingMessage(messageObject)) {
contentView.removeView(videoPlayerContainer);
videoPlayerContainer = null;
videoTextureView = null;
aspectRatioFrameLayout = null;
}
for (int i = 0; i < chatListView.getChildCount(); i++) {
if (chatListView.getChildAt(i) instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) chatListView.getChildAt(i);
if (cell.getMessageObject().getId() == messageObject.getId()) {
cell.getPhotoImage().setVisible(false, true);
}
}
}
}
@Override
public void onZoomFinished(MessageObject messageObject) {
if (messageObject == null) {
return;
}
if (MediaController.getInstance().isPlayingMessage(messageObject)) {
for (int i = 0; i < chatListView.getChildCount(); i++) {
if (chatListView.getChildAt(i) instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) chatListView.getChildAt(i);
if (cell.getMessageObject().getId() == messageObject.getId()) {
AnimatedFileDrawable animation = cell.getPhotoImage().getAnimation();
if (animation.isRunning()) {
animation.stop();
}
if (animation != null) {
Bitmap bitmap = animation.getAnimatedBitmap();
if (bitmap != null) {
try {
Bitmap src = pinchToZoomHelper.getVideoBitmap(bitmap.getWidth(), bitmap.getHeight());
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
src.recycle();
} catch (Throwable e) {
FileLog.e(e);
}
}
}
}
}
}
createTextureView(true);
MediaController.getInstance().setTextureView(videoTextureView, aspectRatioFrameLayout, videoPlayerContainer, true);
}
chatListView.invalidate();
}
});
pinchToZoomHelper.setClipBoundsListener(topBottom -> {
topBottom[1] = chatListView.getBottom();
topBottom[0] = chatListView.getTop() + chatListViewPaddingTop - AndroidUtilities.dp(4);
});
emojiAnimationsOverlay = new EmojiAnimationsOverlay(ChatActivity.this, contentView, chatListView, currentAccount, dialog_id, threadMessageId);
actionBar.setDrawBlurBackground(contentView);
TLRPC.Dialog dialog = getMessagesController().dialogs_dict.get(dialog_id);
if (dialog != null) {
reactionsMentionCount = dialog.unread_reactions_count;
updateReactionsMentionButton(false);
}
return fragmentView;
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class ChatActivity method updatePinnedMessageView.
private void updatePinnedMessageView(boolean animated, int animateToNext) {
if (pinnedMessageView == null || chatMode != 0 || inMenuMode) {
return;
}
int pinned_msg_id;
boolean changed = false;
MessageObject pinnedMessageObject;
if (isThreadChat()) {
if (!threadMessageVisible) {
pinnedMessageObject = threadMessageObject;
pinned_msg_id = threadMessageId;
} else {
pinnedMessageObject = null;
pinned_msg_id = 0;
}
} else if (currentPinnedMessageId != 0 && !pinnedMessageIds.isEmpty()) {
pinnedMessageObject = pinnedMessageObjects.get(currentPinnedMessageId);
if (pinnedMessageObject == null) {
pinnedMessageObject = messagesDict[0].get(currentPinnedMessageId);
}
pinned_msg_id = currentPinnedMessageId;
} else {
pinnedMessageObject = null;
pinned_msg_id = 0;
}
SharedPreferences preferences = MessagesController.getNotificationsSettings(currentAccount);
if (threadMessageObject == null && (chatInfo == null && userInfo == null || pinned_msg_id == 0 || !pinnedMessageIds.isEmpty() && pinnedMessageIds.get(0) == preferences.getInt("pin_" + dialog_id, 0)) || reportType >= 0 || actionBar != null && (actionBar.isActionModeShowed() || actionBar.isSearchFieldVisible())) {
changed = hidePinnedMessageView(animated);
} else {
updatePinnedListButton(animated);
if (pinnedMessageObject != null) {
if (pinnedMessageView.getTag() != null) {
pinnedMessageView.setTag(null);
changed = true;
if (pinnedMessageViewAnimator != null) {
pinnedMessageViewAnimator.cancel();
pinnedMessageViewAnimator = null;
}
if (animated) {
ValueAnimator animator = ValueAnimator.ofFloat(pinnedMessageEnterOffset, 0);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int position = -1;
@Override
public void onAnimationUpdate(ValueAnimator animation) {
pinnedMessageEnterOffset = (float) animation.getAnimatedValue();
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
}
});
pinnedMessageView.setVisibility(View.VISIBLE);
pinnedMessageViewAnimator = new AnimatorSet();
pinnedMessageViewAnimator.playTogether(animator);
pinnedMessageViewAnimator.setDuration(200);
pinnedMessageViewAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (pinnedMessageViewAnimator != null && pinnedMessageViewAnimator.equals(animation)) {
pinnedMessageViewAnimator = null;
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (pinnedMessageViewAnimator != null && pinnedMessageViewAnimator.equals(animation)) {
pinnedMessageViewAnimator = null;
}
}
});
pinnedMessageViewAnimator.start();
} else {
pinnedMessageEnterOffset = 0;
invalidateChatListViewTopPadding();
invalidateMessagesVisiblePart();
pinnedMessageView.setVisibility(View.VISIBLE);
}
}
for (int a = 0; a < pinnedNextAnimation.length; a++) {
if (pinnedNextAnimation[a] != null) {
pinnedNextAnimation[a].cancel();
pinnedNextAnimation[a] = null;
}
}
setPinnedTextTranslationX = false;
SimpleTextView nameTextView = pinnedNameTextView[animateToNext != 0 && loadedPinnedMessagesCount == 2 ? 1 : 0];
SimpleTextView messageTextView = pinnedMessageTextView[animateToNext != 0 ? 1 : 0];
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) pinnedNameTextView[0].getLayoutParams();
FrameLayout.LayoutParams layoutParams2 = (FrameLayout.LayoutParams) pinnedNameTextView[1].getLayoutParams();
FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) pinnedCounterTextView.getLayoutParams();
FrameLayout.LayoutParams layoutParams4 = (FrameLayout.LayoutParams) pinnedMessageTextView[0].getLayoutParams();
FrameLayout.LayoutParams layoutParams5 = (FrameLayout.LayoutParams) pinnedMessageTextView[1].getLayoutParams();
int cacheType = 1;
int size = 0;
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(pinnedMessageObject.photoThumbs2, AndroidUtilities.dp(320));
TLRPC.PhotoSize thumbPhotoSize = FileLoader.getClosestPhotoSizeWithSize(pinnedMessageObject.photoThumbs2, AndroidUtilities.dp(40));
TLObject photoSizeObject = pinnedMessageObject.photoThumbsObject2;
if (photoSize == null) {
if (pinnedMessageObject.mediaExists) {
photoSize = FileLoader.getClosestPhotoSizeWithSize(pinnedMessageObject.photoThumbs, AndroidUtilities.getPhotoSize());
if (photoSize != null) {
size = photoSize.size;
}
cacheType = 0;
} else {
photoSize = FileLoader.getClosestPhotoSizeWithSize(pinnedMessageObject.photoThumbs, AndroidUtilities.dp(320));
}
thumbPhotoSize = FileLoader.getClosestPhotoSizeWithSize(pinnedMessageObject.photoThumbs, AndroidUtilities.dp(40));
photoSizeObject = pinnedMessageObject.photoThumbsObject;
}
if (photoSize == thumbPhotoSize) {
thumbPhotoSize = null;
}
boolean noImage;
int prevMargin = layoutParams1.leftMargin;
if (noImage = (photoSize == null || photoSize instanceof TLRPC.TL_photoSizeEmpty || photoSize.location instanceof TLRPC.TL_fileLocationUnavailable || pinnedMessageObject.isAnyKindOfSticker() || pinnedMessageObject.isSecretMedia())) {
pinnedImageLocation = null;
pinnedImageLocationObject = null;
if (animateToNext == 0) {
pinnedMessageImageView[0].setImageBitmap(null);
pinnedMessageImageView[0].setVisibility(View.INVISIBLE);
}
layoutParams1.leftMargin = layoutParams2.leftMargin = layoutParams3.leftMargin = layoutParams4.leftMargin = layoutParams5.leftMargin = AndroidUtilities.dp(18);
} else {
if (pinnedMessageObject.isRoundVideo()) {
pinnedMessageImageView[1].setRoundRadius(AndroidUtilities.dp(16));
} else {
pinnedMessageImageView[1].setRoundRadius(AndroidUtilities.dp(2));
}
pinnedImageSize = size;
pinnedImageCacheType = cacheType;
pinnedImageLocation = photoSize;
pinnedImageThumbLocation = thumbPhotoSize;
pinnedImageLocationObject = photoSizeObject;
pinnedMessageImageView[1].setImage(ImageLocation.getForObject(pinnedImageLocation, photoSizeObject), "50_50", ImageLocation.getForObject(thumbPhotoSize, photoSizeObject), "50_50_b", null, size, cacheType, pinnedMessageObject);
pinnedMessageImageView[1].setVisibility(View.VISIBLE);
if (animateToNext != 0) {
pinnedMessageImageView[1].setAlpha(0.0f);
}
layoutParams1.leftMargin = layoutParams2.leftMargin = layoutParams3.leftMargin = layoutParams4.leftMargin = layoutParams5.leftMargin = AndroidUtilities.dp(55);
}
pinnedNameTextView[0].setLayoutParams(layoutParams1);
pinnedNameTextView[1].setLayoutParams(layoutParams2);
pinnedCounterTextView.setLayoutParams(layoutParams3);
pinnedMessageTextView[0].setLayoutParams(layoutParams4);
pinnedMessageTextView[1].setLayoutParams(layoutParams5);
if (threadMessageId != 0) {
MessagesController messagesController = getMessagesController();
TLRPC.MessageFwdHeader fwd_from = threadMessageObject.messageOwner.fwd_from;
TLRPC.User user = null;
TLRPC.Chat chat = null;
if (fwd_from != null && fwd_from.saved_from_peer != null) {
if (fwd_from.saved_from_peer.user_id != 0) {
if (fwd_from.from_id instanceof TLRPC.TL_peerUser) {
user = messagesController.getUser(fwd_from.from_id.user_id);
} else {
user = messagesController.getUser(fwd_from.saved_from_peer.user_id);
}
} else if (fwd_from.saved_from_peer.channel_id != 0) {
if (threadMessageObject.isSavedFromMegagroup() && fwd_from.from_id instanceof TLRPC.TL_peerUser) {
user = messagesController.getUser(fwd_from.from_id.user_id);
} else {
chat = messagesController.getChat(fwd_from.saved_from_peer.channel_id);
}
} else if (fwd_from.saved_from_peer.chat_id != 0) {
if (fwd_from.from_id instanceof TLRPC.TL_peerUser) {
user = messagesController.getUser(fwd_from.from_id.user_id);
} else if (fwd_from.from_id instanceof TLRPC.TL_peerChat) {
chat = messagesController.getChat(fwd_from.from_id.chat_id);
} else if (fwd_from.from_id instanceof TLRPC.TL_peerChannel) {
chat = messagesController.getChat(fwd_from.from_id.channel_id);
} else {
chat = messagesController.getChat(fwd_from.saved_from_peer.chat_id);
}
}
} else if (threadMessageObject.isFromUser()) {
user = messagesController.getUser(threadMessageObject.messageOwner.from_id.user_id);
} else if (threadMessageObject.messageOwner.from_id instanceof TLRPC.TL_peerChannel) {
chat = messagesController.getChat(threadMessageObject.messageOwner.from_id.channel_id);
} else if (threadMessageObject.messageOwner.from_id instanceof TLRPC.TL_peerChat) {
chat = messagesController.getChat(threadMessageObject.messageOwner.from_id.chat_id);
} else if (threadMessageObject.messageOwner.post) {
chat = messagesController.getChat(threadMessageObject.messageOwner.peer_id.channel_id);
}
if (user != null) {
nameTextView.setText(ContactsController.formatName(user.first_name, user.last_name));
} else if (chat != null) {
nameTextView.setText(chat.title);
}
} else {
if (currentPinnedMessageIndex[0] == 0 || loadedPinnedMessagesCount != 2) {
nameTextView.setText(LocaleController.getString("PinnedMessage", R.string.PinnedMessage));
} else {
nameTextView.setText(LocaleController.getString("PreviousPinnedMessage", R.string.PreviousPinnedMessage));
}
if (currentPinnedMessageIndex[0] != 0) {
int total = getPinnedMessagesCount();
pinnedCounterTextView.setNumber(Math.min(total - 1, Math.max(1, total - currentPinnedMessageIndex[0])), animated && pinnedCounterTextView.getTag() == null);
}
}
CharSequence pinnedText = null;
if (pinnedMessageObject.type == 14) {
pinnedText = String.format("%s - %s", pinnedMessageObject.getMusicAuthor(), pinnedMessageObject.getMusicTitle());
} else if (pinnedMessageObject.type == MessageObject.TYPE_POLL) {
TLRPC.TL_messageMediaPoll poll = (TLRPC.TL_messageMediaPoll) pinnedMessageObject.messageOwner.media;
String mess = poll.poll.question;
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
mess = mess.replace('\n', ' ');
pinnedText = mess;
} else if (pinnedMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
pinnedText = Emoji.replaceEmoji(pinnedMessageObject.messageOwner.media.game.title, messageTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false);
} else if (!TextUtils.isEmpty(pinnedMessageObject.caption)) {
String mess = pinnedMessageObject.caption.toString();
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
mess = mess.replace('\n', ' ');
pinnedText = Emoji.replaceEmoji(mess, messageTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false);
} else if (pinnedMessageObject.messageText != null) {
String mess = pinnedMessageObject.messageText.toString();
if (mess.length() > 150) {
mess = mess.substring(0, 150);
}
mess = mess.replace('\n', ' ');
pinnedText = Emoji.replaceEmoji(mess, messageTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(14), false);
}
if (pinnedText != null) {
if (pinnedText instanceof Spannable)
MediaDataController.addTextStyleRuns(pinnedMessageObject, (Spannable) pinnedText);
messageTextView.setText(pinnedText);
}
if (animateToNext != 0) {
pinnedNextAnimation[0] = new AnimatorSet();
pinnedNextAnimation[1] = new AnimatorSet();
ArrayList<Animator> animators = new ArrayList<>();
ArrayList<Animator> animators2 = new ArrayList<>();
messageTextView.setVisibility(View.VISIBLE);
nameTextView.setVisibility(View.VISIBLE);
if (loadedPinnedMessagesCount == 2 || currentPinnedMessageIndex[0] == 0) {
if (pinnedCounterTextView.getTag() == null) {
animators.add(ObjectAnimator.ofFloat(pinnedCounterTextView, View.ALPHA, 1.0f, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedCounterTextView, View.TRANSLATION_Y, 0.0f, -AndroidUtilities.dp(4)));
pinnedCounterTextView.setTag(1);
}
} else {
if (pinnedCounterTextView.getTag() != null) {
pinnedCounterTextView.setVisibility(View.VISIBLE);
pinnedCounterTextView.setAlpha(0.0f);
animators.add(ObjectAnimator.ofFloat(pinnedCounterTextView, View.ALPHA, 0.0f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedCounterTextView, View.TRANSLATION_Y, -AndroidUtilities.dp(4), 0));
pinnedCounterTextView.setTag(null);
}
}
if (loadedPinnedMessagesCount == 2 && !TextUtils.equals(nameTextView.getText(), pinnedNameTextView[0].getText())) {
nameTextView.setAlpha(0);
animators.add(ObjectAnimator.ofFloat(nameTextView, View.ALPHA, 0.0f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedNameTextView[0], View.ALPHA, 1.0f, 0.0f));
animators.add(ObjectAnimator.ofFloat(nameTextView, View.TRANSLATION_Y, AndroidUtilities.dp(animateToNext == 2 ? 4 : -4), 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedNameTextView[0], View.TRANSLATION_Y, 0.0f, AndroidUtilities.dp(animateToNext == 2 ? -4 : 4)));
} else {
if (nameTextView != pinnedNameTextView[0]) {
nameTextView.setAlpha(1.0f);
pinnedNameTextView[0].setAlpha(0.0f);
nameTextView.setTranslationY(0.0f);
pinnedNameTextView[0].setTranslationY(0.0f);
} else {
nameTextView.setAlpha(1.0f);
nameTextView.setTranslationY(0.0f);
pinnedNameTextView[1].setTranslationY(0.0f);
pinnedNameTextView[1].setAlpha(0.0f);
}
}
boolean animateText;
if (!TextUtils.equals(messageTextView.getText(), pinnedMessageTextView[0].getText())) {
messageTextView.setAlpha(0);
animators.add(ObjectAnimator.ofFloat(messageTextView, View.ALPHA, 0.0f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageTextView[0], View.ALPHA, 1.0f, 0.0f));
if (animateText = forceScrollToFirst && loadedPinnedMessagesCount > 5) {
animators2.add(ObjectAnimator.ofFloat(messageTextView, View.TRANSLATION_Y, AndroidUtilities.dp(4), AndroidUtilities.dp(-2)));
} else {
animators.add(ObjectAnimator.ofFloat(messageTextView, View.TRANSLATION_Y, AndroidUtilities.dp(animateToNext == 2 ? 4 : -4), 0.0f));
}
animators.add(ObjectAnimator.ofFloat(pinnedMessageTextView[0], View.TRANSLATION_Y, 0.0f, AndroidUtilities.dp(animateToNext == 2 ? -4 : 4)));
} else {
animateText = false;
messageTextView.setAlpha(1.0f);
pinnedMessageTextView[0].setAlpha(0.0f);
messageTextView.setTranslationY(0.0f);
pinnedMessageTextView[0].setTranslationY(0.0f);
}
BackupImageView animateImage;
if (layoutParams1.leftMargin != prevMargin) {
animateImage = null;
setPinnedTextTranslationX = true;
int diff = prevMargin - layoutParams1.leftMargin;
animators.add(ObjectAnimator.ofFloat(pinnedMessageTextView[0], View.TRANSLATION_X, diff, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageTextView[1], View.TRANSLATION_X, diff, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedNameTextView[0], View.TRANSLATION_X, diff, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedNameTextView[1], View.TRANSLATION_X, diff, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedCounterTextView, View.TRANSLATION_X, pinnedCounterTextViewX + diff, pinnedCounterTextViewX));
if (diff > 0) {
pinnedMessageImageView[0].setAlpha(1f);
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[0], View.ALPHA, 1.0f, 0.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[0], View.SCALE_X, 1.0f, 0.7f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[0], View.SCALE_Y, 1.0f, 0.7f));
} else {
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.ALPHA, 0.0f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.SCALE_X, 0.7f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.SCALE_Y, 0.7f, 1.0f));
}
} else {
setPinnedTextTranslationX = false;
messageTextView.setTranslationX(0);
pinnedMessageTextView[0].setTranslationX(0);
nameTextView.setTranslationX(0);
pinnedNameTextView[0].setTranslationX(0);
pinnedCounterTextView.setTranslationX(pinnedCounterTextViewX);
pinnedMessageImageView[1].setAlpha(1.0f);
if (!noImage) {
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.ALPHA, 0.0f, 1.0f));
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[0], View.ALPHA, 1.0f, 0.0f));
if (forceScrollToFirst && loadedPinnedMessagesCount > 5) {
animateImage = pinnedMessageImageView[1];
animators2.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.TRANSLATION_Y, AndroidUtilities.dp(3), AndroidUtilities.dp(-2)));
} else {
animateImage = null;
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[1], View.TRANSLATION_Y, AndroidUtilities.dp(animateToNext == 2 ? 3 : -3), 0.0f));
}
animators.add(ObjectAnimator.ofFloat(pinnedMessageImageView[0], View.TRANSLATION_Y, 0.0f, AndroidUtilities.dp(animateToNext == 2 ? -3 : 3)));
} else {
animateImage = null;
}
}
pinnedNextAnimation[1].addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
pinnedNextAnimation[1] = null;
pinnedMessageImageView[1].setTranslationY(0);
}
@Override
public void onAnimationEnd(Animator animation) {
if (animation.equals(pinnedNextAnimation[1])) {
if (animateText || animateImage != null) {
pinnedNextAnimation[1] = new AnimatorSet();
pinnedNextAnimation[1].setInterpolator(CubicBezierInterpolator.EASE_OUT);
pinnedNextAnimation[1].setDuration(180);
ArrayList<Animator> animators1 = new ArrayList<>();
if (animateText) {
animators1.add(ObjectAnimator.ofFloat(messageTextView, View.TRANSLATION_Y, 0.0f));
}
if (animateImage != null) {
animators1.add(ObjectAnimator.ofFloat(animateImage, View.TRANSLATION_Y, 0.0f));
}
pinnedNextAnimation[1].addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (animateText) {
messageTextView.setTranslationY(0.0f);
}
if (animateImage != null) {
animateImage.setTranslationY(0.0f);
}
pinnedNextAnimation[1] = null;
}
});
pinnedNextAnimation[1].playTogether(animators1);
pinnedNextAnimation[1].start();
} else {
pinnedNextAnimation[1] = null;
}
}
}
});
pinnedNextAnimation[1].setDuration(180);
if (forceScrollToFirst && loadedPinnedMessagesCount > 5) {
pinnedNextAnimation[1].setInterpolator(CubicBezierInterpolator.EASE_OUT);
}
pinnedNextAnimation[1].playTogether(animators2);
pinnedNextAnimation[0].playTogether(animators);
pinnedNextAnimation[0].addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (pinnedCounterTextView.getTag() != null) {
pinnedCounterTextView.setVisibility(View.INVISIBLE);
int total = getPinnedMessagesCount();
pinnedCounterTextView.setNumber(Math.min(total - 1, Math.max(1, total - currentPinnedMessageIndex[0])), false);
} else {
pinnedCounterTextView.setAlpha(1.0f);
}
pinnedCounterTextView.setTranslationY(0.0f);
pinnedMessageTextView[0].setTranslationX(0);
pinnedMessageTextView[1].setTranslationX(0);
pinnedCounterTextView.setTranslationX(pinnedCounterTextViewX);
if (!animateText) {
messageTextView.setTranslationY(0.0f);
}
nameTextView.setTranslationY(0.0f);
pinnedNameTextView[0].setTranslationX(0);
pinnedNameTextView[1].setTranslationX(0);
pinnedMessageImageView[1].setAlpha(1.0f);
pinnedMessageImageView[1].setScaleX(1f);
pinnedMessageImageView[1].setScaleY(1f);
pinnedMessageImageView[0].setAlpha(1.0f);
pinnedMessageImageView[0].setScaleX(1f);
pinnedMessageImageView[0].setScaleY(1f);
pinnedMessageTextView[1] = pinnedMessageTextView[0];
pinnedMessageTextView[0] = messageTextView;
pinnedMessageTextView[1].setVisibility(View.INVISIBLE);
if (nameTextView != pinnedNameTextView[0]) {
pinnedNameTextView[1] = pinnedNameTextView[0];
pinnedNameTextView[0] = nameTextView;
pinnedNameTextView[1].setVisibility(View.INVISIBLE);
}
if (noImage) {
pinnedMessageImageView[1].setImageBitmap(null);
pinnedMessageImageView[1].setVisibility(View.INVISIBLE);
}
BackupImageView backupImageView = pinnedMessageImageView[1];
pinnedMessageImageView[1] = pinnedMessageImageView[0];
pinnedMessageImageView[0] = backupImageView;
pinnedMessageImageView[1].setAlpha(1.0f);
pinnedMessageImageView[1].setScaleX(1f);
pinnedMessageImageView[1].setScaleY(1f);
pinnedMessageImageView[1].setVisibility(View.INVISIBLE);
pinnedNextAnimation[0] = null;
setPinnedTextTranslationX = false;
}
});
pinnedNextAnimation[0].setDuration(180);
if (!setPinnedTextTranslationX) {
pinnedNextAnimation[0].start();
pinnedNextAnimation[1].start();
}
} else {
if (loadedPinnedMessagesCount == 2 || currentPinnedMessageIndex[0] == 0) {
if (pinnedCounterTextView.getTag() == null) {
pinnedCounterTextView.setAlpha(0.0f);
pinnedCounterTextView.setVisibility(View.INVISIBLE);
pinnedCounterTextView.setTag(1);
}
} else {
if (pinnedCounterTextView.getTag() != null) {
pinnedCounterTextView.setVisibility(View.VISIBLE);
pinnedCounterTextView.setAlpha(1.0f);
pinnedCounterTextView.setTag(null);
}
}
pinnedCounterTextView.setTranslationY(0.0f);
pinnedCounterTextView.setTranslationX(pinnedCounterTextViewX);
pinnedCounterTextView.setAlpha(loadedPinnedMessagesCount == 2 || currentPinnedMessageIndex[0] == 0 ? 0.0f : 1.0f);
messageTextView.setVisibility(View.VISIBLE);
messageTextView.setAlpha(1.0f);
messageTextView.setTranslationX(0);
messageTextView.setTranslationY(0);
nameTextView.setVisibility(View.VISIBLE);
nameTextView.setAlpha(1.0f);
nameTextView.setTranslationX(0);
nameTextView.setTranslationY(0);
pinnedMessageTextView[1].setVisibility(View.INVISIBLE);
pinnedMessageTextView[1].setTranslationX(0);
pinnedMessageTextView[1].setTranslationY(0);
pinnedNameTextView[1].setVisibility(View.INVISIBLE);
pinnedNameTextView[1].setTranslationX(0);
pinnedNameTextView[1].setTranslationY(0);
pinnedMessageImageView[0].setVisibility(View.INVISIBLE);
BackupImageView backupImageView = pinnedMessageImageView[1];
pinnedMessageImageView[1] = pinnedMessageImageView[0];
pinnedMessageImageView[0] = backupImageView;
pinnedMessageImageView[0].setAlpha(1.0f);
pinnedMessageImageView[0].setScaleX(1f);
pinnedMessageImageView[0].setScaleY(1f);
pinnedMessageImageView[0].setTranslationY(0);
pinnedMessageImageView[1].setAlpha(1.0f);
pinnedMessageImageView[1].setScaleX(1f);
pinnedMessageImageView[1].setScaleY(1f);
pinnedMessageImageView[1].setTranslationY(0);
}
if (isThreadChat()) {
pinnedLineView.set(0, 1, false);
} else {
int position = Collections.binarySearch(pinnedMessageIds, currentPinnedMessageId, Comparator.reverseOrder());
pinnedLineView.set(pinnedMessageIds.size() - 1 - position, pinnedMessageIds.size(), animated);
}
} else {
pinnedCounterTextView.setVisibility(loadedPinnedMessagesCount == 2 || currentPinnedMessageIndex[0] == 0 ? View.INVISIBLE : View.VISIBLE);
pinnedCounterTextView.setAlpha(loadedPinnedMessagesCount == 2 || currentPinnedMessageIndex[0] == 0 ? 0.0f : 1.0f);
pinnedImageLocation = null;
pinnedImageLocationObject = null;
changed = hidePinnedMessageView(animated);
if (loadingPinnedMessages.indexOfKey(pinned_msg_id) < 0) {
loadingPinnedMessages.put(pinned_msg_id, true);
ArrayList<Integer> ids = new ArrayList<>();
ids.add(pinned_msg_id);
getMediaDataController().loadPinnedMessages(dialog_id, ChatObject.isChannel(currentChat) ? currentChat.id : 0, ids, true);
}
}
}
if (changed) {
checkListViewPaddings();
}
}
use of org.telegram.tgnet.TLObject in project Telegram-FOSS by Telegram-FOSS-Team.
the class DialogsActivity method onItemClick.
private void onItemClick(View view, int position, RecyclerListView.Adapter adapter) {
if (getParentActivity() == null) {
return;
}
long dialogId = 0;
int message_id = 0;
boolean isGlobalSearch = false;
int folderId = 0;
int filterId = 0;
if (adapter instanceof DialogsAdapter) {
DialogsAdapter dialogsAdapter = (DialogsAdapter) adapter;
int dialogsType = dialogsAdapter.getDialogsType();
if (dialogsType == 7 || dialogsType == 8) {
MessagesController.DialogFilter dialogFilter = getMessagesController().selectedDialogFilter[dialogsType == 7 ? 0 : 1];
filterId = dialogFilter.id;
}
TLObject object = dialogsAdapter.getItem(position);
if (object instanceof TLRPC.User) {
dialogId = ((TLRPC.User) object).id;
} else if (object instanceof TLRPC.Dialog) {
TLRPC.Dialog dialog = (TLRPC.Dialog) object;
folderId = dialog.folder_id;
if (dialog instanceof TLRPC.TL_dialogFolder) {
if (actionBar.isActionModeShowed(null)) {
return;
}
TLRPC.TL_dialogFolder dialogFolder = (TLRPC.TL_dialogFolder) dialog;
Bundle args = new Bundle();
args.putInt("folderId", dialogFolder.folder.id);
presentFragment(new DialogsActivity(args));
return;
}
dialogId = dialog.id;
if (actionBar.isActionModeShowed(null)) {
showOrUpdateActionMode(dialogId, view);
return;
}
} else if (object instanceof TLRPC.TL_recentMeUrlChat) {
dialogId = -((TLRPC.TL_recentMeUrlChat) object).chat_id;
} else if (object instanceof TLRPC.TL_recentMeUrlUser) {
dialogId = ((TLRPC.TL_recentMeUrlUser) object).user_id;
} else if (object instanceof TLRPC.TL_recentMeUrlChatInvite) {
TLRPC.TL_recentMeUrlChatInvite chatInvite = (TLRPC.TL_recentMeUrlChatInvite) object;
TLRPC.ChatInvite invite = chatInvite.chat_invite;
if (invite.chat == null && (!invite.channel || invite.megagroup) || invite.chat != null && (!ChatObject.isChannel(invite.chat) || invite.chat.megagroup)) {
String hash = chatInvite.url;
int index = hash.indexOf('/');
if (index > 0) {
hash = hash.substring(index + 1);
}
showDialog(new JoinGroupAlert(getParentActivity(), invite, hash, DialogsActivity.this));
return;
} else {
if (invite.chat != null) {
dialogId = -invite.chat.id;
} else {
return;
}
}
} else if (object instanceof TLRPC.TL_recentMeUrlStickerSet) {
TLRPC.StickerSet stickerSet = ((TLRPC.TL_recentMeUrlStickerSet) object).set.set;
TLRPC.TL_inputStickerSetID set = new TLRPC.TL_inputStickerSetID();
set.id = stickerSet.id;
set.access_hash = stickerSet.access_hash;
showDialog(new StickersAlert(getParentActivity(), DialogsActivity.this, set, null, null));
return;
} else if (object instanceof TLRPC.TL_recentMeUrlUnknown) {
return;
} else {
return;
}
} else if (adapter == searchViewPager.dialogsSearchAdapter) {
Object obj = searchViewPager.dialogsSearchAdapter.getItem(position);
isGlobalSearch = searchViewPager.dialogsSearchAdapter.isGlobalSearch(position);
if (obj instanceof TLRPC.User) {
dialogId = ((TLRPC.User) obj).id;
if (!onlySelect) {
searchDialogId = dialogId;
searchObject = (TLRPC.User) obj;
}
} else if (obj instanceof TLRPC.Chat) {
dialogId = -((TLRPC.Chat) obj).id;
if (!onlySelect) {
searchDialogId = dialogId;
searchObject = (TLRPC.Chat) obj;
}
} else if (obj instanceof TLRPC.EncryptedChat) {
dialogId = DialogObject.makeEncryptedDialogId(((TLRPC.EncryptedChat) obj).id);
if (!onlySelect) {
searchDialogId = dialogId;
searchObject = (TLRPC.EncryptedChat) obj;
}
} else if (obj instanceof MessageObject) {
MessageObject messageObject = (MessageObject) obj;
dialogId = messageObject.getDialogId();
message_id = messageObject.getId();
searchViewPager.dialogsSearchAdapter.addHashtagsFromMessage(searchViewPager.dialogsSearchAdapter.getLastSearchString());
} else if (obj instanceof String) {
String str = (String) obj;
if (searchViewPager.dialogsSearchAdapter.isHashtagSearch()) {
actionBar.openSearchField(str, false);
} else if (!str.equals("section")) {
NewContactActivity activity = new NewContactActivity();
activity.setInitialPhoneNumber(str, true);
presentFragment(activity);
}
}
if (dialogId != 0 && actionBar.isActionModeShowed()) {
if (actionBar.isActionModeShowed(ACTION_MODE_SEARCH_DIALOGS_TAG) && message_id == 0 && !isGlobalSearch) {
showOrUpdateActionMode(dialogId, view);
}
return;
}
}
if (dialogId == 0) {
return;
}
if (onlySelect) {
if (!validateSlowModeDialog(dialogId)) {
return;
}
if (!selectedDialogs.isEmpty() || (initialDialogsType == 3 && selectAlertString != null)) {
boolean checked = addOrRemoveSelectedDialog(dialogId, view);
if (adapter == searchViewPager.dialogsSearchAdapter) {
actionBar.closeSearchField();
findAndUpdateCheckBox(dialogId, checked);
}
updateSelectedCount();
} else {
didSelectResult(dialogId, true, false);
}
} else {
Bundle args = new Bundle();
if (DialogObject.isEncryptedDialog(dialogId)) {
args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId));
} else if (DialogObject.isUserDialog(dialogId)) {
args.putLong("user_id", dialogId);
} else {
long did = dialogId;
if (message_id != 0) {
TLRPC.Chat chat = getMessagesController().getChat(-did);
if (chat != null && chat.migrated_to != null) {
args.putLong("migrated_to", did);
did = -chat.migrated_to.channel_id;
}
}
args.putLong("chat_id", -did);
}
if (message_id != 0) {
args.putInt("message_id", message_id);
} else if (!isGlobalSearch) {
closeSearch();
} else {
if (searchObject != null) {
searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject);
searchObject = null;
}
}
args.putInt("dialog_folder_id", folderId);
args.putInt("dialog_filter_id", filterId);
if (AndroidUtilities.isTablet()) {
if (openedDialogId == dialogId && adapter != searchViewPager.dialogsSearchAdapter) {
return;
}
if (viewPages != null) {
for (int a = 0; a < viewPages.length; a++) {
viewPages[a].dialogsAdapter.setOpenedDialogId(openedDialogId = dialogId);
}
}
updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG);
}
if (searchViewPager.actionModeShowing()) {
searchViewPager.hideActionMode();
}
if (searchString != null) {
if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) {
getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
presentFragment(new ChatActivity(args));
}
} else {
if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) {
ChatActivity chatActivity = new ChatActivity(args);
if (adapter instanceof DialogsAdapter && DialogObject.isUserDialog(dialogId) && (getMessagesController().dialogs_dict.get(dialogId) == null)) {
TLRPC.Document sticker = getMediaDataController().getGreetingsSticker();
if (sticker != null) {
chatActivity.setPreloadedSticker(sticker, true);
}
}
presentFragment(chatActivity);
}
}
}
}
Aggregations