use of org.telegram.messenger.Emoji in project Telegram-FOSS by Telegram-FOSS-Team.
the class PhotoViewer method setParentActivity.
public void setParentActivity(final Activity activity, Theme.ResourcesProvider resourcesProvider) {
Theme.createChatResources(activity, false);
this.resourcesProvider = resourcesProvider;
currentAccount = UserConfig.selectedAccount;
centerImage.setCurrentAccount(currentAccount);
leftImage.setCurrentAccount(currentAccount);
rightImage.setCurrentAccount(currentAccount);
if (parentActivity == activity || activity == null) {
return;
}
inBubbleMode = activity instanceof BubbleActivity;
parentActivity = activity;
activityContext = new ContextThemeWrapper(parentActivity, R.style.Theme_TMessages);
touchSlop = ViewConfiguration.get(parentActivity).getScaledTouchSlop();
if (progressDrawables == null) {
final Drawable circleDrawable = ContextCompat.getDrawable(parentActivity, R.drawable.circle_big);
progressDrawables = new Drawable[] { // PROGRESS_EMPTY
circleDrawable, // PROGRESS_CANCEL
ContextCompat.getDrawable(parentActivity, R.drawable.cancel_big), // PROGRESS_LOAD
ContextCompat.getDrawable(parentActivity, R.drawable.load_big) };
}
scroller = new Scroller(activity);
windowView = new FrameLayout(activity) {
private Runnable attachRunnable;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return isVisible && super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return isVisible && PhotoViewer.this.onTouchEvent(event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (!muteVideo && sendPhotoType != SELECT_TYPE_AVATAR && isCurrentVideo && videoPlayer != null && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN && (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)) {
videoPlayer.setVolume(1.0f);
}
return super.dispatchKeyEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (videoPlayerControlVisible && isPlaying) {
switch(ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
AndroidUtilities.cancelRunOnUIThread(hideActionBarRunnable);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_POINTER_UP:
scheduleActionBarHide();
break;
}
}
return super.dispatchTouchEvent(ev);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result;
try {
result = super.drawChild(canvas, child, drawingTime);
} catch (Throwable ignore) {
result = false;
}
return result;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (Build.VERSION.SDK_INT >= 21 && lastInsets != null) {
WindowInsets insets = (WindowInsets) lastInsets;
if (!inBubbleMode) {
if (AndroidUtilities.incorrectDisplaySizeFix) {
if (heightSize > AndroidUtilities.displaySize.y) {
heightSize = AndroidUtilities.displaySize.y;
}
heightSize += AndroidUtilities.statusBarHeight;
} else {
int insetBottom = insets.getStableInsetBottom();
if (insetBottom >= 0 && AndroidUtilities.statusBarHeight >= 0) {
int newSize = heightSize - AndroidUtilities.statusBarHeight - insets.getStableInsetBottom();
if (newSize > 0 && newSize < 4096) {
AndroidUtilities.displaySize.y = newSize;
}
}
}
}
int bottomInsets = insets.getSystemWindowInsetBottom();
if (captionEditText.isPopupShowing()) {
bottomInsets -= containerView.getKeyboardHeight();
}
heightSize -= bottomInsets;
} else {
if (heightSize > AndroidUtilities.displaySize.y) {
heightSize = AndroidUtilities.displaySize.y;
}
}
setMeasuredDimension(widthSize, heightSize);
ViewGroup.LayoutParams layoutParams = animatingImageView.getLayoutParams();
animatingImageView.measure(MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.AT_MOST));
containerView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
}
@SuppressWarnings("DrawAllocation")
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
animatingImageView.layout(0, 0, animatingImageView.getMeasuredWidth(), animatingImageView.getMeasuredHeight());
containerView.layout(0, 0, containerView.getMeasuredWidth(), containerView.getMeasuredHeight());
wasLayout = true;
if (changed) {
if (!dontResetZoomOnFirstLayout) {
scale = 1;
translationX = 0;
translationY = 0;
updateMinMax(scale);
}
if (checkImageView != null) {
checkImageView.post(() -> {
LayoutParams layoutParams = (LayoutParams) checkImageView.getLayoutParams();
WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();
int newMargin = (ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(34)) / 2 + (isStatusBarVisible() ? AndroidUtilities.statusBarHeight : 0);
if (newMargin != layoutParams.topMargin) {
layoutParams.topMargin = newMargin;
checkImageView.setLayoutParams(layoutParams);
}
layoutParams = (LayoutParams) photosCounterView.getLayoutParams();
newMargin = (ActionBar.getCurrentActionBarHeight() - AndroidUtilities.dp(40)) / 2 + (isStatusBarVisible() ? AndroidUtilities.statusBarHeight : 0);
if (layoutParams.topMargin != newMargin) {
layoutParams.topMargin = newMargin;
photosCounterView.setLayoutParams(layoutParams);
}
});
}
}
if (dontResetZoomOnFirstLayout) {
setScaleToFill();
dontResetZoomOnFirstLayout = false;
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
attachedToWindow = true;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
attachedToWindow = false;
wasLayout = false;
}
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
if (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible()) {
closeCaptionEnter(true);
return false;
}
PhotoViewer.getInstance().closePhoto(true, false);
return true;
}
return super.dispatchKeyEventPreIme(event);
}
@Override
protected void onDraw(Canvas canvas) {
if (Build.VERSION.SDK_INT >= 21 && isVisible && lastInsets != null) {
WindowInsets insets = (WindowInsets) lastInsets;
if (animationInProgress == 1) {
blackPaint.setAlpha((int) (255 * animatingImageView.getAnimationProgress()));
} else if (animationInProgress == 3) {
blackPaint.setAlpha((int) (255 * (1.0f - animatingImageView.getAnimationProgress())));
} else {
blackPaint.setAlpha(backgroundDrawable.getAlpha());
}
canvas.drawRect(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight() + insets.getSystemWindowInsetBottom(), blackPaint);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (parentChatActivity != null) {
View undoView = parentChatActivity.getUndoView();
if (undoView.getVisibility() == View.VISIBLE) {
canvas.save();
View parent = (View) undoView.getParent();
canvas.clipRect(parent.getX(), parent.getY(), parent.getX() + parent.getWidth(), parent.getY() + parent.getHeight());
canvas.translate(undoView.getX(), undoView.getY());
undoView.draw(canvas);
canvas.restore();
invalidate();
}
}
}
};
windowView.setBackgroundDrawable(backgroundDrawable);
windowView.setClipChildren(true);
windowView.setFocusable(false);
animatingImageView = new ClippingImageView(activity);
animatingImageView.setAnimationValues(animationValues);
windowView.addView(animatingImageView, LayoutHelper.createFrame(40, 40));
containerView = new FrameLayoutDrawer(activity);
containerView.setFocusable(false);
windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
if (Build.VERSION.SDK_INT >= 21) {
containerView.setFitsSystemWindows(true);
containerView.setOnApplyWindowInsetsListener((v, insets) -> {
int newTopInset = insets.getSystemWindowInsetTop();
if (parentActivity instanceof LaunchActivity && (newTopInset != 0 || AndroidUtilities.isInMultiwindow) && !inBubbleMode && AndroidUtilities.statusBarHeight != newTopInset) {
AndroidUtilities.statusBarHeight = newTopInset;
((LaunchActivity) parentActivity).drawerLayoutContainer.requestLayout();
}
WindowInsets oldInsets = (WindowInsets) lastInsets;
lastInsets = insets;
if (oldInsets == null || !oldInsets.toString().equals(insets.toString())) {
if (animationInProgress == 1 || animationInProgress == 3) {
animatingImageView.setTranslationX(animatingImageView.getTranslationX() - getLeftInset());
animationValues[0][2] = animatingImageView.getTranslationX();
}
if (windowView != null) {
windowView.requestLayout();
}
}
containerView.setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), 0);
if (actionBar != null) {
AndroidUtilities.cancelRunOnUIThread(updateContainerFlagsRunnable);
if (isVisible && animationInProgress == 0) {
AndroidUtilities.runOnUIThread(updateContainerFlagsRunnable, 200);
}
}
if (Build.VERSION.SDK_INT >= 30) {
return WindowInsets.CONSUMED;
} else {
return insets.consumeSystemWindowInsets();
}
});
containerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
windowLayoutParams = new WindowManager.LayoutParams();
windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.format = PixelFormat.TRANSLUCENT;
windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
if (Build.VERSION.SDK_INT >= 28) {
windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
}
if (Build.VERSION.SDK_INT >= 21) {
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
} else {
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
}
paintingOverlay = new PaintingOverlay(parentActivity);
containerView.addView(paintingOverlay, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
actionBar = new ActionBar(activity) {
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
containerView.invalidate();
}
};
actionBar.setOverlayTitleAnimation(true);
actionBar.setTitleColor(0xffffffff);
actionBar.setSubtitleColor(0xffffffff);
actionBar.setBackgroundColor(Theme.ACTION_BAR_PHOTO_VIEWER_COLOR);
actionBar.setOccupyStatusBar(isStatusBarVisible());
actionBar.setItemsBackgroundColor(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, false);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setTitle(LocaleController.formatString("Of", R.string.Of, 1, 1));
containerView.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
if (needCaptionLayout && (captionEditText.isPopupShowing() || captionEditText.isKeyboardVisible())) {
closeCaptionEnter(false);
return;
}
closePhoto(true, false);
} else if (id == gallery_menu_save) {
if (Build.VERSION.SDK_INT >= 23 && (Build.VERSION.SDK_INT <= 28 || BuildVars.NO_SCOPED_STORAGE) && parentActivity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
parentActivity.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 4);
return;
}
File f = null;
final boolean isVideo;
if (currentMessageObject != null) {
if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && currentMessageObject.messageOwner.media.webpage != null && currentMessageObject.messageOwner.media.webpage.document == null) {
TLObject fileLocation = getFileLocation(currentIndex, null);
f = FileLoader.getPathToAttach(fileLocation, true);
} else {
f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
}
isVideo = currentMessageObject.isVideo();
} else if (currentFileLocationVideo != null) {
f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), avatarsDialogId != 0 || isEvent);
isVideo = false;
} else if (pageBlocksAdapter != null) {
f = pageBlocksAdapter.getFile(currentIndex);
isVideo = pageBlocksAdapter.isVideo(currentIndex);
} else {
isVideo = false;
}
if (f != null && f.exists()) {
MediaController.saveFile(f.toString(), parentActivity, isVideo ? 1 : 0, null, null, () -> BulletinFactory.createSaveToGalleryBulletin(containerView, isVideo, 0xf9222222, 0xffffffff).show());
} else {
showDownloadAlert();
}
} else if (id == gallery_menu_showall) {
if (currentDialogId != 0) {
disableShowCheck = true;
Bundle args2 = new Bundle();
args2.putLong("dialog_id", currentDialogId);
MediaActivity mediaActivity = new MediaActivity(args2, null);
if (parentChatActivity != null) {
mediaActivity.setChatInfo(parentChatActivity.getCurrentChatInfo());
}
closePhoto(false, false);
if (parentActivity instanceof LaunchActivity) {
((LaunchActivity) parentActivity).presentFragment(mediaActivity, false, true);
}
}
} else if (id == gallery_menu_showinchat) {
if (currentMessageObject == null) {
return;
}
Bundle args = new Bundle();
long dialogId = currentDialogId;
if (currentMessageObject != null) {
dialogId = currentMessageObject.getDialogId();
}
if (DialogObject.isEncryptedDialog(dialogId)) {
args.putInt("enc_id", DialogObject.getEncryptedChatId(dialogId));
} else if (DialogObject.isUserDialog(dialogId)) {
args.putLong("user_id", dialogId);
} else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
if (chat != null && chat.migrated_to != null) {
args.putLong("migrated_to", dialogId);
dialogId = -chat.migrated_to.channel_id;
}
args.putLong("chat_id", -dialogId);
}
args.putInt("message_id", currentMessageObject.getId());
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
if (parentActivity instanceof LaunchActivity) {
LaunchActivity launchActivity = (LaunchActivity) parentActivity;
boolean remove = launchActivity.getMainFragmentsCount() > 1 || AndroidUtilities.isTablet();
launchActivity.presentFragment(new ChatActivity(args), remove, true);
}
closePhoto(false, false);
currentMessageObject = null;
} else if (id == gallery_menu_send) {
if (currentMessageObject == null || !(parentActivity instanceof LaunchActivity)) {
return;
}
((LaunchActivity) parentActivity).switchToAccount(currentMessageObject.currentAccount, true);
Bundle args = new Bundle();
args.putBoolean("onlySelect", true);
args.putInt("dialogsType", 3);
DialogsActivity fragment = new DialogsActivity(args);
final ArrayList<MessageObject> fmessages = new ArrayList<>();
fmessages.add(currentMessageObject);
final ChatActivity parentChatActivityFinal = parentChatActivity;
fragment.setDelegate((fragment1, dids, message, param) -> {
if (dids.size() > 1 || dids.get(0) == UserConfig.getInstance(currentAccount).getClientUserId() || message != null) {
for (int a = 0; a < dids.size(); a++) {
long did = dids.get(a);
if (message != null) {
SendMessagesHelper.getInstance(currentAccount).sendMessage(message.toString(), did, null, null, null, true, null, null, null, true, 0, null);
}
SendMessagesHelper.getInstance(currentAccount).sendMessage(fmessages, did, false, false, true, 0);
}
fragment1.finishFragment();
if (parentChatActivityFinal != null) {
if (dids.size() == 1) {
parentChatActivityFinal.getUndoView().showWithAction(dids.get(0), UndoView.ACTION_FWD_MESSAGES, fmessages.size());
} else {
parentChatActivityFinal.getUndoView().showWithAction(0, UndoView.ACTION_FWD_MESSAGES, fmessages.size(), dids.size(), null, null);
}
}
} else {
long did = dids.get(0);
Bundle args1 = new Bundle();
args1.putBoolean("scrollToTopOnResume", true);
if (DialogObject.isEncryptedDialog(did)) {
args1.putInt("enc_id", DialogObject.getEncryptedChatId(did));
} else if (DialogObject.isUserDialog(did)) {
args1.putLong("user_id", did);
} else {
args1.putLong("chat_id", -did);
}
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.closeChats);
ChatActivity chatActivity = new ChatActivity(args1);
if (((LaunchActivity) parentActivity).presentFragment(chatActivity, true, false)) {
chatActivity.showFieldPanelForForward(true, fmessages);
} else {
fragment1.finishFragment();
}
}
});
((LaunchActivity) parentActivity).presentFragment(fragment, false, true);
closePhoto(false, false);
} else if (id == gallery_menu_delete) {
if (parentActivity == null || placeProvider == null) {
return;
}
boolean isChannel = false;
if (currentMessageObject != null && !currentMessageObject.scheduled) {
long dialogId = currentMessageObject.getDialogId();
if (DialogObject.isChatDialog(dialogId)) {
isChannel = ChatObject.isChannel(MessagesController.getInstance(currentAccount).getChat(-dialogId));
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
String text = placeProvider.getDeleteMessageString();
if (text != null) {
builder.setTitle(LocaleController.getString("AreYouSureDeletePhotoTitle", R.string.AreYouSureDeletePhotoTitle));
builder.setMessage(text);
} else if (isEmbedVideo || currentFileLocationVideo != null && currentFileLocationVideo != currentFileLocation || currentMessageObject != null && currentMessageObject.isVideo()) {
builder.setTitle(LocaleController.getString("AreYouSureDeleteVideoTitle", R.string.AreYouSureDeleteVideoTitle));
if (isChannel) {
builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideoEveryone", R.string.AreYouSureDeleteVideoEveryone));
} else {
builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo", R.string.AreYouSureDeleteVideo));
}
} else if (currentMessageObject != null && currentMessageObject.isGif()) {
builder.setTitle(LocaleController.getString("AreYouSureDeleteGIFTitle", R.string.AreYouSureDeleteGIFTitle));
if (isChannel) {
builder.setMessage(LocaleController.formatString("AreYouSureDeleteGIFEveryone", R.string.AreYouSureDeleteGIFEveryone));
} else {
builder.setMessage(LocaleController.formatString("AreYouSureDeleteGIF", R.string.AreYouSureDeleteGIF));
}
} else {
builder.setTitle(LocaleController.getString("AreYouSureDeletePhotoTitle", R.string.AreYouSureDeletePhotoTitle));
if (isChannel) {
builder.setMessage(LocaleController.formatString("AreYouSureDeletePhotoEveryone", R.string.AreYouSureDeletePhotoEveryone));
} else {
builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto));
}
}
final boolean[] deleteForAll = new boolean[1];
if (currentMessageObject != null && !currentMessageObject.scheduled) {
long dialogId = currentMessageObject.getDialogId();
if (!DialogObject.isEncryptedDialog(dialogId)) {
TLRPC.Chat currentChat;
TLRPC.User currentUser;
if (DialogObject.isUserDialog(dialogId)) {
currentUser = MessagesController.getInstance(currentAccount).getUser(dialogId);
currentChat = null;
} else {
currentUser = null;
currentChat = MessagesController.getInstance(currentAccount).getChat(-dialogId);
}
if (currentUser != null || !ChatObject.isChannel(currentChat)) {
boolean hasOutgoing = false;
int currentDate = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
int revokeTimeLimit;
if (currentUser != null) {
revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimePmLimit;
} else {
revokeTimeLimit = MessagesController.getInstance(currentAccount).revokeTimeLimit;
}
if (currentUser != null && currentUser.id != UserConfig.getInstance(currentAccount).getClientUserId() || currentChat != null) {
boolean canRevokeInbox = currentUser != null && MessagesController.getInstance(currentAccount).canRevokePmInbox;
if ((currentMessageObject.messageOwner.action == null || currentMessageObject.messageOwner.action instanceof TLRPC.TL_messageActionEmpty) && (currentMessageObject.isOut() || canRevokeInbox || ChatObject.hasAdminRights(currentChat)) && (currentDate - currentMessageObject.messageOwner.date) <= revokeTimeLimit) {
FrameLayout frameLayout = new FrameLayout(parentActivity);
CheckBoxCell cell = new CheckBoxCell(parentActivity, 1, resourcesProvider);
cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
if (currentChat != null) {
cell.setText(LocaleController.getString("DeleteForAll", R.string.DeleteForAll), "", false, false);
} else {
cell.setText(LocaleController.formatString("DeleteForUser", R.string.DeleteForUser, UserObject.getFirstName(currentUser)), "", false, false);
}
cell.setPadding(LocaleController.isRTL ? AndroidUtilities.dp(16) : AndroidUtilities.dp(8), 0, LocaleController.isRTL ? AndroidUtilities.dp(8) : AndroidUtilities.dp(16), 0);
frameLayout.addView(cell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 0));
cell.setOnClickListener(v -> {
CheckBoxCell cell1 = (CheckBoxCell) v;
deleteForAll[0] = !deleteForAll[0];
cell1.setChecked(deleteForAll[0], true);
});
builder.setView(frameLayout);
builder.setCustomViewOffset(9);
}
}
}
}
}
builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
if (!imagesArr.isEmpty()) {
if (currentIndex < 0 || currentIndex >= imagesArr.size()) {
return;
}
MessageObject obj = imagesArr.get(currentIndex);
if (obj.isSent()) {
closePhoto(false, false);
ArrayList<Integer> arr = new ArrayList<>();
if (slideshowMessageId != 0) {
arr.add(slideshowMessageId);
} else {
arr.add(obj.getId());
}
ArrayList<Long> random_ids = null;
TLRPC.EncryptedChat encryptedChat = null;
if (DialogObject.isEncryptedDialog(obj.getDialogId()) && obj.messageOwner.random_id != 0) {
random_ids = new ArrayList<>();
random_ids.add(obj.messageOwner.random_id);
encryptedChat = MessagesController.getInstance(currentAccount).getEncryptedChat(DialogObject.getEncryptedChatId(obj.getDialogId()));
}
MessagesController.getInstance(currentAccount).deleteMessages(arr, random_ids, encryptedChat, obj.getDialogId(), deleteForAll[0], obj.scheduled);
}
} else if (!avatarsArr.isEmpty()) {
if (currentIndex < 0 || currentIndex >= avatarsArr.size()) {
return;
}
TLRPC.Message message = imagesArrMessages.get(currentIndex);
if (message != null) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(message.id);
MessagesController.getInstance(currentAccount).deleteMessages(arr, null, null, MessageObject.getDialogId(message), true, false);
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.reloadDialogPhotos);
}
if (isCurrentAvatarSet()) {
if (avatarsDialogId > 0) {
MessagesController.getInstance(currentAccount).deleteUserPhoto(null);
} else {
MessagesController.getInstance(currentAccount).changeChatAvatar(-avatarsDialogId, null, null, null, 0, null, null, null, null);
}
closePhoto(false, false);
} else {
TLRPC.Photo photo = avatarsArr.get(currentIndex);
if (photo == null) {
return;
}
TLRPC.TL_inputPhoto inputPhoto = new TLRPC.TL_inputPhoto();
inputPhoto.id = photo.id;
inputPhoto.access_hash = photo.access_hash;
inputPhoto.file_reference = photo.file_reference;
if (inputPhoto.file_reference == null) {
inputPhoto.file_reference = new byte[0];
}
if (avatarsDialogId > 0) {
MessagesController.getInstance(currentAccount).deleteUserPhoto(inputPhoto);
}
MessagesStorage.getInstance(currentAccount).clearUserPhoto(avatarsDialogId, photo.id);
imagesArrLocations.remove(currentIndex);
imagesArrLocationsSizes.remove(currentIndex);
imagesArrLocationsVideo.remove(currentIndex);
imagesArrMessages.remove(currentIndex);
avatarsArr.remove(currentIndex);
if (imagesArrLocations.isEmpty()) {
closePhoto(false, false);
} else {
int index = currentIndex;
if (index >= avatarsArr.size()) {
index = avatarsArr.size() - 1;
}
currentIndex = -1;
setImageIndex(index);
}
if (message == null) {
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.reloadDialogPhotos);
}
}
} else if (!secureDocuments.isEmpty()) {
if (placeProvider == null) {
return;
}
secureDocuments.remove(currentIndex);
placeProvider.deleteImageAtIndex(currentIndex);
if (secureDocuments.isEmpty()) {
closePhoto(false, false);
} else {
int index = currentIndex;
if (index >= secureDocuments.size()) {
index = secureDocuments.size() - 1;
}
currentIndex = -1;
setImageIndex(index);
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
AlertDialog alertDialog = builder.create();
showAlertDialog(builder);
TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (button != null) {
button.setTextColor(getThemedColor(Theme.key_dialogTextRed2));
}
} else if (id == gallery_menu_share || id == gallery_menu_share2) {
onSharePressed();
} else if (id == gallery_menu_speed) {
menuItemSpeed.setVisibility(View.VISIBLE);
menuItemSpeed.toggleSubMenu();
for (int a = 0; a < speedItems.length; a++) {
if (a == 0 && Math.abs(currentVideoSpeed - 0.25f) < 0.001f || a == 1 && Math.abs(currentVideoSpeed - 0.5f) < 0.001f || a == 2 && Math.abs(currentVideoSpeed - 1.0f) < 0.001f || a == 3 && Math.abs(currentVideoSpeed - 1.5f) < 0.001f || a == 4 && Math.abs(currentVideoSpeed - 2.0f) < 0.001f) {
speedItems[a].setColors(0xff6BB6F9, 0xff6BB6F9);
} else {
speedItems[a].setColors(0xfffafafa, 0xfffafafa);
}
}
} else if (id == gallery_menu_openin) {
try {
if (isEmbedVideo) {
Browser.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
closePhoto(false, false);
} else if (currentMessageObject != null) {
if (AndroidUtilities.openForView(currentMessageObject, parentActivity, resourcesProvider)) {
closePhoto(false, false);
} else {
showDownloadAlert();
}
} else if (pageBlocksAdapter != null) {
if (AndroidUtilities.openForView(pageBlocksAdapter.getMedia(currentIndex), parentActivity)) {
closePhoto(false, false);
} else {
showDownloadAlert();
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else if (id == gallery_menu_masks || id == gallery_menu_masks2) {
if (parentActivity == null || currentMessageObject == null) {
return;
}
TLObject object;
if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
object = currentMessageObject.messageOwner.media.photo;
} else if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
object = currentMessageObject.messageOwner.media.document;
} else {
return;
}
masksAlert = new StickersAlert(parentActivity, currentMessageObject, object, resourcesProvider) {
@Override
public void dismiss() {
super.dismiss();
if (masksAlert == this) {
masksAlert = null;
}
}
};
masksAlert.show();
} else if (id == gallery_menu_pip) {
if (pipItem.getAlpha() != 1.0f) {
return;
}
if (isEmbedVideo) {
pipVideoView = photoViewerWebView.openInPip();
if (pipVideoView != null) {
if (PipInstance != null) {
PipInstance.destroyPhotoViewer();
}
isInline = true;
PipInstance = Instance;
Instance = null;
isVisible = false;
if (currentPlaceObject != null && !currentPlaceObject.imageReceiver.getVisible()) {
currentPlaceObject.imageReceiver.setVisible(true, true);
}
dismissInternal();
}
} else {
switchToPip(false);
}
} else if (id == gallery_menu_cancel_loading) {
if (currentMessageObject == null) {
return;
}
FileLoader.getInstance(currentAccount).cancelLoadFile(currentMessageObject.getDocument());
releasePlayer(false);
bottomLayout.setTag(1);
bottomLayout.setVisibility(View.VISIBLE);
} else if (id == gallery_menu_savegif) {
if (currentMessageObject != null) {
TLRPC.Document document = currentMessageObject.getDocument();
if (parentChatActivity != null && parentChatActivity.chatActivityEnterView != null) {
parentChatActivity.chatActivityEnterView.addRecentGif(document);
} else {
MediaDataController.getInstance(currentAccount).addRecentGif(document, (int) (System.currentTimeMillis() / 1000));
}
MessagesController.getInstance(currentAccount).saveGif(currentMessageObject, document);
} else if (pageBlocksAdapter != null) {
TLObject object = pageBlocksAdapter.getMedia(currentIndex);
if (object instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) object;
MediaDataController.getInstance(currentAccount).addRecentGif(document, (int) (System.currentTimeMillis() / 1000));
MessagesController.getInstance(currentAccount).saveGif(pageBlocksAdapter.getParentObject(), document);
}
} else {
return;
}
if (containerView != null) {
BulletinFactory.of(containerView, resourcesProvider).createDownloadBulletin(BulletinFactory.FileType.GIF, resourcesProvider).show();
}
} else if (id == gallery_menu_set_as_main) {
TLRPC.Photo photo = avatarsArr.get(currentIndex);
if (photo == null || photo.sizes.isEmpty()) {
return;
}
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 800);
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 90);
UserConfig userConfig = UserConfig.getInstance(currentAccount);
if (avatarsDialogId == userConfig.clientUserId) {
TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();
req.id = new TLRPC.TL_inputPhoto();
req.id.id = photo.id;
req.id.access_hash = photo.access_hash;
req.id.file_reference = photo.file_reference;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (response instanceof TLRPC.TL_photos_photo) {
TLRPC.TL_photos_photo photos_photo = (TLRPC.TL_photos_photo) response;
MessagesController.getInstance(currentAccount).putUsers(photos_photo.users, false);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userConfig.clientUserId);
if (photos_photo.photo instanceof TLRPC.TL_photo) {
int idx = avatarsArr.indexOf(photo);
if (idx >= 0) {
avatarsArr.set(idx, photos_photo.photo);
}
if (user != null) {
user.photo.photo_id = photos_photo.photo.id;
userConfig.setCurrentUser(user);
userConfig.saveConfig(true);
}
}
}
}));
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(userConfig.clientUserId);
if (user != null) {
user.photo.photo_id = photo.id;
user.photo.dc_id = photo.dc_id;
user.photo.photo_small = smallSize.location;
user.photo.photo_big = bigSize.location;
userConfig.setCurrentUser(user);
userConfig.saveConfig(true);
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.mainUserInfoChanged);
}
} else {
TLRPC.Chat chat = MessagesController.getInstance(currentAccount).getChat(-avatarsDialogId);
if (chat == null) {
return;
}
TLRPC.TL_inputChatPhoto inputChatPhoto = new TLRPC.TL_inputChatPhoto();
inputChatPhoto.id = new TLRPC.TL_inputPhoto();
inputChatPhoto.id.id = photo.id;
inputChatPhoto.id.access_hash = photo.access_hash;
inputChatPhoto.id.file_reference = photo.file_reference;
MessagesController.getInstance(currentAccount).changeChatAvatar(-avatarsDialogId, inputChatPhoto, null, null, 0, null, null, null, null);
chat.photo.dc_id = photo.dc_id;
chat.photo.photo_small = smallSize.location;
chat.photo.photo_big = bigSize.location;
NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_AVATAR);
}
currentAvatarLocation = ImageLocation.getForPhoto(bigSize, photo);
avatarsArr.remove(currentIndex);
avatarsArr.add(0, photo);
ImageLocation location = imagesArrLocations.get(currentIndex);
imagesArrLocations.remove(currentIndex);
imagesArrLocations.add(0, location);
location = imagesArrLocationsVideo.get(currentIndex);
imagesArrLocationsVideo.remove(currentIndex);
imagesArrLocationsVideo.add(0, location);
Integer size = imagesArrLocationsSizes.get(currentIndex);
imagesArrLocationsSizes.remove(currentIndex);
imagesArrLocationsSizes.add(0, size);
TLRPC.Message message = imagesArrMessages.get(currentIndex);
imagesArrMessages.remove(currentIndex);
imagesArrMessages.add(0, message);
currentIndex = -1;
setImageIndex(0);
groupedPhotosListView.clear();
groupedPhotosListView.fillList();
hintView.showWithAction(avatarsDialogId, UndoView.ACTION_PROFILE_PHOTO_CHANGED, currentFileLocationVideo == currentFileLocation ? null : 1);
AndroidUtilities.runOnUIThread(() -> {
if (menuItem == null) {
return;
}
menuItem.hideSubItem(gallery_menu_set_as_main);
}, 300);
} else if (id == gallery_menu_edit_avatar) {
File f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), true);
boolean isVideo = currentFileLocationVideo.imageType == FileLoader.IMAGE_TYPE_ANIMATION;
String thumb;
if (isVideo) {
thumb = FileLoader.getPathToAttach(getFileLocation(currentFileLocation), getFileLocationExt(currentFileLocation), true).getAbsolutePath();
} else {
thumb = null;
}
placeProvider.openPhotoForEdit(f.getAbsolutePath(), thumb, isVideo);
}
}
@Override
public boolean canOpenMenu() {
menuItemSpeed.setVisibility(View.INVISIBLE);
if (currentMessageObject != null || currentSecureDocument != null) {
return true;
} else if (currentFileLocationVideo != null) {
File f = FileLoader.getPathToAttach(getFileLocation(currentFileLocationVideo), getFileLocationExt(currentFileLocationVideo), avatarsDialogId != 0 || isEvent);
return f.exists();
} else if (pageBlocksAdapter != null) {
return true;
}
return false;
}
});
ActionBarMenu menu = actionBar.createMenu();
masksItem = menu.addItem(gallery_menu_masks, R.drawable.msg_mask);
masksItem.setContentDescription(LocaleController.getString("Masks", R.string.Masks));
pipItem = menu.addItem(gallery_menu_pip, R.drawable.ic_goinline);
pipItem.setContentDescription(LocaleController.getString("AccDescrPipMode", R.string.AccDescrPipMode));
sendItem = menu.addItem(gallery_menu_send, R.drawable.msg_forward);
sendItem.setContentDescription(LocaleController.getString("Forward", R.string.Forward));
shareItem = menu.addItem(gallery_menu_share2, R.drawable.share);
shareItem.setContentDescription(LocaleController.getString("ShareFile", R.string.ShareFile));
menuItem = menu.addItem(0, R.drawable.ic_ab_other);
menuItemSpeed = new ActionBarMenuItem(parentActivity, null, 0, 0, resourcesProvider);
menuItemSpeed.setDelegate(id -> {
if (id >= gallery_menu_speed_veryslow && id <= gallery_menu_speed_veryfast) {
switch(id) {
case gallery_menu_speed_veryslow:
currentVideoSpeed = 0.25f;
break;
case gallery_menu_speed_slow:
currentVideoSpeed = 0.5f;
break;
case gallery_menu_speed_normal:
currentVideoSpeed = 1.0f;
break;
case gallery_menu_speed_fast:
currentVideoSpeed = 1.5f;
break;
case gallery_menu_speed_veryfast:
currentVideoSpeed = 2.0f;
break;
}
if (currentMessageObject != null) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("playback_speed", Activity.MODE_PRIVATE);
if (Math.abs(currentVideoSpeed - 1.0f) < 0.001f) {
preferences.edit().remove("speed" + currentMessageObject.getDialogId() + "_" + currentMessageObject.getId()).commit();
} else {
preferences.edit().putFloat("speed" + currentMessageObject.getDialogId() + "_" + currentMessageObject.getId(), currentVideoSpeed).commit();
}
}
if (videoPlayer != null) {
videoPlayer.setPlaybackSpeed(currentVideoSpeed);
}
if (photoViewerWebView != null) {
photoViewerWebView.setPlaybackSpeed(currentVideoSpeed);
}
setMenuItemIcon();
menuItemSpeed.setVisibility(View.INVISIBLE);
}
});
menuItem.addView(menuItemSpeed);
menuItemSpeed.setVisibility(View.INVISIBLE);
speedItem = menuItem.addSubItem(gallery_menu_speed, R.drawable.msg_speed, null, LocaleController.getString("Speed", R.string.Speed), true, false);
speedItem.setSubtext(LocaleController.getString("SpeedNormal", R.string.SpeedNormal));
speedItem.setItemHeight(56);
speedItem.setTag(R.id.width_tag, 240);
speedItem.setColors(0xfffafafa, 0xfffafafa);
speedItem.setRightIcon(R.drawable.msg_arrowright);
speedGap = menuItem.addGap(gallery_menu_gap);
menuItem.getPopupLayout().setFitItems(true);
speedItems[0] = menuItemSpeed.addSubItem(gallery_menu_speed_veryslow, R.drawable.msg_speed_0_2, LocaleController.getString("SpeedVerySlow", R.string.SpeedVerySlow)).setColors(0xfffafafa, 0xfffafafa);
speedItems[1] = menuItemSpeed.addSubItem(gallery_menu_speed_slow, R.drawable.msg_speed_0_5, LocaleController.getString("SpeedSlow", R.string.SpeedSlow)).setColors(0xfffafafa, 0xfffafafa);
speedItems[2] = menuItemSpeed.addSubItem(gallery_menu_speed_normal, R.drawable.msg_speed_1, LocaleController.getString("SpeedNormal", R.string.SpeedNormal)).setColors(0xfffafafa, 0xfffafafa);
speedItems[3] = menuItemSpeed.addSubItem(gallery_menu_speed_fast, R.drawable.msg_speed_1_5, LocaleController.getString("SpeedFast", R.string.SpeedFast)).setColors(0xfffafafa, 0xfffafafa);
speedItems[4] = menuItemSpeed.addSubItem(gallery_menu_speed_veryfast, R.drawable.msg_speed_2, LocaleController.getString("SpeedVeryFast", R.string.SpeedVeryFast)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_openin, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp)).setColors(0xfffafafa, 0xfffafafa);
menuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
allMediaItem = menuItem.addSubItem(gallery_menu_showall, R.drawable.msg_media, LocaleController.getString("ShowAllMedia", R.string.ShowAllMedia));
allMediaItem.setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_savegif, R.drawable.msg_gif, LocaleController.getString("SaveToGIFs", R.string.SaveToGIFs)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_showinchat, R.drawable.msg_message, LocaleController.getString("ShowInChat", R.string.ShowInChat)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_masks2, R.drawable.msg_sticker, LocaleController.getString("ShowStickers", R.string.ShowStickers)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_share, R.drawable.msg_shareout, LocaleController.getString("ShareFile", R.string.ShareFile)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_save, R.drawable.msg_gallery, LocaleController.getString("SaveToGallery", R.string.SaveToGallery)).setColors(0xfffafafa, 0xfffafafa);
// menuItem.addSubItem(gallery_menu_edit_avatar, R.drawable.photo_paint, LocaleController.getString("EditPhoto", R.string.EditPhoto)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_set_as_main, R.drawable.menu_private, LocaleController.getString("SetAsMain", R.string.SetAsMain)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_delete, R.drawable.msg_delete, LocaleController.getString("Delete", R.string.Delete)).setColors(0xfffafafa, 0xfffafafa);
menuItem.addSubItem(gallery_menu_cancel_loading, R.drawable.msg_cancel, LocaleController.getString("StopDownload", R.string.StopDownload)).setColors(0xfffafafa, 0xfffafafa);
menuItem.redrawPopup(0xf9222222);
menuItemSpeed.redrawPopup(0xf9222222);
setMenuItemIcon();
menuItem.setSubMenuDelegate(new ActionBarMenuItem.ActionBarSubMenuItemDelegate() {
@Override
public void onShowSubMenu() {
if (videoPlayerControlVisible && isPlaying) {
AndroidUtilities.cancelRunOnUIThread(hideActionBarRunnable);
}
}
@Override
public void onHideSubMenu() {
if (videoPlayerControlVisible && isPlaying) {
scheduleActionBarHide();
}
}
});
bottomLayout = new FrameLayout(activityContext) {
@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
if (child == nameTextView || child == dateTextView) {
widthUsed = bottomButtonsLayout.getMeasuredWidth();
}
super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
};
bottomLayout.setBackgroundColor(0x7f000000);
containerView.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
pressedDrawable[0] = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[] { 0x32000000, 0 });
pressedDrawable[0].setShape(GradientDrawable.RECTANGLE);
pressedDrawable[1] = new GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, new int[] { 0x32000000, 0 });
pressedDrawable[1].setShape(GradientDrawable.RECTANGLE);
groupedPhotosListView = new GroupedPhotosListView(activityContext, AndroidUtilities.dp(10));
containerView.addView(groupedPhotosListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 68, Gravity.BOTTOM | Gravity.LEFT));
groupedPhotosListView.setDelegate(new GroupedPhotosListView.GroupedPhotosListViewDelegate() {
@Override
public int getCurrentIndex() {
return currentIndex;
}
@Override
public int getCurrentAccount() {
return currentAccount;
}
@Override
public long getAvatarsDialogId() {
return avatarsDialogId;
}
@Override
public int getSlideshowMessageId() {
return slideshowMessageId;
}
@Override
public ArrayList<ImageLocation> getImagesArrLocations() {
return imagesArrLocations;
}
@Override
public ArrayList<MessageObject> getImagesArr() {
return imagesArr;
}
@Override
public List<TLRPC.PageBlock> getPageBlockArr() {
return pageBlocksAdapter != null ? pageBlocksAdapter.getAll() : null;
}
@Override
public Object getParentObject() {
return pageBlocksAdapter != null ? pageBlocksAdapter.getParentObject() : null;
}
@Override
public void setCurrentIndex(int index) {
currentIndex = -1;
if (currentThumb != null) {
currentThumb.release();
currentThumb = null;
}
dontAutoPlay = true;
setImageIndex(index);
dontAutoPlay = false;
}
@Override
public void onShowAnimationStart() {
containerView.requestLayout();
}
@Override
public void onStopScrolling() {
if (shouldMessageObjectAutoPlayed(currentMessageObject)) {
playerAutoStarted = true;
onActionClick(true);
checkProgress(0, false, true);
}
}
@Override
public boolean validGroupId(long groupId) {
if (placeProvider != null) {
return placeProvider.validateGroupId(groupId);
}
return true;
}
});
for (int a = 0; a < 3; a++) {
fullscreenButton[a] = new ImageView(parentActivity);
fullscreenButton[a].setImageResource(R.drawable.msg_maxvideo);
fullscreenButton[a].setContentDescription(LocaleController.getString("AccSwitchToFullscreen", R.string.AccSwitchToFullscreen));
fullscreenButton[a].setScaleType(ImageView.ScaleType.CENTER);
fullscreenButton[a].setBackground(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
fullscreenButton[a].setVisibility(View.INVISIBLE);
fullscreenButton[a].setAlpha(1.0f);
containerView.addView(fullscreenButton[a], LayoutHelper.createFrame(48, 48));
fullscreenButton[a].setOnClickListener(v -> {
if (parentActivity == null) {
return;
}
wasRotated = false;
fullscreenedByButton = 1;
if (prevOrientation == -10) {
prevOrientation = parentActivity.getRequestedOrientation();
}
WindowManager manager = (WindowManager) parentActivity.getSystemService(Activity.WINDOW_SERVICE);
int displayRotation = manager.getDefaultDisplay().getRotation();
if (displayRotation == Surface.ROTATION_270) {
parentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
parentActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
toggleActionBar(false, false);
});
}
final LinkMovementMethod captionLinkMovementMethod = new CaptionLinkMovementMethod();
captionTextViewSwitcher = new CaptionTextViewSwitcher(containerView.getContext());
captionTextViewSwitcher.setFactory(() -> createCaptionTextView(captionLinkMovementMethod));
captionTextViewSwitcher.setVisibility(View.INVISIBLE);
setCaptionHwLayerEnabled(true);
for (int a = 0; a < 3; a++) {
photoProgressViews[a] = new PhotoProgressView(containerView) {
@Override
protected void onBackgroundStateUpdated(int state) {
if (this == photoProgressViews[0]) {
updateAccessibilityOverlayVisibility();
}
}
@Override
protected void onVisibilityChanged(boolean visible) {
if (this == photoProgressViews[0]) {
updateAccessibilityOverlayVisibility();
}
}
};
photoProgressViews[a].setBackgroundState(PROGRESS_EMPTY, false, true);
}
miniProgressView = new RadialProgressView(activityContext, resourcesProvider) {
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
if (containerView != null) {
containerView.invalidate();
}
}
@Override
public void invalidate() {
super.invalidate();
if (containerView != null) {
containerView.invalidate();
}
}
};
miniProgressView.setUseSelfAlpha(true);
miniProgressView.setProgressColor(0xffffffff);
miniProgressView.setSize(AndroidUtilities.dp(54));
miniProgressView.setBackgroundResource(R.drawable.circle_big);
miniProgressView.setVisibility(View.INVISIBLE);
miniProgressView.setAlpha(0.0f);
containerView.addView(miniProgressView, LayoutHelper.createFrame(64, 64, Gravity.CENTER));
bottomButtonsLayout = new LinearLayout(containerView.getContext());
bottomButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
bottomLayout.addView(bottomButtonsLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
paintButton = new ImageView(containerView.getContext());
paintButton.setImageResource(R.drawable.photo_paint);
paintButton.setScaleType(ImageView.ScaleType.CENTER);
paintButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
bottomButtonsLayout.addView(paintButton, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
paintButton.setOnClickListener(v -> openCurrentPhotoInPaintModeForSelect());
paintButton.setContentDescription(LocaleController.getString("AccDescrPhotoEditor", R.string.AccDescrPhotoEditor));
shareButton = new ImageView(containerView.getContext());
shareButton.setImageResource(R.drawable.share);
shareButton.setScaleType(ImageView.ScaleType.CENTER);
shareButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
bottomButtonsLayout.addView(shareButton, LayoutHelper.createFrame(50, LayoutHelper.MATCH_PARENT));
shareButton.setOnClickListener(v -> onSharePressed());
shareButton.setContentDescription(LocaleController.getString("ShareFile", R.string.ShareFile));
nameTextView = new FadingTextViewLayout(containerView.getContext()) {
@Override
protected void onTextViewCreated(TextView textView) {
super.onTextViewCreated(textView);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setTextColor(0xffffffff);
textView.setGravity(Gravity.LEFT);
}
};
bottomLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 5, 8, 0));
dateTextView = new FadingTextViewLayout(containerView.getContext(), true) {
private LocaleController.LocaleInfo lastLocaleInfo = null;
private int staticCharsCount = 0;
@Override
protected void onTextViewCreated(TextView textView) {
super.onTextViewCreated(textView);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setTextColor(0xffffffff);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setGravity(Gravity.LEFT);
}
@Override
protected int getStaticCharsCount() {
final LocaleController.LocaleInfo localeInfo = LocaleController.getInstance().getCurrentLocaleInfo();
if (lastLocaleInfo != localeInfo) {
lastLocaleInfo = localeInfo;
staticCharsCount = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date()), LocaleController.getInstance().formatterDay.format(new Date())).length();
}
return staticCharsCount;
}
@Override
public void setText(CharSequence text, boolean animated) {
if (animated) {
boolean dontAnimateUnchangedStaticChars = true;
if (LocaleController.isRTL) {
final int staticCharsCount = getStaticCharsCount();
if (staticCharsCount > 0) {
if (text.length() != staticCharsCount || getText() == null || getText().length() != staticCharsCount) {
dontAnimateUnchangedStaticChars = false;
}
}
}
setText(text, true, dontAnimateUnchangedStaticChars);
} else {
setText(text, false, false);
}
}
};
bottomLayout.addView(dateTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 16, 25, 8, 0));
createVideoControlsInterface();
progressView = new RadialProgressView(parentActivity, resourcesProvider);
progressView.setProgressColor(0xffffffff);
progressView.setBackgroundResource(R.drawable.circle_big);
progressView.setVisibility(View.INVISIBLE);
containerView.addView(progressView, LayoutHelper.createFrame(54, 54, Gravity.CENTER));
qualityPicker = new PickerBottomLayoutViewer(parentActivity);
qualityPicker.setBackgroundColor(0x7f000000);
qualityPicker.updateSelectedCount(0, false);
qualityPicker.setTranslationY(AndroidUtilities.dp(120));
qualityPicker.doneButton.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
qualityPicker.doneButton.setTextColor(getThemedColor(Theme.key_dialogFloatingButton));
containerView.addView(qualityPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM | Gravity.LEFT));
qualityPicker.cancelButton.setOnClickListener(view -> {
selectedCompression = previousCompression;
didChangedCompressionLevel(false);
showQualityView(false);
requestVideoPreview(2);
});
qualityPicker.doneButton.setOnClickListener(view -> {
showQualityView(false);
requestVideoPreview(2);
});
videoForwardDrawable = new VideoForwardDrawable(false);
videoForwardDrawable.setDelegate(new VideoForwardDrawable.VideoForwardDrawableDelegate() {
@Override
public void onAnimationEnd() {
}
@Override
public void invalidate() {
containerView.invalidate();
}
});
qualityChooseView = new QualityChooseView(parentActivity);
qualityChooseView.setTranslationY(AndroidUtilities.dp(120));
qualityChooseView.setVisibility(View.INVISIBLE);
qualityChooseView.setBackgroundColor(0x7f000000);
containerView.addView(qualityChooseView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 70, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
pickerView = new FrameLayout(activityContext) {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return bottomTouchEnabled && super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return bottomTouchEnabled && super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return bottomTouchEnabled && super.onTouchEvent(event);
}
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
videoTimelineView.setTranslationY(translationY);
videoAvatarTooltip.setTranslationY(translationY);
}
if (videoAvatarTooltip != null && videoAvatarTooltip.getVisibility() != GONE) {
videoAvatarTooltip.setTranslationY(translationY);
}
}
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
videoTimelineView.setAlpha(alpha);
}
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (videoTimelineView != null && videoTimelineView.getVisibility() != GONE) {
videoTimelineView.setVisibility(visibility == VISIBLE ? VISIBLE : INVISIBLE);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (itemsLayout.getVisibility() != GONE) {
int x = (right - left - AndroidUtilities.dp(70) - itemsLayout.getMeasuredWidth()) / 2;
itemsLayout.layout(x, itemsLayout.getTop(), x + itemsLayout.getMeasuredWidth(), itemsLayout.getTop() + itemsLayout.getMeasuredHeight());
}
}
};
pickerView.setBackgroundColor(0x7f000000);
containerView.addView(pickerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT));
docNameTextView = new TextView(containerView.getContext());
docNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
docNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
docNameTextView.setSingleLine(true);
docNameTextView.setMaxLines(1);
docNameTextView.setEllipsize(TextUtils.TruncateAt.END);
docNameTextView.setTextColor(0xffffffff);
docNameTextView.setGravity(Gravity.LEFT);
pickerView.addView(docNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 23, 84, 0));
docInfoTextView = new TextView(containerView.getContext());
docInfoTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
docInfoTextView.setSingleLine(true);
docInfoTextView.setMaxLines(1);
docInfoTextView.setEllipsize(TextUtils.TruncateAt.END);
docInfoTextView.setTextColor(0xffffffff);
docInfoTextView.setGravity(Gravity.LEFT);
pickerView.addView(docInfoTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 20, 46, 84, 0));
videoTimelineView = new VideoTimelinePlayView(parentActivity) {
@Override
public void setTranslationY(float translationY) {
if (getTranslationY() != translationY) {
super.setTranslationY(translationY);
containerView.invalidate();
}
}
};
videoTimelineView.setDelegate(new VideoTimelinePlayView.VideoTimelineViewDelegate() {
private Runnable seekToRunnable;
private int seekTo;
private boolean wasPlaying;
@Override
public void onLeftProgressChanged(float progress) {
if (videoPlayer == null) {
return;
}
if (videoPlayer.isPlaying()) {
manuallyPaused = false;
videoPlayer.pause();
containerView.invalidate();
}
updateAvatarStartTime(1);
seekTo(progress);
videoPlayerSeekbar.setProgress(0);
videoTimelineView.setProgress(progress);
updateVideoInfo();
}
@Override
public void onRightProgressChanged(float progress) {
if (videoPlayer == null) {
return;
}
if (videoPlayer.isPlaying()) {
manuallyPaused = false;
videoPlayer.pause();
containerView.invalidate();
}
updateAvatarStartTime(2);
seekTo(progress);
videoPlayerSeekbar.setProgress(1f);
videoTimelineView.setProgress(progress);
updateVideoInfo();
}
@Override
public void onPlayProgressChanged(float progress) {
if (videoPlayer == null) {
return;
}
if (sendPhotoType == SELECT_TYPE_AVATAR) {
updateAvatarStartTime(0);
}
seekTo(progress);
}
private void seekTo(float progress) {
seekTo = (int) (videoDuration * progress);
if (seekToRunnable == null) {
AndroidUtilities.runOnUIThread(seekToRunnable = () -> {
if (videoPlayer != null) {
videoPlayer.seekTo(seekTo);
}
if (sendPhotoType == SELECT_TYPE_AVATAR) {
needCaptureFrameReadyAtTime = seekTo;
if (captureFrameReadyAtTime != needCaptureFrameReadyAtTime) {
captureFrameReadyAtTime = -1;
}
}
seekToRunnable = null;
}, 100);
}
}
private void updateAvatarStartTime(int fix) {
if (sendPhotoType != SELECT_TYPE_AVATAR) {
return;
}
if (fix != 0) {
if (photoCropView != null && (videoTimelineView.getLeftProgress() > avatarStartProgress || videoTimelineView.getRightProgress() < avatarStartProgress)) {
photoCropView.setVideoThumbVisible(false);
if (fix == 1) {
avatarStartTime = (long) (videoDuration * 1000 * videoTimelineView.getLeftProgress());
} else {
avatarStartTime = (long) (videoDuration * 1000 * videoTimelineView.getRightProgress());
}
captureFrameAtTime = -1;
}
} else {
avatarStartProgress = videoTimelineView.getProgress();
avatarStartTime = (long) (videoDuration * 1000 * avatarStartProgress);
}
}
@Override
public void didStartDragging(int type) {
if (type == VideoTimelinePlayView.TYPE_PROGRESS) {
cancelVideoPlayRunnable();
if (sendPhotoType == SELECT_TYPE_AVATAR) {
cancelFlashAnimations();
captureFrameAtTime = -1;
}
if (wasPlaying = videoPlayer != null && videoPlayer.isPlaying()) {
manuallyPaused = false;
videoPlayer.pause();
containerView.invalidate();
}
}
}
@Override
public void didStopDragging(int type) {
if (seekToRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(seekToRunnable);
seekToRunnable.run();
}
cancelVideoPlayRunnable();
if (sendPhotoType == SELECT_TYPE_AVATAR && flashView != null && type == VideoTimelinePlayView.TYPE_PROGRESS) {
cancelFlashAnimations();
captureFrameAtTime = avatarStartTime;
if (captureFrameReadyAtTime == seekTo) {
captureCurrentFrame();
}
} else {
if (sendPhotoType == SELECT_TYPE_AVATAR || wasPlaying) {
manuallyPaused = false;
if (videoPlayer != null) {
videoPlayer.play();
}
}
}
}
});
showVideoTimeline(false, false);
videoTimelineView.setBackgroundColor(0x7f000000);
containerView.addView(videoTimelineView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 58, Gravity.LEFT | Gravity.BOTTOM, 0, 8, 0, 0));
videoAvatarTooltip = new TextView(parentActivity);
videoAvatarTooltip.setSingleLine(true);
videoAvatarTooltip.setVisibility(View.GONE);
videoAvatarTooltip.setText(LocaleController.getString("ChooseCover", R.string.ChooseCover));
videoAvatarTooltip.setGravity(Gravity.CENTER_HORIZONTAL);
videoAvatarTooltip.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
videoAvatarTooltip.setTextColor(0xff8c8c8c);
containerView.addView(videoAvatarTooltip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 0, 8, 0, 0));
pickerViewSendButton = new ImageView(parentActivity) {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return bottomTouchEnabled && super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return bottomTouchEnabled && super.onTouchEvent(event);
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (captionEditText.getCaptionLimitOffset() < 0) {
captionLimitView.setVisibility(visibility);
} else {
captionLimitView.setVisibility(View.GONE);
}
}
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
captionLimitView.setTranslationY(translationY);
}
@Override
public void setAlpha(float alpha) {
super.setAlpha(alpha);
captionLimitView.setAlpha(alpha);
}
};
pickerViewSendButton.setScaleType(ImageView.ScaleType.CENTER);
pickerViewSendDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton));
pickerViewSendButton.setBackgroundDrawable(pickerViewSendDrawable);
pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(0xffffffff, PorterDuff.Mode.MULTIPLY));
pickerViewSendButton.setImageResource(R.drawable.attach_send);
pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
containerView.addView(pickerViewSendButton, LayoutHelper.createFrame(56, 56, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 14, 14));
pickerViewSendButton.setContentDescription(LocaleController.getString("Send", R.string.Send));
pickerViewSendButton.setOnClickListener(v -> {
if (captionEditText.getCaptionLimitOffset() < 0) {
AndroidUtilities.shakeView(captionLimitView, 2, 0);
Vibrator vibrator = (Vibrator) captionLimitView.getContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
vibrator.vibrate(200);
}
return;
}
if (parentChatActivity != null && parentChatActivity.isInScheduleMode() && !parentChatActivity.isEditingMessageMedia()) {
showScheduleDatePickerDialog();
} else {
sendPressed(true, 0);
}
});
pickerViewSendButton.setOnLongClickListener(view -> {
if (placeProvider != null && !placeProvider.allowSendingSubmenu()) {
return false;
}
if (parentChatActivity == null || parentChatActivity.isInScheduleMode()) {
return false;
}
if (captionEditText.getCaptionLimitOffset() < 0) {
return false;
}
TLRPC.Chat chat = parentChatActivity.getCurrentChat();
TLRPC.User user = parentChatActivity.getCurrentUser();
sendPopupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(parentActivity);
sendPopupLayout.setAnimationEnabled(false);
sendPopupLayout.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
v.getHitRect(hitRect);
if (!hitRect.contains((int) event.getX(), (int) event.getY())) {
sendPopupWindow.dismiss();
}
}
}
return false;
});
sendPopupLayout.setDispatchKeyEventListener(keyEvent -> {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
});
sendPopupLayout.setShownFromBotton(false);
sendPopupLayout.setBackgroundColor(0xf9222222);
final boolean canReplace = placeProvider != null && placeProvider.canReplace(currentIndex);
final int[] order = { 4, 3, 2, 0, 1 };
for (int i = 0; i < 5; i++) {
final int a = order[i];
if (a != 2 && a != 3 && canReplace) {
continue;
}
if (a == 0 && !parentChatActivity.canScheduleMessage()) {
continue;
}
if (a == 0 && placeProvider != null && placeProvider.getSelectedPhotos() != null) {
HashMap<Object, Object> hashMap = placeProvider.getSelectedPhotos();
boolean hasTtl = false;
for (HashMap.Entry<Object, Object> entry : hashMap.entrySet()) {
Object object = entry.getValue();
if (object instanceof MediaController.PhotoEntry) {
MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) object;
if (photoEntry.ttl != 0) {
hasTtl = true;
break;
}
} else if (object instanceof MediaController.SearchImage) {
MediaController.SearchImage searchImage = (MediaController.SearchImage) object;
if (searchImage.ttl != 0) {
hasTtl = true;
break;
}
}
}
if (hasTtl) {
continue;
}
} else if (a == 1 && UserObject.isUserSelf(user)) {
continue;
} else if ((a == 2 || a == 3) && !canReplace) {
continue;
} else if (a == 4 && (isCurrentVideo || timeItem.getColorFilter() != null)) {
continue;
}
ActionBarMenuSubItem cell = new ActionBarMenuSubItem(parentActivity, a == 0, a == 3, resourcesProvider);
if (a == 0) {
if (UserObject.isUserSelf(user)) {
cell.setTextAndIcon(LocaleController.getString("SetReminder", R.string.SetReminder), R.drawable.msg_schedule);
} else {
cell.setTextAndIcon(LocaleController.getString("ScheduleMessage", R.string.ScheduleMessage), R.drawable.msg_schedule);
}
} else if (a == 1) {
cell.setTextAndIcon(LocaleController.getString("SendWithoutSound", R.string.SendWithoutSound), R.drawable.input_notify_off);
} else if (a == 2) {
cell.setTextAndIcon(LocaleController.getString("ReplacePhoto", R.string.ReplacePhoto), R.drawable.msg_replace);
} else if (a == 3) {
cell.setTextAndIcon(LocaleController.getString("SendAsNewPhoto", R.string.SendAsNewPhoto), R.drawable.msg_sendphoto);
} else if (a == 4) {
cell.setTextAndIcon(LocaleController.getString("SendWithoutCompression", R.string.SendWithoutCompression), R.drawable.msg_sendfile);
}
cell.setMinimumWidth(AndroidUtilities.dp(196));
cell.setColors(0xffffffff, 0xffffffff);
sendPopupLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
cell.setOnClickListener(v -> {
if (sendPopupWindow != null && sendPopupWindow.isShowing()) {
sendPopupWindow.dismiss();
}
if (a == 0) {
showScheduleDatePickerDialog();
} else if (a == 1) {
sendPressed(false, 0);
} else if (a == 2) {
replacePressed();
} else if (a == 3) {
sendPressed(true, 0);
} else if (a == 4) {
sendPressed(true, 0, false, true);
}
});
}
if (sendPopupLayout.getChildCount() == 0) {
return false;
}
sendPopupLayout.setupRadialSelectors(0x24ffffff);
sendPopupWindow = new ActionBarPopupWindow(sendPopupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
sendPopupWindow.setAnimationEnabled(false);
sendPopupWindow.setAnimationStyle(R.style.PopupContextAnimation2);
sendPopupWindow.setOutsideTouchable(true);
sendPopupWindow.setClippingEnabled(true);
sendPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
sendPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
sendPopupWindow.getContentView().setFocusableInTouchMode(true);
sendPopupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
sendPopupWindow.setFocusable(true);
int[] location = new int[2];
view.getLocationInWindow(location);
sendPopupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, location[0] + view.getMeasuredWidth() - sendPopupLayout.getMeasuredWidth() + AndroidUtilities.dp(14), location[1] - sendPopupLayout.getMeasuredHeight() - AndroidUtilities.dp(18));
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
return false;
});
captionLimitView = new TextView(parentActivity);
captionLimitView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
captionLimitView.setTextColor(0xffEC7777);
captionLimitView.setGravity(Gravity.CENTER);
captionLimitView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
containerView.addView(captionLimitView, LayoutHelper.createFrame(56, 20, Gravity.BOTTOM | Gravity.RIGHT, 3, 0, 14, 78));
itemsLayout = new LinearLayout(parentActivity) {
boolean ignoreLayout;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int visibleItemsCount = 0;
int count = getChildCount();
for (int a = 0; a < count; a++) {
View v = getChildAt(a);
if (v.getVisibility() != VISIBLE) {
continue;
}
visibleItemsCount++;
}
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (visibleItemsCount != 0) {
int itemWidth = Math.min(AndroidUtilities.dp(70), width / visibleItemsCount);
if (compressItem.getVisibility() == VISIBLE) {
ignoreLayout = true;
int compressIconWidth;
if (selectedCompression < 2) {
compressIconWidth = 48;
} else {
compressIconWidth = 64;
}
int padding = Math.max(0, (itemWidth - AndroidUtilities.dp(compressIconWidth)) / 2);
compressItem.setPadding(padding, 0, padding, 0);
ignoreLayout = false;
}
for (int a = 0; a < count; a++) {
View v = getChildAt(a);
if (v.getVisibility() == GONE) {
continue;
}
v.measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
setMeasuredDimension(itemWidth * visibleItemsCount, height);
} else {
setMeasuredDimension(width, height);
}
}
};
itemsLayout.setOrientation(LinearLayout.HORIZONTAL);
pickerView.addView(itemsLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 0, 70, 0));
cropItem = new ImageView(parentActivity);
cropItem.setScaleType(ImageView.ScaleType.CENTER);
cropItem.setImageResource(R.drawable.photo_crop);
cropItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
itemsLayout.addView(cropItem, LayoutHelper.createLinear(48, 48));
cropItem.setOnClickListener(v -> {
if (captionEditText.getTag() != null) {
return;
}
if (isCurrentVideo) {
if (!videoConvertSupported) {
return;
}
if (videoTextureView instanceof VideoEditTextureView) {
VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
return;
}
} else {
return;
}
}
switchToEditMode(1);
});
cropItem.setContentDescription(LocaleController.getString("CropImage", R.string.CropImage));
rotateItem = new ImageView(parentActivity);
rotateItem.setScaleType(ImageView.ScaleType.CENTER);
rotateItem.setImageResource(R.drawable.tool_rotate);
rotateItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
itemsLayout.addView(rotateItem, LayoutHelper.createLinear(48, 48));
rotateItem.setOnClickListener(v -> {
if (photoCropView == null) {
return;
}
if (photoCropView.rotate()) {
rotateItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY));
} else {
rotateItem.setColorFilter(null);
}
});
rotateItem.setContentDescription(LocaleController.getString("AccDescrRotate", R.string.AccDescrRotate));
mirrorItem = new ImageView(parentActivity);
mirrorItem.setScaleType(ImageView.ScaleType.CENTER);
mirrorItem.setImageResource(R.drawable.photo_flip);
mirrorItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
itemsLayout.addView(mirrorItem, LayoutHelper.createLinear(48, 48));
mirrorItem.setOnClickListener(v -> {
if (photoCropView == null) {
return;
}
if (photoCropView.mirror()) {
mirrorItem.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY));
} else {
mirrorItem.setColorFilter(null);
}
});
mirrorItem.setContentDescription(LocaleController.getString("AccDescrMirror", R.string.AccDescrMirror));
paintItem = new ImageView(parentActivity);
paintItem.setScaleType(ImageView.ScaleType.CENTER);
paintItem.setImageResource(R.drawable.photo_paint);
paintItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
itemsLayout.addView(paintItem, LayoutHelper.createLinear(48, 48));
paintItem.setOnClickListener(v -> {
if (captionEditText.getTag() != null) {
return;
}
if (isCurrentVideo) {
if (!videoConvertSupported) {
return;
}
if (videoTextureView instanceof VideoEditTextureView) {
VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
return;
}
} else {
return;
}
}
switchToEditMode(3);
});
paintItem.setContentDescription(LocaleController.getString("AccDescrPhotoEditor", R.string.AccDescrPhotoEditor));
muteItem = new ImageView(parentActivity);
muteItem.setScaleType(ImageView.ScaleType.CENTER);
muteItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
containerView.addView(muteItem, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 16, 0, 0, 0));
muteItem.setOnClickListener(v -> {
if (captionEditText.getTag() != null) {
return;
}
muteVideo = !muteVideo;
updateMuteButton();
updateVideoInfo();
if (muteVideo && !checkImageView.isChecked()) {
checkImageView.callOnClick();
} else {
Object object = imagesArrLocals.get(currentIndex);
if (object instanceof MediaController.MediaEditState) {
((MediaController.MediaEditState) object).editedInfo = getCurrentVideoEditedInfo();
}
}
});
cameraItem = new ImageView(parentActivity);
cameraItem.setScaleType(ImageView.ScaleType.CENTER);
cameraItem.setImageResource(R.drawable.photo_add);
cameraItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
cameraItem.setContentDescription(LocaleController.getString("AccDescrTakeMorePics", R.string.AccDescrTakeMorePics));
containerView.addView(cameraItem, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 16, 0));
cameraItem.setOnClickListener(v -> {
if (placeProvider == null || captionEditText.getTag() != null) {
return;
}
placeProvider.needAddMorePhotos();
closePhoto(true, false);
});
tuneItem = new ImageView(parentActivity);
tuneItem.setScaleType(ImageView.ScaleType.CENTER);
tuneItem.setImageResource(R.drawable.photo_tools);
tuneItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
itemsLayout.addView(tuneItem, LayoutHelper.createLinear(48, 48));
tuneItem.setOnClickListener(v -> {
if (captionEditText.getTag() != null) {
return;
}
if (isCurrentVideo) {
if (!videoConvertSupported) {
return;
}
if (videoTextureView instanceof VideoEditTextureView) {
VideoEditTextureView textureView = (VideoEditTextureView) videoTextureView;
if (textureView.getVideoWidth() <= 0 || textureView.getVideoHeight() <= 0) {
return;
}
} else {
return;
}
}
switchToEditMode(2);
});
tuneItem.setContentDescription(LocaleController.getString("AccDescrPhotoAdjust", R.string.AccDescrPhotoAdjust));
compressItem = new ImageView(parentActivity);
compressItem.setTag(1);
compressItem.setScaleType(ImageView.ScaleType.CENTER);
compressItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
selectedCompression = selectCompression();
int compressIconWidth;
if (selectedCompression <= 1) {
compressItem.setImageResource(R.drawable.video_quality1);
} else if (selectedCompression == 2) {
compressItem.setImageResource(R.drawable.video_quality2);
} else {
selectedCompression = compressionsCount - 1;
compressItem.setImageResource(R.drawable.video_quality3);
}
compressItem.setContentDescription(LocaleController.getString("AccDescrVideoQuality", R.string.AccDescrVideoQuality));
itemsLayout.addView(compressItem, LayoutHelper.createLinear(48, 48));
compressItem.setOnClickListener(v -> {
if (captionEditText.getTag() != null || muteVideo) {
return;
}
if (compressItem.getTag() == null) {
if (videoConvertSupported) {
if (tooltip == null) {
tooltip = new Tooltip(activity, containerView, 0xcc111111, Color.WHITE);
}
tooltip.setText(LocaleController.getString("VideoQualityIsTooLow", R.string.VideoQualityIsTooLow));
tooltip.show(compressItem);
}
return;
}
showQualityView(true);
requestVideoPreview(1);
});
timeItem = new ImageView(parentActivity);
timeItem.setScaleType(ImageView.ScaleType.CENTER);
timeItem.setImageResource(R.drawable.photo_timer);
timeItem.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
timeItem.setContentDescription(LocaleController.getString("SetTimer", R.string.SetTimer));
itemsLayout.addView(timeItem, LayoutHelper.createLinear(48, 48));
timeItem.setOnClickListener(v -> {
if (parentActivity == null || captionEditText.getTag() != null) {
return;
}
BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity, false, resourcesProvider);
builder.setUseHardwareLayer(false);
LinearLayout linearLayout = new LinearLayout(parentActivity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
builder.setCustomView(linearLayout);
TextView titleView = new TextView(parentActivity);
titleView.setLines(1);
titleView.setSingleLine(true);
titleView.setText(LocaleController.getString("MessageLifetime", R.string.MessageLifetime));
titleView.setTextColor(0xffffffff);
titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(8), AndroidUtilities.dp(21), AndroidUtilities.dp(4));
titleView.setGravity(Gravity.CENTER_VERTICAL);
linearLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
titleView.setOnTouchListener((v13, event) -> true);
titleView = new TextView(parentActivity);
titleView.setText(isCurrentVideo ? LocaleController.getString("MessageLifetimeVideo", R.string.MessageLifetimeVideo) : LocaleController.getString("MessageLifetimePhoto", R.string.MessageLifetimePhoto));
titleView.setTextColor(0xff808080);
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), AndroidUtilities.dp(8));
titleView.setGravity(Gravity.CENTER_VERTICAL);
linearLayout.addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
titleView.setOnTouchListener((v12, event) -> true);
final BottomSheet bottomSheet = builder.create();
final NumberPicker numberPicker = new NumberPicker(parentActivity, resourcesProvider);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(28);
Object object = imagesArrLocals.get(currentIndex);
int currentTTL;
if (object instanceof MediaController.PhotoEntry) {
currentTTL = ((MediaController.PhotoEntry) object).ttl;
} else if (object instanceof MediaController.SearchImage) {
currentTTL = ((MediaController.SearchImage) object).ttl;
} else {
currentTTL = 0;
}
if (currentTTL == 0) {
SharedPreferences preferences1 = MessagesController.getGlobalMainSettings();
numberPicker.setValue(preferences1.getInt("self_destruct", 7));
} else {
if (currentTTL >= 0 && currentTTL < 21) {
numberPicker.setValue(currentTTL);
} else {
numberPicker.setValue(21 + currentTTL / 5 - 5);
}
}
numberPicker.setTextColor(0xffffffff);
numberPicker.setSelectorColor(0xff4d4d4d);
numberPicker.setFormatter(value -> {
if (value == 0) {
return LocaleController.getString("ShortMessageLifetimeForever", R.string.ShortMessageLifetimeForever);
} else if (value >= 1 && value < 21) {
return LocaleController.formatTTLString(value);
} else {
return LocaleController.formatTTLString((value - 16) * 5);
}
});
linearLayout.addView(numberPicker, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
FrameLayout buttonsLayout = new FrameLayout(parentActivity) {
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int count = getChildCount();
int width = right - left;
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
if ((Integer) child.getTag() == Dialog.BUTTON_POSITIVE) {
child.layout(width - getPaddingRight() - child.getMeasuredWidth(), getPaddingTop(), width - getPaddingRight(), getPaddingTop() + child.getMeasuredHeight());
} else if ((Integer) child.getTag() == Dialog.BUTTON_NEGATIVE) {
int x = getPaddingLeft();
child.layout(x, getPaddingTop(), x + child.getMeasuredWidth(), getPaddingTop() + child.getMeasuredHeight());
} else {
child.layout(getPaddingLeft(), getPaddingTop(), getPaddingLeft() + child.getMeasuredWidth(), getPaddingTop() + child.getMeasuredHeight());
}
}
}
};
buttonsLayout.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8), AndroidUtilities.dp(8));
linearLayout.addView(buttonsLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 52));
TextView textView = new TextView(parentActivity);
textView.setMinWidth(AndroidUtilities.dp(64));
textView.setTag(Dialog.BUTTON_POSITIVE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(getThemedColor(Theme.key_dialogFloatingButton));
textView.setGravity(Gravity.CENTER);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(0xff49bcf2));
textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
buttonsLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.TOP | Gravity.RIGHT));
textView.setOnClickListener(v1 -> {
int value = numberPicker.getValue();
SharedPreferences preferences1 = MessagesController.getGlobalMainSettings();
SharedPreferences.Editor editor = preferences1.edit();
editor.putInt("self_destruct", value);
editor.commit();
bottomSheet.dismiss();
int seconds;
if (value >= 0 && value < 21) {
seconds = value;
} else {
seconds = (value - 16) * 5;
}
Object object1 = imagesArrLocals.get(currentIndex);
if (object1 instanceof MediaController.PhotoEntry) {
((MediaController.PhotoEntry) object1).ttl = seconds;
} else if (object1 instanceof MediaController.SearchImage) {
((MediaController.SearchImage) object1).ttl = seconds;
}
timeItem.setColorFilter(seconds != 0 ? new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingButton), PorterDuff.Mode.MULTIPLY) : null);
if (!checkImageView.isChecked()) {
checkImageView.callOnClick();
}
});
textView = new TextView(parentActivity);
textView.setMinWidth(AndroidUtilities.dp(64));
textView.setTag(Dialog.BUTTON_NEGATIVE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(0xffffffff);
textView.setGravity(Gravity.CENTER);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
textView.setBackgroundDrawable(Theme.getRoundRectSelectorDrawable(0xffffffff));
textView.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), 0);
buttonsLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 36, Gravity.TOP | Gravity.RIGHT));
textView.setOnClickListener(v14 -> bottomSheet.dismiss());
bottomSheet.show();
bottomSheet.setBackgroundColor(0xff000000);
});
editorDoneLayout = new PickerBottomLayoutViewer(activityContext);
editorDoneLayout.setBackgroundColor(0xcc000000);
editorDoneLayout.updateSelectedCount(0, false);
editorDoneLayout.setVisibility(View.GONE);
containerView.addView(editorDoneLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
editorDoneLayout.cancelButton.setOnClickListener(view -> {
cropTransform.setViewTransform(previousHasTransform, previousCropPx, previousCropPy, previousCropRotation, previousCropOrientation, previousCropScale, 1.0f, 1.0f, previousCropPw, previousCropPh, 0, 0, previousCropMirrored);
switchToEditMode(0);
});
editorDoneLayout.doneButton.setOnClickListener(view -> {
if (currentEditMode == 1 && !photoCropView.isReady()) {
return;
}
applyCurrentEditMode();
switchToEditMode(0);
});
resetButton = new TextView(activityContext);
resetButton.setVisibility(View.GONE);
resetButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
resetButton.setTextColor(0xffffffff);
resetButton.setGravity(Gravity.CENTER);
resetButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_PICKER_SELECTOR_COLOR, 0));
resetButton.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
resetButton.setText(LocaleController.getString("Reset", R.string.CropReset).toUpperCase());
resetButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
editorDoneLayout.addView(resetButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.CENTER));
resetButton.setOnClickListener(v -> photoCropView.reset());
gestureDetector = new GestureDetector2(containerView.getContext(), this);
gestureDetector.setIsLongpressEnabled(false);
setDoubleTapEnabled(true);
ImageReceiver.ImageReceiverDelegate imageReceiverDelegate = (imageReceiver, set, thumb, memCache) -> {
if (imageReceiver == centerImage && set && !thumb) {
if (!isCurrentVideo && (currentEditMode == 1 || sendPhotoType == SELECT_TYPE_AVATAR) && photoCropView != null) {
Bitmap bitmap = imageReceiver.getBitmap();
if (bitmap != null) {
photoCropView.setBitmap(bitmap, imageReceiver.getOrientation(), sendPhotoType != SELECT_TYPE_AVATAR, true, paintingOverlay, cropTransform, null, null);
}
}
if (paintingOverlay.getVisibility() == View.VISIBLE) {
containerView.requestLayout();
}
detectFaces();
}
if (imageReceiver == centerImage && set && placeProvider != null && placeProvider.scaleToFill() && !ignoreDidSetImage && sendPhotoType != SELECT_TYPE_AVATAR) {
if (!wasLayout) {
dontResetZoomOnFirstLayout = true;
} else {
setScaleToFill();
}
}
};
centerImage.setParentView(containerView);
centerImage.setCrossfadeAlpha((byte) 2);
centerImage.setInvalidateAll(true);
centerImage.setDelegate(imageReceiverDelegate);
leftImage.setParentView(containerView);
leftImage.setCrossfadeAlpha((byte) 2);
leftImage.setInvalidateAll(true);
leftImage.setDelegate(imageReceiverDelegate);
rightImage.setParentView(containerView);
rightImage.setCrossfadeAlpha((byte) 2);
rightImage.setInvalidateAll(true);
rightImage.setDelegate(imageReceiverDelegate);
WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Activity.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();
checkImageView = new CheckBox(containerView.getContext(), R.drawable.selectphoto_large) {
@Override
public boolean onTouchEvent(MotionEvent event) {
return bottomTouchEnabled && super.onTouchEvent(event);
}
};
checkImageView.setDrawBackground(true);
checkImageView.setHasBorder(true);
checkImageView.setSize(34);
checkImageView.setCheckOffset(AndroidUtilities.dp(1));
checkImageView.setColor(getThemedColor(Theme.key_dialogFloatingButton), 0xffffffff);
checkImageView.setVisibility(View.GONE);
containerView.addView(checkImageView, LayoutHelper.createFrame(34, 34, Gravity.RIGHT | Gravity.TOP, 0, rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 61 : 71, 11, 0));
if (isStatusBarVisible()) {
((FrameLayout.LayoutParams) checkImageView.getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
}
checkImageView.setOnClickListener(v -> {
if (captionEditText.getTag() != null) {
return;
}
setPhotoChecked();
});
photosCounterView = new CounterView(parentActivity);
containerView.addView(photosCounterView, LayoutHelper.createFrame(40, 40, Gravity.RIGHT | Gravity.TOP, 0, rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90 ? 58 : 68, 64, 0));
if (isStatusBarVisible()) {
((FrameLayout.LayoutParams) photosCounterView.getLayoutParams()).topMargin += AndroidUtilities.statusBarHeight;
}
photosCounterView.setOnClickListener(v -> {
if (captionEditText.getTag() != null || placeProvider == null || placeProvider.getSelectedPhotosOrder() == null || placeProvider.getSelectedPhotosOrder().isEmpty()) {
return;
}
togglePhotosListView(!isPhotosListViewVisible, true);
});
selectedPhotosListView = new SelectedPhotosListView(parentActivity);
selectedPhotosListView.setVisibility(View.GONE);
selectedPhotosListView.setAlpha(0.0f);
selectedPhotosListView.setLayoutManager(new LinearLayoutManager(parentActivity, LinearLayoutManager.HORIZONTAL, true) {
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScrollerEnd linearSmoothScroller = new LinearSmoothScrollerEnd(recyclerView.getContext()) {
@Override
protected int calculateTimeForDeceleration(int dx) {
return Math.max(180, super.calculateTimeForDeceleration(dx));
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
});
selectedPhotosListView.setAdapter(selectedPhotosAdapter = new ListAdapter(parentActivity));
containerView.addView(selectedPhotosListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 103, Gravity.LEFT | Gravity.TOP));
selectedPhotosListView.setOnItemClickListener((view, position) -> {
if (!imagesArrLocals.isEmpty() && currentIndex >= 0 && currentIndex < imagesArrLocals.size()) {
Object entry = imagesArrLocals.get(currentIndex);
if (entry instanceof MediaController.MediaEditState) {
((MediaController.MediaEditState) entry).editedInfo = getCurrentVideoEditedInfo();
}
}
ignoreDidSetImage = true;
int idx = imagesArrLocals.indexOf(view.getTag());
if (idx >= 0) {
currentIndex = -1;
setImageIndex(idx);
}
ignoreDidSetImage = false;
});
captionEditText = new PhotoViewerCaptionEnterView(activityContext, containerView, windowView, resourcesProvider) {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
try {
return !bottomTouchEnabled && super.dispatchTouchEvent(ev);
} catch (Exception e) {
FileLog.e(e);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
try {
return !bottomTouchEnabled && super.onInterceptTouchEvent(ev);
} catch (Exception e) {
FileLog.e(e);
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (bottomTouchEnabled && event.getAction() == MotionEvent.ACTION_DOWN) {
keyboardAnimationEnabled = true;
}
return !bottomTouchEnabled && super.onTouchEvent(event);
}
@Override
protected void extendActionMode(ActionMode actionMode, Menu menu) {
if (parentChatActivity != null) {
parentChatActivity.extendActionMode(menu);
}
}
};
captionEditText.setDelegate(new PhotoViewerCaptionEnterView.PhotoViewerCaptionEnterViewDelegate() {
@Override
public void onCaptionEnter() {
closeCaptionEnter(true);
}
@Override
public void onTextChanged(CharSequence text) {
if (mentionsAdapter != null && captionEditText != null && parentChatActivity != null && text != null) {
mentionsAdapter.searchUsernameOrHashtag(text.toString(), captionEditText.getCursorPosition(), parentChatActivity.messages, false, false);
}
int color = getThemedColor(Theme.key_dialogFloatingIcon);
if (captionEditText.getCaptionLimitOffset() < 0) {
captionLimitView.setText(Integer.toString(captionEditText.getCaptionLimitOffset()));
captionLimitView.setVisibility(pickerViewSendButton.getVisibility());
pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * 0.58f)), PorterDuff.Mode.MULTIPLY));
} else {
pickerViewSendButton.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
captionLimitView.setVisibility(View.GONE);
}
if (placeProvider != null) {
placeProvider.onCaptionChanged(text);
}
}
@Override
public void onWindowSizeChanged(int size) {
int height = AndroidUtilities.dp(36 * Math.min(3, mentionsAdapter.getItemCount()) + (mentionsAdapter.getItemCount() > 3 ? 18 : 0));
if (size - ActionBar.getCurrentActionBarHeight() * 2 < height) {
allowMentions = false;
if (mentionListView != null && mentionListView.getVisibility() == View.VISIBLE) {
mentionListView.setVisibility(View.INVISIBLE);
}
} else {
allowMentions = true;
if (mentionListView != null && mentionListView.getVisibility() == View.INVISIBLE) {
mentionListView.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onEmojiViewCloseStart() {
setOffset(captionEditText.getEmojiPadding());
if (captionEditText.getTag() != null) {
if (isCurrentVideo) {
actionBar.setTitleAnimated(muteVideo ? LocaleController.getString("GifCaption", R.string.GifCaption) : LocaleController.getString("VideoCaption", R.string.VideoCaption), true, 220);
} else {
actionBar.setTitleAnimated(LocaleController.getString("PhotoCaption", R.string.PhotoCaption), true, 220);
}
checkImageView.animate().alpha(0f).setDuration(220).start();
photosCounterView.animate().alpha(0f).setDuration(220).start();
selectedPhotosListView.animate().alpha(0.0f).translationY(-AndroidUtilities.dp(10)).setDuration(220).start();
} else {
checkImageView.animate().alpha(1f).setDuration(220).start();
photosCounterView.animate().alpha(1f).setDuration(220).start();
if (lastTitle != null) {
actionBar.setTitleAnimated(lastTitle, false, 220);
lastTitle = null;
}
}
}
@Override
public void onEmojiViewCloseEnd() {
setOffset(0);
captionEditText.setVisibility(View.GONE);
}
private void setOffset(int offset) {
for (int i = 0; i < containerView.getChildCount(); i++) {
View child = containerView.getChildAt(i);
if (child == cameraItem || child == muteItem || child == pickerView || child == videoTimelineView || child == pickerViewSendButton || child == captionTextViewSwitcher || muteItem.getVisibility() == View.VISIBLE && child == bottomLayout) {
child.setTranslationY(offset);
}
}
}
});
if (Build.VERSION.SDK_INT >= 19) {
captionEditText.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
captionEditText.setVisibility(View.GONE);
containerView.addView(captionEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT));
mentionListView = new RecyclerListView(activityContext, resourcesProvider) {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return !bottomTouchEnabled && super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return !bottomTouchEnabled && super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return !bottomTouchEnabled && super.onTouchEvent(event);
}
};
mentionListView.setTag(5);
mentionLayoutManager = new LinearLayoutManager(activityContext) {
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
};
mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mentionListView.setLayoutManager(mentionLayoutManager);
mentionListView.setBackgroundColor(0x7f000000);
mentionListView.setVisibility(View.GONE);
mentionListView.setClipToPadding(true);
mentionListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
containerView.addView(mentionListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));
mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(activityContext, true, 0, 0, new MentionsAdapter.MentionsAdapterDelegate() {
@Override
public void needChangePanelVisibility(boolean show) {
if (show) {
FrameLayout.LayoutParams layoutParams3 = (FrameLayout.LayoutParams) mentionListView.getLayoutParams();
int height = 36 * Math.min(3, mentionsAdapter.getItemCount()) + (mentionsAdapter.getItemCount() > 3 ? 18 : 0);
layoutParams3.height = AndroidUtilities.dp(height);
layoutParams3.topMargin = -AndroidUtilities.dp(height);
mentionListView.setLayoutParams(layoutParams3);
if (mentionListAnimation != null) {
mentionListAnimation.cancel();
mentionListAnimation = null;
}
if (mentionListView.getVisibility() == View.VISIBLE) {
mentionListView.setAlpha(1.0f);
return;
} else {
mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
}
if (allowMentions) {
mentionListView.setVisibility(View.VISIBLE);
mentionListAnimation = new AnimatorSet();
mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionListView, View.ALPHA, 0.0f, 1.0f));
mentionListAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionListAnimation = null;
}
}
});
mentionListAnimation.setDuration(200);
mentionListAnimation.start();
} else {
mentionListView.setAlpha(1.0f);
mentionListView.setVisibility(View.INVISIBLE);
}
} else {
if (mentionListAnimation != null) {
mentionListAnimation.cancel();
mentionListAnimation = null;
}
if (mentionListView.getVisibility() == View.GONE) {
return;
}
if (allowMentions) {
mentionListAnimation = new AnimatorSet();
mentionListAnimation.playTogether(ObjectAnimator.ofFloat(mentionListView, View.ALPHA, 0.0f));
mentionListAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (mentionListAnimation != null && mentionListAnimation.equals(animation)) {
mentionListView.setVisibility(View.GONE);
mentionListAnimation = null;
}
}
});
mentionListAnimation.setDuration(200);
mentionListAnimation.start();
} else {
mentionListView.setVisibility(View.GONE);
}
}
}
@Override
public void onContextSearch(boolean searching) {
}
@Override
public void onContextClick(TLRPC.BotInlineResult result) {
}
}, resourcesProvider));
mentionListView.setOnItemClickListener((view, position) -> {
Object object = mentionsAdapter.getItem(position);
int start = mentionsAdapter.getResultStartPosition();
int len = mentionsAdapter.getResultLength();
if (object instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) object;
if (user.username != null) {
captionEditText.replaceWithText(start, len, "@" + user.username + " ", false);
} else {
String name = UserObject.getFirstName(user);
Spannable spannable = new SpannableString(name + " ");
spannable.setSpan(new URLSpanUserMentionPhotoViewer("" + user.id, true), 0, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
captionEditText.replaceWithText(start, len, spannable, false);
}
} else if (object instanceof String) {
captionEditText.replaceWithText(start, len, object + " ", false);
} else if (object instanceof MediaDataController.KeywordResult) {
String code = ((MediaDataController.KeywordResult) object).emoji;
captionEditText.addEmojiToRecent(code);
captionEditText.replaceWithText(start, len, code, true);
}
});
mentionListView.setOnItemLongClickListener((view, position) -> {
Object object = mentionsAdapter.getItem(position);
if (object instanceof String) {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity, resourcesProvider);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch));
builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> mentionsAdapter.clearRecentHashtags());
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
return true;
}
return false;
});
hintView = new UndoView(activityContext, null, false, resourcesProvider);
hintView.setAdditionalTranslationY(AndroidUtilities.dp(112));
hintView.setColors(0xf9222222, 0xffffffff);
containerView.addView(hintView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
AccessibilityManager am = (AccessibilityManager) activityContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
if (am.isEnabled()) {
playButtonAccessibilityOverlay = new View(activityContext);
playButtonAccessibilityOverlay.setContentDescription(LocaleController.getString("AccActionPlay", R.string.AccActionPlay));
playButtonAccessibilityOverlay.setFocusable(true);
containerView.addView(playButtonAccessibilityOverlay, LayoutHelper.createFrame(64, 64, Gravity.CENTER));
}
}
use of org.telegram.messenger.Emoji 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.messenger.Emoji in project Telegram-FOSS by Telegram-FOSS-Team.
the class EmojiView method updateGifTabs.
private void updateGifTabs() {
final int lastPosition = gifTabs.getCurrentPosition();
final boolean wasRecentTabSelected = lastPosition == gifRecentTabNum;
final boolean hadRecent = gifRecentTabNum >= 0;
final boolean hasRecent = !recentGifs.isEmpty();
gifTabs.beginUpdate(false);
int gifTabsCount = 0;
gifRecentTabNum = -2;
gifTrendingTabNum = -2;
gifFirstEmojiTabNum = -2;
if (hasRecent) {
gifRecentTabNum = gifTabsCount++;
gifTabs.addIconTab(0, gifIcons[0]).setContentDescription(LocaleController.getString("RecentStickers", R.string.RecentStickers));
}
gifTrendingTabNum = gifTabsCount++;
gifTabs.addIconTab(1, gifIcons[1]).setContentDescription(LocaleController.getString("FeaturedGifs", R.string.FeaturedGifs));
gifFirstEmojiTabNum = gifTabsCount;
final int hPadding = AndroidUtilities.dp(13);
final int vPadding = AndroidUtilities.dp(11);
final List<String> gifSearchEmojies = MessagesController.getInstance(currentAccount).gifSearchEmojies;
for (int i = 0, N = gifSearchEmojies.size(); i < N; i++) {
final String emoji = gifSearchEmojies.get(i);
final Emoji.EmojiDrawable emojiDrawable = Emoji.getEmojiDrawable(emoji);
if (emojiDrawable != null) {
gifTabsCount++;
TLRPC.Document document = MediaDataController.getInstance(currentAccount).getEmojiAnimatedSticker(emoji);
final View iconTab = gifTabs.addEmojiTab(3 + i, emojiDrawable, document);
// iconTab.setPadding(hPadding, vPadding, hPadding, vPadding);
iconTab.setContentDescription(emoji);
}
}
gifTabs.commitUpdate();
gifTabs.updateTabStyles();
if (wasRecentTabSelected && !hasRecent) {
gifTabs.selectTab(gifTrendingTabNum);
} else if (ViewCompat.isLaidOut(gifTabs)) {
if (hasRecent && !hadRecent) {
gifTabs.onPageScrolled(lastPosition + 1, 0);
} else if (!hasRecent && hadRecent) {
gifTabs.onPageScrolled(lastPosition - 1, 0);
}
}
}
use of org.telegram.messenger.Emoji in project Telegram-FOSS by Telegram-FOSS-Team.
the class MentionsAdapter method searchUsernameOrHashtag.
public void searchUsernameOrHashtag(String text, int position, ArrayList<MessageObject> messageObjects, boolean usernameOnly, boolean forSearch) {
if (cancelDelayRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(cancelDelayRunnable);
cancelDelayRunnable = null;
}
if (channelReqId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(channelReqId, true);
channelReqId = 0;
}
if (searchGlobalRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(searchGlobalRunnable);
searchGlobalRunnable = null;
}
if (TextUtils.isEmpty(text) || text.length() > MessagesController.getInstance(currentAccount).maxMessageLength) {
searchForContextBot(null, null);
delegate.needChangePanelVisibility(false);
lastText = null;
clearStickers();
return;
}
int searchPostion = position;
if (text.length() > 0) {
searchPostion--;
}
lastText = null;
lastUsernameOnly = usernameOnly;
lastForSearch = forSearch;
StringBuilder result = new StringBuilder();
int foundType = -1;
boolean searchEmoji = !usernameOnly && text != null && text.length() > 0 && text.length() <= 14;
String originalEmoji = "";
if (searchEmoji) {
CharSequence emoji = originalEmoji = text;
int length = emoji.length();
for (int a = 0; a < length; a++) {
char ch = emoji.charAt(a);
char nch = a < length - 1 ? emoji.charAt(a + 1) : 0;
if (a < length - 1 && ch == 0xD83C && nch >= 0xDFFB && nch <= 0xDFFF) {
emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 2, emoji.length()));
length -= 2;
a--;
} else if (ch == 0xfe0f) {
emoji = TextUtils.concat(emoji.subSequence(0, a), emoji.subSequence(a + 1, emoji.length()));
length--;
a--;
}
}
lastSticker = emoji.toString().trim();
}
boolean isValidEmoji = searchEmoji && (Emoji.isValidEmoji(originalEmoji) || Emoji.isValidEmoji(lastSticker));
if (isValidEmoji && parentFragment != null && (parentFragment.getCurrentChat() == null || ChatObject.canSendStickers(parentFragment.getCurrentChat()))) {
stickersToLoad.clear();
if (SharedConfig.suggestStickers == 2 || !isValidEmoji) {
if (visibleByStickersSearch && SharedConfig.suggestStickers == 2) {
visibleByStickersSearch = false;
delegate.needChangePanelVisibility(false);
notifyDataSetChanged();
}
return;
}
stickers = null;
stickersMap = null;
foundType = 4;
if (lastReqId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(lastReqId, true);
lastReqId = 0;
}
boolean serverStickersOnly = MessagesController.getInstance(currentAccount).suggestStickersApiOnly;
delayLocalResults = false;
if (!serverStickersOnly) {
final ArrayList<TLRPC.Document> recentStickers = MediaDataController.getInstance(currentAccount).getRecentStickersNoCopy(MediaDataController.TYPE_IMAGE);
final ArrayList<TLRPC.Document> favsStickers = MediaDataController.getInstance(currentAccount).getRecentStickersNoCopy(MediaDataController.TYPE_FAVE);
int recentsAdded = 0;
for (int a = 0, size = Math.min(20, recentStickers.size()); a < size; a++) {
TLRPC.Document document = recentStickers.get(a);
if (isValidSticker(document, lastSticker)) {
addStickerToResult(document, "recent");
recentsAdded++;
if (recentsAdded >= 5) {
break;
}
}
}
for (int a = 0, size = favsStickers.size(); a < size; a++) {
TLRPC.Document document = favsStickers.get(a);
if (isValidSticker(document, lastSticker)) {
addStickerToResult(document, "fav");
}
}
HashMap<String, ArrayList<TLRPC.Document>> allStickers = MediaDataController.getInstance(currentAccount).getAllStickers();
ArrayList<TLRPC.Document> newStickers = allStickers != null ? allStickers.get(lastSticker) : null;
if (newStickers != null && !newStickers.isEmpty()) {
addStickersToResult(newStickers, null);
}
if (stickers != null) {
Collections.sort(stickers, new Comparator<StickerResult>() {
private int getIndex(StickerResult result) {
for (int a = 0; a < favsStickers.size(); a++) {
if (favsStickers.get(a).id == result.sticker.id) {
return a + 2000000;
}
}
for (int a = 0; a < Math.min(20, recentStickers.size()); a++) {
if (recentStickers.get(a).id == result.sticker.id) {
return recentStickers.size() - a + 1000000;
}
}
return -1;
}
@Override
public int compare(StickerResult lhs, StickerResult rhs) {
boolean isAnimated1 = MessageObject.isAnimatedStickerDocument(lhs.sticker, true);
boolean isAnimated2 = MessageObject.isAnimatedStickerDocument(rhs.sticker, true);
if (isAnimated1 == isAnimated2) {
int idx1 = getIndex(lhs);
int idx2 = getIndex(rhs);
if (idx1 > idx2) {
return -1;
} else if (idx1 < idx2) {
return 1;
}
return 0;
} else {
if (isAnimated1) {
return -1;
} else {
return 1;
}
}
}
});
}
}
if (SharedConfig.suggestStickers == 0 || serverStickersOnly) {
searchServerStickers(lastSticker, originalEmoji);
}
if (stickers != null && !stickers.isEmpty()) {
if (SharedConfig.suggestStickers == 0 && stickers.size() < 5) {
delayLocalResults = true;
delegate.needChangePanelVisibility(false);
visibleByStickersSearch = false;
} else {
checkStickerFilesExistAndDownload();
boolean show = stickersToLoad.isEmpty();
delegate.needChangePanelVisibility(show);
visibleByStickersSearch = true;
}
notifyDataSetChanged();
} else if (visibleByStickersSearch) {
delegate.needChangePanelVisibility(false);
visibleByStickersSearch = false;
}
} else if (!usernameOnly && needBotContext && text.charAt(0) == '@') {
int index = text.indexOf(' ');
int len = text.length();
String username = null;
String query = null;
if (index > 0) {
username = text.substring(1, index);
query = text.substring(index + 1);
} else if (text.charAt(len - 1) == 't' && text.charAt(len - 2) == 'o' && text.charAt(len - 3) == 'b') {
username = text.substring(1);
query = "";
} else {
searchForContextBot(null, null);
}
if (username != null && username.length() >= 1) {
for (int a = 1; a < username.length(); a++) {
char ch = username.charAt(a);
if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
username = "";
break;
}
}
} else {
username = "";
}
searchForContextBot(username, query);
} else {
searchForContextBot(null, null);
}
if (foundContextBot != null) {
return;
}
final MessagesController messagesController = MessagesController.getInstance(currentAccount);
int dogPostion = -1;
if (usernameOnly) {
result.append(text.substring(1));
resultStartPosition = 0;
resultLength = result.length();
foundType = 0;
} else {
for (int a = searchPostion; a >= 0; a--) {
if (a >= text.length()) {
continue;
}
char ch = text.charAt(a);
if (a == 0 || text.charAt(a - 1) == ' ' || text.charAt(a - 1) == '\n' || ch == ':') {
if (ch == '@') {
if (needUsernames || needBotContext && a == 0) {
if (info == null && a != 0) {
lastText = text;
lastPosition = position;
messages = messageObjects;
delegate.needChangePanelVisibility(false);
return;
}
dogPostion = a;
foundType = 0;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
}
} else if (ch == '#') {
if (searchAdapterHelper.loadRecentHashtags()) {
foundType = 1;
resultStartPosition = a;
resultLength = result.length() + 1;
result.insert(0, ch);
break;
} else {
lastText = text;
lastPosition = position;
messages = messageObjects;
delegate.needChangePanelVisibility(false);
return;
}
} else if (a == 0 && botInfo != null && ch == '/') {
foundType = 2;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
} else if (ch == ':' && result.length() > 0) {
boolean isNextPunctiationChar = punctuationsChars.indexOf(result.charAt(0)) >= 0;
if (!isNextPunctiationChar || result.length() > 1) {
foundType = 3;
resultStartPosition = a;
resultLength = result.length() + 1;
break;
}
}
}
result.insert(0, ch);
}
}
if (foundType == -1) {
delegate.needChangePanelVisibility(false);
return;
}
if (foundType == 0) {
final ArrayList<Long> users = new ArrayList<>();
for (int a = 0; a < Math.min(100, messageObjects.size()); a++) {
long from_id = messageObjects.get(a).getFromChatId();
if (from_id > 0 && !users.contains(from_id)) {
users.add(from_id);
}
}
final String usernameString = result.toString().toLowerCase();
boolean hasSpace = usernameString.indexOf(' ') >= 0;
ArrayList<TLObject> newResult = new ArrayList<>();
final LongSparseArray<TLRPC.User> newResultsHashMap = new LongSparseArray<>();
final LongSparseArray<TLObject> newMap = new LongSparseArray<>();
ArrayList<TLRPC.TL_topPeer> inlineBots = MediaDataController.getInstance(currentAccount).inlineBots;
if (!usernameOnly && needBotContext && dogPostion == 0 && !inlineBots.isEmpty()) {
int count = 0;
for (int a = 0; a < inlineBots.size(); a++) {
TLRPC.User user = messagesController.getUser(inlineBots.get(a).peer.user_id);
if (user == null) {
continue;
}
if (!TextUtils.isEmpty(user.username) && (usernameString.length() == 0 || user.username.toLowerCase().startsWith(usernameString))) {
newResult.add(user);
newResultsHashMap.put(user.id, user);
newMap.put(user.id, user);
count++;
}
if (count == 5) {
break;
}
}
}
final TLRPC.Chat chat;
int threadId;
if (parentFragment != null) {
chat = parentFragment.getCurrentChat();
threadId = parentFragment.getThreadId();
} else if (info != null) {
chat = messagesController.getChat(info.id);
threadId = 0;
} else {
chat = null;
threadId = 0;
}
if (chat != null && info != null && info.participants != null && (!ChatObject.isChannel(chat) || chat.megagroup)) {
for (int a = (forSearch ? -1 : 0); a < info.participants.participants.size(); a++) {
String username;
String firstName;
String lastName;
TLObject object;
long id;
if (a == -1) {
if (usernameString.length() == 0) {
newResult.add(chat);
continue;
}
firstName = chat.title;
lastName = null;
username = chat.username;
object = chat;
id = -chat.id;
} else {
TLRPC.ChatParticipant chatParticipant = info.participants.participants.get(a);
TLRPC.User user = messagesController.getUser(chatParticipant.user_id);
if (user == null || !usernameOnly && UserObject.isUserSelf(user) || newResultsHashMap.indexOfKey(user.id) >= 0) {
continue;
}
if (usernameString.length() == 0) {
if (!user.deleted) {
newResult.add(user);
continue;
}
}
firstName = user.first_name;
lastName = user.last_name;
username = user.username;
object = user;
id = user.id;
}
if (!TextUtils.isEmpty(username) && username.toLowerCase().startsWith(usernameString) || !TextUtils.isEmpty(firstName) && firstName.toLowerCase().startsWith(usernameString) || !TextUtils.isEmpty(lastName) && lastName.toLowerCase().startsWith(usernameString) || hasSpace && ContactsController.formatName(firstName, lastName).toLowerCase().startsWith(usernameString)) {
newResult.add(object);
newMap.put(id, object);
}
}
}
Collections.sort(newResult, new Comparator<TLObject>() {
private long getId(TLObject object) {
if (object instanceof TLRPC.User) {
return ((TLRPC.User) object).id;
} else {
return -((TLRPC.Chat) object).id;
}
}
@Override
public int compare(TLObject lhs, TLObject rhs) {
long id1 = getId(lhs);
long id2 = getId(rhs);
if (newMap.indexOfKey(id1) >= 0 && newMap.indexOfKey(id2) >= 0) {
return 0;
} else if (newMap.indexOfKey(id1) >= 0) {
return -1;
} else if (newMap.indexOfKey(id2) >= 0) {
return 1;
}
int lhsNum = users.indexOf(id1);
int rhsNum = users.indexOf(id2);
if (lhsNum != -1 && rhsNum != -1) {
return lhsNum < rhsNum ? -1 : (lhsNum == rhsNum ? 0 : 1);
} else if (lhsNum != -1 && rhsNum == -1) {
return -1;
} else if (lhsNum == -1 && rhsNum != -1) {
return 1;
}
return 0;
}
});
searchResultHashtags = null;
stickers = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
searchResultSuggestions = null;
if (chat != null && chat.megagroup && usernameString.length() > 0) {
if (newResult.size() < 5) {
AndroidUtilities.runOnUIThread(cancelDelayRunnable = () -> {
cancelDelayRunnable = null;
showUsersResult(newResult, newMap, true);
}, 1000);
} else {
showUsersResult(newResult, newMap, true);
}
AndroidUtilities.runOnUIThread(searchGlobalRunnable = new Runnable() {
@Override
public void run() {
if (searchGlobalRunnable != this) {
return;
}
TLRPC.TL_channels_getParticipants req = new TLRPC.TL_channels_getParticipants();
req.channel = MessagesController.getInputChannel(chat);
req.limit = 20;
req.offset = 0;
TLRPC.TL_channelParticipantsMentions channelParticipantsMentions = new TLRPC.TL_channelParticipantsMentions();
channelParticipantsMentions.flags |= 1;
channelParticipantsMentions.q = usernameString;
if (threadId != 0) {
channelParticipantsMentions.flags |= 2;
channelParticipantsMentions.top_msg_id = threadId;
}
req.filter = channelParticipantsMentions;
final int currentReqId = ++channelLastReqId;
channelReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (channelReqId != 0 && currentReqId == channelLastReqId && searchResultUsernamesMap != null && searchResultUsernames != null) {
showUsersResult(newResult, newMap, false);
if (error == null) {
TLRPC.TL_channels_channelParticipants res = (TLRPC.TL_channels_channelParticipants) response;
messagesController.putUsers(res.users, false);
messagesController.putChats(res.chats, false);
boolean hasResults = !searchResultUsernames.isEmpty();
if (!res.participants.isEmpty()) {
long currentUserId = UserConfig.getInstance(currentAccount).getClientUserId();
for (int a = 0; a < res.participants.size(); a++) {
TLRPC.ChannelParticipant participant = res.participants.get(a);
long peerId = MessageObject.getPeerId(participant.peer);
if (searchResultUsernamesMap.indexOfKey(peerId) >= 0 || !isSearchingMentions && peerId == currentUserId) {
continue;
}
if (peerId >= 0) {
TLRPC.User user = messagesController.getUser(peerId);
if (user == null) {
return;
}
searchResultUsernames.add(user);
} else {
TLRPC.Chat chat = messagesController.getChat(-peerId);
if (chat == null) {
return;
}
searchResultUsernames.add(chat);
}
}
}
}
notifyDataSetChanged();
delegate.needChangePanelVisibility(!searchResultUsernames.isEmpty());
}
channelReqId = 0;
}));
}
}, 200);
} else {
showUsersResult(newResult, newMap, true);
}
} else if (foundType == 1) {
ArrayList<String> newResult = new ArrayList<>();
String hashtagString = result.toString().toLowerCase();
ArrayList<SearchAdapterHelper.HashtagObject> hashtags = searchAdapterHelper.getHashtags();
for (int a = 0; a < hashtags.size(); a++) {
SearchAdapterHelper.HashtagObject hashtagObject = hashtags.get(a);
if (hashtagObject != null && hashtagObject.hashtag != null && hashtagObject.hashtag.startsWith(hashtagString)) {
newResult.add(hashtagObject.hashtag);
}
}
searchResultHashtags = newResult;
stickers = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
searchResultSuggestions = null;
notifyDataSetChanged();
delegate.needChangePanelVisibility(!newResult.isEmpty());
} else if (foundType == 2) {
ArrayList<String> newResult = new ArrayList<>();
ArrayList<String> newResultHelp = new ArrayList<>();
ArrayList<TLRPC.User> newResultUsers = new ArrayList<>();
String command = result.toString().toLowerCase();
for (int b = 0; b < botInfo.size(); b++) {
TLRPC.BotInfo info = botInfo.valueAt(b);
for (int a = 0; a < info.commands.size(); a++) {
TLRPC.TL_botCommand botCommand = info.commands.get(a);
if (botCommand != null && botCommand.command != null && botCommand.command.startsWith(command)) {
newResult.add("/" + botCommand.command);
newResultHelp.add(botCommand.description);
newResultUsers.add(messagesController.getUser(info.user_id));
}
}
}
searchResultHashtags = null;
stickers = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultSuggestions = null;
searchResultCommands = newResult;
searchResultCommandsHelp = newResultHelp;
searchResultCommandsUsers = newResultUsers;
notifyDataSetChanged();
delegate.needChangePanelVisibility(!newResult.isEmpty());
} else if (foundType == 3) {
String[] newLanguage = AndroidUtilities.getCurrentKeyboardLanguage();
if (!Arrays.equals(newLanguage, lastSearchKeyboardLanguage)) {
MediaDataController.getInstance(currentAccount).fetchNewEmojiKeywords(newLanguage);
}
lastSearchKeyboardLanguage = newLanguage;
MediaDataController.getInstance(currentAccount).getEmojiSuggestions(lastSearchKeyboardLanguage, result.toString(), false, (param, alias) -> {
searchResultSuggestions = param;
searchResultHashtags = null;
stickers = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
notifyDataSetChanged();
delegate.needChangePanelVisibility(searchResultSuggestions != null && !searchResultSuggestions.isEmpty());
});
} else if (foundType == 4) {
searchResultHashtags = null;
searchResultUsernames = null;
searchResultUsernamesMap = null;
searchResultSuggestions = null;
searchResultCommands = null;
searchResultCommandsHelp = null;
searchResultCommandsUsers = null;
}
}
use of org.telegram.messenger.Emoji in project Telegram-FOSS by Telegram-FOSS-Team.
the class ChatMessageCell method setMessageContent.
private void setMessageContent(MessageObject messageObject, MessageObject.GroupedMessages groupedMessages, boolean bottomNear, boolean topNear) {
if (messageObject.checkLayout() || currentPosition != null && lastHeight != AndroidUtilities.displaySize.y) {
currentMessageObject = null;
}
boolean widthChanged = lastWidth != getParentWidth();
lastHeight = AndroidUtilities.displaySize.y;
lastWidth = getParentWidth();
isRoundVideo = messageObject != null && messageObject.isRoundVideo();
TLRPC.Message newReply = messageObject.hasValidReplyMessageObject() ? messageObject.replyMessageObject.messageOwner : null;
boolean messageIdChanged = currentMessageObject == null || currentMessageObject.getId() != messageObject.getId();
boolean messageChanged = currentMessageObject != messageObject || messageObject.forceUpdate || (isRoundVideo && isPlayingRound != (MediaController.getInstance().isPlayingMessage(currentMessageObject) && delegate != null && !delegate.keyboardIsOpened()));
boolean dataChanged = currentMessageObject != null && currentMessageObject.getId() == messageObject.getId() && lastSendState == MessageObject.MESSAGE_SEND_STATE_EDITING && messageObject.isSent() || currentMessageObject == messageObject && (isUserDataChanged() || photoNotSet) || lastPostAuthor != messageObject.messageOwner.post_author || wasPinned != isPinned || newReply != lastReplyMessage;
boolean groupChanged = groupedMessages != currentMessagesGroup;
boolean pollChanged = false;
if (dataChanged || messageChanged || messageIdChanged) {
accessibilityText = null;
}
if (drawCommentButton || drawSideButton == 3 && !((hasDiscussion && messageObject.isLinkedToChat(linkedChatId) || isRepliesChat) && (currentPosition == null || currentPosition.siblingHeights == null && (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0 || currentPosition.siblingHeights != null && (currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0))) {
dataChanged = true;
}
if (!messageChanged && messageObject.isDice()) {
setCurrentDiceValue(isUpdating);
}
if (!messageChanged && messageObject.isPoll()) {
ArrayList<TLRPC.TL_pollAnswerVoters> newResults = null;
TLRPC.Poll newPoll = null;
int newVoters = 0;
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPoll) {
TLRPC.TL_messageMediaPoll mediaPoll = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media;
newResults = mediaPoll.results.results;
newPoll = mediaPoll.poll;
newVoters = mediaPoll.results.total_voters;
}
if (newResults != null && lastPollResults != null && newVoters != lastPollResultsVoters) {
pollChanged = true;
}
if (!pollChanged && newResults != lastPollResults) {
pollChanged = true;
}
if (lastPoll != newPoll && lastPoll.closed != newPoll.closed) {
pollChanged = true;
if (!pollVoted) {
pollVoteInProgress = true;
vibrateOnPollVote = false;
}
}
animatePollAvatars = false;
if (pollChanged && attachedToWindow) {
pollAnimationProgressTime = 0.0f;
if (pollVoted && !messageObject.isVoted()) {
pollUnvoteInProgress = true;
}
animatePollAvatars = lastPollResultsVoters == 0 || lastPollResultsVoters != 0 && newVoters == 0;
}
}
if (!groupChanged && groupedMessages != null) {
MessageObject.GroupedMessagePosition newPosition;
if (groupedMessages.messages.size() > 1) {
newPosition = currentMessagesGroup.positions.get(currentMessageObject);
} else {
newPosition = null;
}
groupChanged = newPosition != currentPosition;
}
if (messageChanged || dataChanged || groupChanged || pollChanged || widthChanged && messageObject.isPoll() || isPhotoDataChanged(messageObject) || pinnedBottom != bottomNear || pinnedTop != topNear) {
wasPinned = isPinned;
pinnedBottom = bottomNear;
pinnedTop = topNear;
currentMessageObject = messageObject;
currentMessagesGroup = groupedMessages;
lastTime = -2;
lastPostAuthor = messageObject.messageOwner.post_author;
isHighlightedAnimated = false;
widthBeforeNewTimeLine = -1;
if (currentMessagesGroup != null && (currentMessagesGroup.posArray.size() > 1)) {
currentPosition = currentMessagesGroup.positions.get(currentMessageObject);
if (currentPosition == null) {
currentMessagesGroup = null;
}
} else {
currentMessagesGroup = null;
currentPosition = null;
}
if (currentMessagesGroup == null || currentMessagesGroup.isDocuments) {
drawPinnedTop = pinnedTop;
drawPinnedBottom = pinnedBottom;
} else {
drawPinnedTop = pinnedTop && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_TOP) != 0);
drawPinnedBottom = pinnedBottom && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0);
}
isPlayingRound = isRoundVideo && MediaController.getInstance().isPlayingMessage(currentMessageObject) && delegate != null && !delegate.keyboardIsOpened() && !delegate.isLandscape();
photoImage.setCrossfadeWithOldImage(false);
photoImage.setCrossfadeDuration(ImageReceiver.DEFAULT_CROSSFADE_DURATION);
photoImage.setGradientBitmap(null);
lastSendState = messageObject.messageOwner.send_state;
lastDeleteDate = messageObject.messageOwner.destroyTime;
lastViewsCount = messageObject.messageOwner.views;
lastRepliesCount = getRepliesCount();
isPressed = false;
gamePreviewPressed = false;
sideButtonPressed = false;
isCheckPressed = true;
hasNewLineForTime = false;
isThreadPost = isThreadChat && messageObject.messageOwner.fwd_from != null && messageObject.messageOwner.fwd_from.channel_post != 0;
isAvatarVisible = !isThreadPost && isChat && !messageObject.isOutOwner() && messageObject.needDrawAvatar() && (currentPosition == null || currentPosition.edge);
boolean drawAvatar = isChat && !isThreadPost && !messageObject.isOutOwner() && messageObject.needDrawAvatar();
if (messageObject.customAvatarDrawable != null) {
isAvatarVisible = true;
drawAvatar = true;
}
wasLayout = false;
groupPhotoInvisible = false;
animatingDrawVideoImageButton = 0;
drawVideoSize = false;
canStreamVideo = false;
animatingNoSound = 0;
if (MessagesController.getInstance(currentAccount).isChatNoForwards(messageObject.getChatId()) || (messageObject.messageOwner != null && messageObject.messageOwner.noforwards)) {
drawSideButton = 0;
} else {
drawSideButton = !isRepliesChat && checkNeedDrawShareButton(messageObject) && (currentPosition == null || currentPosition.last) ? 1 : 0;
if (isPinnedChat || drawSideButton == 1 && messageObject.messageOwner.fwd_from != null && !messageObject.isOutOwner() && messageObject.messageOwner.fwd_from.saved_from_peer != null && messageObject.getDialogId() == UserConfig.getInstance(currentAccount).getClientUserId()) {
drawSideButton = 2;
}
}
replyNameLayout = null;
adminLayout = null;
checkOnlyButtonPressed = false;
replyTextLayout = null;
lastReplyMessage = null;
hasEmbed = false;
autoPlayingMedia = false;
replyNameWidth = 0;
replyTextWidth = 0;
viaWidth = 0;
viaNameWidth = 0;
addedCaptionHeight = 0;
currentReplyPhoto = null;
currentUser = null;
currentChat = null;
currentViaBotUser = null;
instantViewLayout = null;
drawNameLayout = false;
lastLoadingSizeTotal = 0;
if (scheduledInvalidate) {
AndroidUtilities.cancelRunOnUIThread(invalidateRunnable);
scheduledInvalidate = false;
}
resetPressedLink(-1);
messageObject.forceUpdate = false;
drawPhotoImage = false;
drawMediaCheckBox = false;
hasLinkPreview = false;
hasOldCaptionPreview = false;
hasGamePreview = false;
hasInvoicePreview = false;
instantPressed = instantButtonPressed = commentButtonPressed = false;
if (!pollChanged && Build.VERSION.SDK_INT >= 21) {
for (int a = 0; a < selectorDrawable.length; a++) {
if (selectorDrawable[a] != null) {
selectorDrawable[a].setVisible(false, false);
selectorDrawable[a].setState(StateSet.NOTHING);
}
}
}
spoilerPressed = null;
isCaptionSpoilerPressed = false;
isSpoilerRevealing = false;
linkPreviewPressed = false;
buttonPressed = 0;
additionalTimeOffsetY = 0;
miniButtonPressed = 0;
pressedBotButton = -1;
pressedVoteButton = -1;
pollHintPressed = false;
psaHintPressed = false;
linkPreviewHeight = 0;
mediaOffsetY = 0;
documentAttachType = DOCUMENT_ATTACH_TYPE_NONE;
documentAttach = null;
descriptionLayout = null;
titleLayout = null;
videoInfoLayout = null;
photosCountLayout = null;
siteNameLayout = null;
authorLayout = null;
captionLayout = null;
captionWidth = 0;
captionHeight = 0;
captionOffsetX = 0;
currentCaption = null;
docTitleLayout = null;
drawImageButton = false;
drawVideoImageButton = false;
currentPhotoObject = null;
photoParentObject = null;
currentPhotoObjectThumb = null;
currentPhotoObjectThumbStripped = null;
if (messageChanged || messageIdChanged || dataChanged) {
currentPhotoFilter = null;
}
buttonState = -1;
miniButtonState = -1;
hasMiniProgress = 0;
if (addedForTest && currentUrl != null && currentWebFile != null) {
ImageLoader.getInstance().removeTestWebFile(currentUrl);
}
addedForTest = false;
photoNotSet = false;
drawBackground = true;
drawName = false;
useSeekBarWaweform = false;
drawInstantView = false;
drawInstantViewType = 0;
drawForwardedName = false;
drawCommentButton = false;
photoImage.setSideClip(0);
photoImage.setAspectFit(false);
gradientShader = null;
motionBackgroundDrawable = null;
imageBackgroundColor = 0;
imageBackgroundGradientColor1 = 0;
imageBackgroundGradientColor2 = 0;
imageBackgroundIntensity = 0;
imageBackgroundGradientColor3 = 0;
imageBackgroundGradientRotation = 45;
imageBackgroundSideColor = 0;
mediaBackground = false;
isMedia = false;
hasPsaHint = messageObject.messageOwner.fwd_from != null && !TextUtils.isEmpty(messageObject.messageOwner.fwd_from.psa_type);
if (hasPsaHint) {
createSelectorDrawable(0);
}
photoImage.setAlpha(1.0f);
if ((messageChanged || dataChanged) && !pollUnvoteInProgress) {
pollButtons.clear();
}
int captionNewLine = 0;
availableTimeWidth = 0;
photoImage.setForceLoading(false);
photoImage.setNeedsQualityThumb(false);
photoImage.setShouldGenerateQualityThumb(false);
photoImage.setAllowDecodeSingleFrame(false);
photoImage.setColorFilter(null);
photoImage.setMediaStartEndTime(-1, -1);
boolean canChangeRadius = true;
if (messageIdChanged || messageObject.reactionsChanged) {
messageObject.reactionsChanged = false;
if (currentPosition == null || ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0)) {
if (currentPosition != null) {
reactionsLayoutInBubble.setMessage(groupedMessages.findPrimaryMessageObject(), !messageObject.shouldDrawReactionsInLayout(), resourcesProvider);
} else {
reactionsLayoutInBubble.setMessage(messageObject, !messageObject.shouldDrawReactionsInLayout(), resourcesProvider);
}
} else {
reactionsLayoutInBubble.setMessage(null, false, resourcesProvider);
}
}
if (messageChanged) {
firstVisibleBlockNum = 0;
lastVisibleBlockNum = 0;
if (currentMessageObject != null && currentMessageObject.textLayoutBlocks != null && currentMessageObject.textLayoutBlocks.size() > 1) {
needNewVisiblePart = true;
}
}
boolean linked = false;
if (currentMessagesGroup != null && currentMessagesGroup.messages.size() > 0) {
MessageObject object = currentMessagesGroup.messages.get(0);
if (object.isLinkedToChat(linkedChatId)) {
linked = true;
}
} else {
linked = messageObject.isLinkedToChat(linkedChatId);
}
if ((hasDiscussion && linked || isRepliesChat && !messageObject.isOutOwner()) && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0)) {
int commentCount = getRepliesCount();
if (!messageObject.shouldDrawWithoutBackground() && !messageObject.isAnimatedEmoji()) {
drawCommentButton = true;
int avatarsOffset = 0;
String comment;
if (commentProgress == null) {
commentProgress = new InfiniteProgress(AndroidUtilities.dp(7));
}
if (isRepliesChat) {
comment = LocaleController.getString("ViewInChat", R.string.ViewInChat);
} else {
if (LocaleController.isRTL) {
comment = commentCount == 0 ? LocaleController.getString("LeaveAComment", R.string.LeaveAComment) : LocaleController.formatPluralString("CommentsCount", commentCount);
} else {
comment = commentCount == 0 ? LocaleController.getString("LeaveAComment", R.string.LeaveAComment) : LocaleController.getPluralString("CommentsNoNumber", commentCount);
}
ArrayList<TLRPC.Peer> recentRepliers = getRecentRepliers();
if (commentCount != 0 && recentRepliers != null && !recentRepliers.isEmpty()) {
createCommentUI();
int size = recentRepliers.size();
for (int a = 0; a < commentAvatarImages.length; a++) {
if (a < size) {
commentAvatarImages[a].setImageCoords(0, 0, AndroidUtilities.dp(24), AndroidUtilities.dp(24));
long id = MessageObject.getPeerId(recentRepliers.get(a));
TLRPC.User user = null;
TLRPC.Chat chat = null;
if (DialogObject.isUserDialog(id)) {
user = MessagesController.getInstance(currentAccount).getUser(id);
} else if (DialogObject.isChatDialog(id)) {
chat = MessagesController.getInstance(currentAccount).getChat(-id);
}
if (user != null) {
commentAvatarDrawables[a].setInfo(user);
commentAvatarImages[a].setForUserOrChat(user, commentAvatarDrawables[a]);
} else if (chat != null) {
commentAvatarDrawables[a].setInfo(chat);
commentAvatarImages[a].setForUserOrChat(chat, commentAvatarDrawables[a]);
} else {
commentAvatarDrawables[a].setInfo(id, "", "");
}
commentAvatarImagesVisible[a] = true;
avatarsOffset += a == 0 ? 2 : 17;
} else if (size != 0) {
commentAvatarImages[a].setImageBitmap((Drawable) null);
commentAvatarImagesVisible[a] = false;
}
}
} else if (commentAvatarImages != null) {
for (int a = 0; a < commentAvatarImages.length; a++) {
commentAvatarImages[a].setImageBitmap((Drawable) null);
commentAvatarImagesVisible[a] = false;
}
}
}
commentWidth = totalCommentWidth = (int) Math.ceil(Theme.chat_replyNamePaint.measureText(comment));
commentLayout = new StaticLayout(comment, Theme.chat_replyNamePaint, commentWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (commentCount != 0 && !LocaleController.isRTL) {
drawCommentNumber = true;
if (commentNumberLayout == null) {
commentNumberLayout = new AnimatedNumberLayout(this, Theme.chat_replyNamePaint);
commentNumberLayout.setNumber(commentCount, false);
} else {
commentNumberLayout.setNumber(commentCount, messageObject.animateComments);
}
messageObject.animateComments = false;
commentNumberWidth = commentNumberLayout.getWidth();
totalCommentWidth += commentNumberWidth + AndroidUtilities.dp(4);
} else {
drawCommentNumber = false;
if (commentNumberLayout != null) {
commentNumberLayout.setNumber(1, false);
}
}
totalCommentWidth += AndroidUtilities.dp(70 + avatarsOffset);
} else {
if (!isRepliesChat && commentCount > 0) {
String comment = LocaleController.formatShortNumber(commentCount, null);
commentWidth = totalCommentWidth = (int) Math.ceil(Theme.chat_stickerCommentCountPaint.measureText(comment));
commentLayout = new StaticLayout(comment, Theme.chat_stickerCommentCountPaint, commentWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else {
commentLayout = null;
}
drawCommentNumber = false;
drawSideButton = isRepliesChat ? 2 : 3;
}
} else {
commentLayout = null;
drawCommentNumber = false;
}
if (messageObject.type == 0) {
drawForwardedName = !isRepliesChat;
int maxWidth;
if (drawAvatar) {
if (AndroidUtilities.isTablet()) {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122);
} else {
maxWidth = Math.min(getParentWidth(), AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122);
}
drawName = true;
} else {
if (AndroidUtilities.isTablet()) {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80);
} else {
maxWidth = Math.min(getParentWidth(), AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
}
drawName = isPinnedChat || messageObject.messageOwner.peer_id.channel_id != 0 && (!messageObject.isOutOwner() || messageObject.isSupergroup()) || messageObject.isImportedForward() && messageObject.messageOwner.fwd_from.from_id == null;
}
availableTimeWidth = maxWidth;
if (messageObject.isRoundVideo()) {
availableTimeWidth -= Math.ceil(Theme.chat_audioTimePaint.measureText("00:00")) + (messageObject.isOutOwner() ? 0 : AndroidUtilities.dp(64));
}
measureTime(messageObject);
int timeMore = timeWidth + AndroidUtilities.dp(6);
if (messageObject.isOutOwner()) {
timeMore += AndroidUtilities.dp(20.5f);
}
timeMore += getExtraTimeX();
hasGamePreview = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame && messageObject.messageOwner.media.game instanceof TLRPC.TL_game;
hasInvoicePreview = messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaInvoice;
hasLinkPreview = !messageObject.isRestrictedMessage && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage;
drawInstantView = hasLinkPreview && messageObject.messageOwner.media.webpage.cached_page != null;
String siteName = hasLinkPreview ? messageObject.messageOwner.media.webpage.site_name : null;
hasEmbed = hasLinkPreview && !TextUtils.isEmpty(messageObject.messageOwner.media.webpage.embed_url) && !messageObject.isGif() && !"instangram".equalsIgnoreCase(siteName);
boolean slideshow = false;
String webpageType = hasLinkPreview ? messageObject.messageOwner.media.webpage.type : null;
TLRPC.Document androidThemeDocument = null;
TLRPC.ThemeSettings androidThemeSettings = null;
if (!drawInstantView) {
if ("telegram_livestream".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 11;
} else if ("telegram_voicechat".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 9;
} else if ("telegram_channel".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 1;
} else if ("telegram_user".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 13;
} else if ("telegram_megagroup".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 2;
} else if ("telegram_message".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 3;
} else if ("telegram_theme".equals(webpageType)) {
for (int b = 0, N2 = messageObject.messageOwner.media.webpage.attributes.size(); b < N2; b++) {
TLRPC.TL_webPageAttributeTheme attribute = messageObject.messageOwner.media.webpage.attributes.get(b);
ArrayList<TLRPC.Document> documents = attribute.documents;
for (int a = 0, N = documents.size(); a < N; a++) {
TLRPC.Document document = documents.get(a);
if ("application/x-tgtheme-android".equals(document.mime_type)) {
drawInstantView = true;
drawInstantViewType = 7;
androidThemeDocument = document;
break;
}
}
if (drawInstantView) {
break;
}
if (attribute.settings != null) {
drawInstantView = true;
drawInstantViewType = 7;
androidThemeSettings = attribute.settings;
break;
}
}
} else if ("telegram_background".equals(webpageType)) {
drawInstantView = true;
drawInstantViewType = 6;
try {
Uri url = Uri.parse(messageObject.messageOwner.media.webpage.url);
imageBackgroundIntensity = Utilities.parseInt(url.getQueryParameter("intensity"));
String bgColor = url.getQueryParameter("bg_color");
String rotation = url.getQueryParameter("rotation");
if (rotation != null) {
imageBackgroundGradientRotation = Utilities.parseInt(rotation);
}
if (TextUtils.isEmpty(bgColor)) {
TLRPC.Document document = messageObject.getDocument();
if (document != null && "image/png".equals(document.mime_type)) {
bgColor = "ffffff";
}
if (imageBackgroundIntensity == 0) {
imageBackgroundIntensity = 50;
}
}
if (bgColor != null) {
imageBackgroundColor = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
int averageColor = imageBackgroundColor;
if (bgColor.length() >= 13 && AndroidUtilities.isValidWallChar(bgColor.charAt(6))) {
imageBackgroundGradientColor1 = Integer.parseInt(bgColor.substring(7, 13), 16) | 0xff000000;
averageColor = AndroidUtilities.getAverageColor(imageBackgroundColor, imageBackgroundGradientColor1);
}
if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
imageBackgroundGradientColor2 = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
}
if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
imageBackgroundGradientColor3 = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
}
if (imageBackgroundIntensity < 0) {
imageBackgroundSideColor = 0xff111111;
} else {
imageBackgroundSideColor = AndroidUtilities.getPatternSideColor(averageColor);
}
photoImage.setColorFilter(new PorterDuffColorFilter(AndroidUtilities.getPatternColor(averageColor), PorterDuff.Mode.SRC_IN));
photoImage.setAlpha(Math.abs(imageBackgroundIntensity) / 100.0f);
} else {
String color = url.getLastPathSegment();
if (color != null && color.length() >= 6) {
imageBackgroundColor = Integer.parseInt(color.substring(0, 6), 16) | 0xff000000;
if (color.length() >= 13 && AndroidUtilities.isValidWallChar(color.charAt(6))) {
imageBackgroundGradientColor1 = Integer.parseInt(color.substring(7, 13), 16) | 0xff000000;
}
if (color.length() >= 20 && AndroidUtilities.isValidWallChar(color.charAt(13))) {
imageBackgroundGradientColor2 = Integer.parseInt(color.substring(14, 20), 16) | 0xff000000;
}
if (color.length() == 27 && AndroidUtilities.isValidWallChar(color.charAt(20))) {
imageBackgroundGradientColor3 = Integer.parseInt(color.substring(21), 16) | 0xff000000;
}
currentPhotoObject = new TLRPC.TL_photoSizeEmpty();
currentPhotoObject.type = "s";
currentPhotoObject.w = AndroidUtilities.dp(180);
currentPhotoObject.h = AndroidUtilities.dp(150);
currentPhotoObject.location = new TLRPC.TL_fileLocationUnavailable();
}
}
} catch (Exception ignore) {
}
}
} else if (siteName != null) {
siteName = siteName.toLowerCase();
if ((siteName.equals("instagram") || siteName.equals("twitter") || "telegram_album".equals(webpageType)) && messageObject.messageOwner.media.webpage.cached_page instanceof TLRPC.TL_page && (messageObject.messageOwner.media.webpage.photo instanceof TLRPC.TL_photo || MessageObject.isVideoDocument(messageObject.messageOwner.media.webpage.document))) {
drawInstantView = false;
slideshow = true;
ArrayList<TLRPC.PageBlock> blocks = messageObject.messageOwner.media.webpage.cached_page.blocks;
int count = 1;
for (int a = 0; a < blocks.size(); a++) {
TLRPC.PageBlock block = blocks.get(a);
if (block instanceof TLRPC.TL_pageBlockSlideshow) {
TLRPC.TL_pageBlockSlideshow b = (TLRPC.TL_pageBlockSlideshow) block;
count = b.items.size();
} else if (block instanceof TLRPC.TL_pageBlockCollage) {
TLRPC.TL_pageBlockCollage b = (TLRPC.TL_pageBlockCollage) block;
count = b.items.size();
}
}
String str = LocaleController.formatString("Of", R.string.Of, 1, count);
photosCountWidth = (int) Math.ceil(Theme.chat_durationPaint.measureText(str));
photosCountLayout = new StaticLayout(str, Theme.chat_durationPaint, photosCountWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
}
backgroundWidth = maxWidth;
if (hasLinkPreview || hasGamePreview || hasInvoicePreview || maxWidth - messageObject.lastLineWidth < timeMore) {
backgroundWidth = Math.max(backgroundWidth, messageObject.lastLineWidth) + AndroidUtilities.dp(31);
backgroundWidth = Math.max(backgroundWidth, timeWidth + AndroidUtilities.dp(31));
} else {
int diff = backgroundWidth - messageObject.lastLineWidth;
if (diff >= 0 && diff <= timeMore) {
backgroundWidth = backgroundWidth + timeMore - diff + AndroidUtilities.dp(31);
} else {
backgroundWidth = Math.max(backgroundWidth, messageObject.lastLineWidth + timeMore) + AndroidUtilities.dp(31);
}
}
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(31);
if (messageObject.isRoundVideo()) {
availableTimeWidth -= Math.ceil(Theme.chat_audioTimePaint.measureText("00:00")) + (messageObject.isOutOwner() ? 0 : AndroidUtilities.dp(64));
}
setMessageObjectInternal(messageObject);
backgroundWidth = messageObject.textWidth + getExtraTextX() * 2 + (hasGamePreview || hasInvoicePreview ? AndroidUtilities.dp(10) : 0);
totalHeight = messageObject.textHeight + AndroidUtilities.dp(19.5f) + namesOffset;
if (!reactionsLayoutInBubble.isSmall) {
reactionsLayoutInBubble.measure(maxWidth);
if (!reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(8);
if (reactionsLayoutInBubble.width > backgroundWidth) {
backgroundWidth = reactionsLayoutInBubble.width;
}
totalHeight += reactionsLayoutInBubble.totalHeight;
}
}
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
int maxChildWidth = Math.max(backgroundWidth, nameWidth);
maxChildWidth = Math.max(maxChildWidth, forwardedNameWidth);
maxChildWidth = Math.max(maxChildWidth, replyNameWidth);
maxChildWidth = Math.max(maxChildWidth, replyTextWidth);
if (commentLayout != null && drawSideButton != 3) {
maxChildWidth = Math.max(maxChildWidth, totalCommentWidth);
}
int maxWebWidth = 0;
if (hasLinkPreview || hasGamePreview || hasInvoicePreview) {
int linkPreviewMaxWidth;
if (AndroidUtilities.isTablet()) {
if (drawAvatar) {
linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(132);
} else {
linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80);
}
} else {
if (drawAvatar) {
linkPreviewMaxWidth = getParentWidth() - AndroidUtilities.dp(132);
} else {
linkPreviewMaxWidth = getParentWidth() - AndroidUtilities.dp(80);
}
}
if (drawSideButton != 0) {
linkPreviewMaxWidth -= AndroidUtilities.dp(20);
}
String site_name;
String title;
String author;
String description;
TLRPC.Photo photo;
TLRPC.Document document;
WebFile webDocument;
int duration;
boolean smallImage;
String type;
final int smallImageSide = AndroidUtilities.dp(48), smallSideMargin = AndroidUtilities.dp(10);
if (hasLinkPreview) {
TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) messageObject.messageOwner.media.webpage;
site_name = webPage.site_name;
title = drawInstantViewType != 6 && drawInstantViewType != 7 ? webPage.title : null;
author = drawInstantViewType != 6 && drawInstantViewType != 7 ? webPage.author : null;
description = drawInstantViewType != 6 && drawInstantViewType != 7 ? webPage.description : null;
photo = webPage.photo;
webDocument = null;
if (drawInstantViewType == 7) {
if (androidThemeSettings != null) {
document = new DocumentObject.ThemeDocument(androidThemeSettings);
} else {
document = androidThemeDocument;
}
} else {
document = webPage.document;
}
type = webPage.type;
duration = webPage.duration;
if (site_name != null && photo != null && site_name.toLowerCase().equals("instagram")) {
linkPreviewMaxWidth = Math.max(AndroidUtilities.displaySize.y / 3, currentMessageObject.textWidth);
}
boolean isSmallImageType = "app".equals(type) || "profile".equals(type) || "article".equals(type) || "telegram_bot".equals(type) || "telegram_user".equals(type) || "telegram_channel".equals(type) || "telegram_megagroup".equals(type) || "telegram_voicechat".equals(type) || "telegram_livestream".equals(type);
smallImage = !slideshow && (!drawInstantView || drawInstantViewType == 1 || drawInstantViewType == 9 || drawInstantViewType == 11 || drawInstantViewType == 13) && document == null && isSmallImageType;
isSmallImage = smallImage && type != null && currentMessageObject.photoThumbs != null;
} else if (hasInvoicePreview) {
TLRPC.TL_messageMediaInvoice invoice = (TLRPC.TL_messageMediaInvoice) messageObject.messageOwner.media;
site_name = messageObject.messageOwner.media.title;
title = null;
description = null;
photo = null;
author = null;
document = null;
if (invoice.photo instanceof TLRPC.TL_webDocument) {
webDocument = WebFile.createWithWebDocument(invoice.photo);
} else {
webDocument = null;
}
duration = 0;
type = "invoice";
isSmallImage = false;
smallImage = false;
} else {
TLRPC.TL_game game = messageObject.messageOwner.media.game;
site_name = game.title;
title = null;
webDocument = null;
description = TextUtils.isEmpty(messageObject.messageText) ? game.description : null;
photo = game.photo;
author = null;
document = game.document;
duration = 0;
type = "game";
isSmallImage = false;
smallImage = false;
}
if (drawInstantViewType == 11) {
site_name = LocaleController.getString("VoipChannelVoiceChat", R.string.VoipChannelVoiceChat);
} else if (drawInstantViewType == 9) {
site_name = LocaleController.getString("VoipGroupVoiceChat", R.string.VoipGroupVoiceChat);
} else if (drawInstantViewType == 6) {
site_name = LocaleController.getString("ChatBackground", R.string.ChatBackground);
} else if ("telegram_theme".equals(webpageType)) {
site_name = LocaleController.getString("ColorTheme", R.string.ColorTheme);
}
int additinalWidth = hasInvoicePreview ? 0 : AndroidUtilities.dp(10);
int restLinesCount = 3;
linkPreviewMaxWidth -= additinalWidth;
if (currentMessageObject.photoThumbs == null && photo != null) {
currentMessageObject.generateThumbs(true);
}
if (site_name != null) {
try {
int width = (int) Math.ceil(Theme.chat_replyNamePaint.measureText(site_name) + 1);
int restLines = 0;
if (!isSmallImage) {
siteNameLayout = new StaticLayout(site_name, Theme.chat_replyNamePaint, Math.min(width, linkPreviewMaxWidth), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else {
restLines = restLinesCount;
siteNameLayout = generateStaticLayout(site_name, Theme.chat_replyNamePaint, linkPreviewMaxWidth, linkPreviewMaxWidth - smallImageSide - smallSideMargin, restLinesCount, 1);
restLinesCount -= siteNameLayout.getLineCount();
}
siteNameRtl = Math.max(siteNameLayout.getLineLeft(0), 0) != 0;
int height = siteNameLayout.getLineBottom(siteNameLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
int layoutWidth = 0;
for (int a = 0; a < siteNameLayout.getLineCount(); ++a) {
int lineLeft = (int) Math.max(0, siteNameLayout.getLineLeft(a));
int lineWidth;
if (lineLeft != 0) {
lineWidth = siteNameLayout.getWidth() - lineLeft;
} else {
int max = linkPreviewMaxWidth;
if (a < restLines || lineLeft != 0 && isSmallImage) {
max -= smallImageSide + smallSideMargin;
}
lineWidth = (int) Math.min(max, Math.ceil(siteNameLayout.getLineWidth(a)));
}
if (a < restLines || lineLeft != 0 && isSmallImage) {
lineWidth += smallImageSide + smallSideMargin;
}
layoutWidth = Math.max(layoutWidth, lineWidth);
}
siteNameWidth = width = layoutWidth;
maxChildWidth = Math.max(maxChildWidth, width + additinalWidth);
maxWebWidth = Math.max(maxWebWidth, width + additinalWidth);
} catch (Exception e) {
FileLog.e(e);
}
}
boolean titleIsRTL = false;
if (title != null) {
try {
titleX = Integer.MAX_VALUE;
if (linkPreviewHeight != 0) {
linkPreviewHeight += AndroidUtilities.dp(2);
totalHeight += AndroidUtilities.dp(2);
}
int restLines = 0;
if (!isSmallImage) {
titleLayout = StaticLayoutEx.createStaticLayout(title, Theme.chat_replyNamePaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, linkPreviewMaxWidth, 4);
} else {
restLines = restLinesCount;
titleLayout = generateStaticLayout(title, Theme.chat_replyNamePaint, linkPreviewMaxWidth, linkPreviewMaxWidth - smallImageSide - smallSideMargin, restLinesCount, 4);
restLinesCount -= titleLayout.getLineCount();
}
int height = titleLayout.getLineBottom(titleLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
for (int a = 0; a < titleLayout.getLineCount(); a++) {
int lineLeft = (int) Math.max(0, titleLayout.getLineLeft(a));
if (lineLeft != 0) {
titleIsRTL = true;
}
if (titleX == Integer.MAX_VALUE) {
titleX = -lineLeft;
} else {
titleX = Math.max(titleX, -lineLeft);
}
int width;
if (lineLeft != 0) {
width = titleLayout.getWidth() - lineLeft;
} else {
int max = linkPreviewMaxWidth;
if (a < restLines || lineLeft != 0 && isSmallImage) {
max -= smallImageSide + smallSideMargin;
}
width = (int) Math.min(max, Math.ceil(titleLayout.getLineWidth(a)));
}
if (a < restLines || lineLeft != 0 && isSmallImage) {
width += smallImageSide + smallSideMargin;
}
maxChildWidth = Math.max(maxChildWidth, width + additinalWidth);
maxWebWidth = Math.max(maxWebWidth, width + additinalWidth);
}
} catch (Exception e) {
FileLog.e(e);
}
if (titleIsRTL && isSmallImage) {
linkPreviewMaxWidth -= AndroidUtilities.dp(48);
}
}
boolean authorIsRTL = false;
if (author != null && title == null) {
try {
if (linkPreviewHeight != 0) {
linkPreviewHeight += AndroidUtilities.dp(2);
totalHeight += AndroidUtilities.dp(2);
}
if (restLinesCount == 3 && (!isSmallImage || description == null)) {
authorLayout = new StaticLayout(author, Theme.chat_replyNamePaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else {
authorLayout = generateStaticLayout(author, Theme.chat_replyNamePaint, linkPreviewMaxWidth, linkPreviewMaxWidth - smallImageSide - smallSideMargin, restLinesCount, 1);
restLinesCount -= authorLayout.getLineCount();
}
int height = authorLayout.getLineBottom(authorLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
int lineLeft = (int) Math.max(authorLayout.getLineLeft(0), 0);
authorX = -lineLeft;
int width;
if (lineLeft != 0) {
width = authorLayout.getWidth() - lineLeft;
authorIsRTL = true;
} else {
width = (int) Math.ceil(authorLayout.getLineWidth(0));
}
maxChildWidth = Math.max(maxChildWidth, width + additinalWidth);
maxWebWidth = Math.max(maxWebWidth, width + additinalWidth);
} catch (Exception e) {
FileLog.e(e);
}
}
if (description != null) {
try {
descriptionX = 0;
currentMessageObject.generateLinkDescription();
if (linkPreviewHeight != 0) {
linkPreviewHeight += AndroidUtilities.dp(2);
totalHeight += AndroidUtilities.dp(2);
}
int restLines = 0;
boolean allowAllLines = site_name != null && site_name.toLowerCase().equals("twitter");
if (restLinesCount == 3 && !isSmallImage) {
descriptionLayout = StaticLayoutEx.createStaticLayout(messageObject.linkDescription, Theme.chat_replyTextPaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, linkPreviewMaxWidth, allowAllLines ? 100 : 6);
} else {
restLines = restLinesCount;
descriptionLayout = generateStaticLayout(messageObject.linkDescription, Theme.chat_replyTextPaint, linkPreviewMaxWidth, linkPreviewMaxWidth - smallImageSide - smallSideMargin, restLinesCount, allowAllLines ? 100 : 6);
}
int height = descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
boolean hasRTL = false;
for (int a = 0; a < descriptionLayout.getLineCount(); a++) {
int lineLeft = (int) Math.ceil(descriptionLayout.getLineLeft(a));
if (lineLeft > 0) {
hasRTL = true;
if (descriptionX == 0) {
descriptionX = -lineLeft;
} else {
descriptionX = Math.max(descriptionX, -lineLeft);
}
}
}
int textWidth = descriptionLayout.getWidth();
for (int a = 0; a < descriptionLayout.getLineCount(); a++) {
int lineLeft = (int) Math.ceil(descriptionLayout.getLineLeft(a));
if (lineLeft == 0 && descriptionX != 0) {
descriptionX = 0;
}
int width;
if (lineLeft > 0) {
width = textWidth - lineLeft;
} else {
if (hasRTL) {
width = textWidth;
} else {
width = Math.min((int) Math.ceil(descriptionLayout.getLineWidth(a)), textWidth);
}
}
if (a < restLines || restLines != 0 && lineLeft != 0 && isSmallImage) {
width += smallImageSide + smallSideMargin;
}
if (maxWebWidth < width + additinalWidth) {
if (titleIsRTL) {
titleX += (width + additinalWidth - maxWebWidth);
}
if (authorIsRTL) {
authorX += (width + additinalWidth - maxWebWidth);
}
maxWebWidth = width + additinalWidth;
}
maxChildWidth = Math.max(maxChildWidth, width + additinalWidth);
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (smallImage && (descriptionLayout == null && titleLayout == null)) {
smallImage = false;
isSmallImage = false;
}
int maxPhotoWidth = smallImage ? smallImageSide : linkPreviewMaxWidth;
if (document != null) {
if (MessageObject.isRoundVideoDocument(document)) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90);
photoParentObject = document;
documentAttach = document;
documentAttachType = DOCUMENT_ATTACH_TYPE_ROUND;
} else if (MessageObject.isGifDocument(document, messageObject.hasValidGroupId())) {
if (!messageObject.isGame() && !SharedConfig.autoplayGifs) {
messageObject.gifState = 1;
}
photoImage.setAllowStartAnimation(messageObject.gifState != 1);
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90);
if (currentPhotoObject != null) {
photoParentObject = document;
} else if (photo != null) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 90);
photoParentObject = photo;
}
if (currentPhotoObject != null && (currentPhotoObject.w == 0 || currentPhotoObject.h == 0)) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
currentPhotoObject.w = attribute.w;
currentPhotoObject.h = attribute.h;
break;
}
}
if (currentPhotoObject.w == 0 || currentPhotoObject.h == 0) {
currentPhotoObject.w = currentPhotoObject.h = AndroidUtilities.dp(150);
}
}
documentAttach = document;
documentAttachType = DOCUMENT_ATTACH_TYPE_GIF;
} else if (MessageObject.isVideoDocument(document)) {
if (photo != null) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, AndroidUtilities.getPhotoSize(), true);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(photo.sizes, 40);
photoParentObject = photo;
}
if (currentPhotoObject == null) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 320);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 40);
photoParentObject = document;
}
if (currentPhotoObject == currentPhotoObjectThumb) {
currentPhotoObjectThumb = null;
}
if (currentMessageObject.strippedThumb != null) {
currentPhotoObjectThumb = null;
currentPhotoObjectThumbStripped = currentMessageObject.strippedThumb;
}
if (currentPhotoObject == null) {
currentPhotoObject = new TLRPC.TL_photoSize();
currentPhotoObject.type = "s";
currentPhotoObject.location = new TLRPC.TL_fileLocationUnavailable();
}
if (currentPhotoObject != null && (currentPhotoObject.w == 0 || currentPhotoObject.h == 0 || currentPhotoObject instanceof TLRPC.TL_photoStrippedSize)) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
if (currentPhotoObject instanceof TLRPC.TL_photoStrippedSize) {
float scale = Math.max(attribute.w, attribute.w) / 50.0f;
currentPhotoObject.w = (int) (attribute.w / scale);
currentPhotoObject.h = (int) (attribute.h / scale);
} else {
currentPhotoObject.w = attribute.w;
currentPhotoObject.h = attribute.h;
}
break;
}
}
if (currentPhotoObject.w == 0 || currentPhotoObject.h == 0) {
currentPhotoObject.w = currentPhotoObject.h = AndroidUtilities.dp(150);
}
}
createDocumentLayout(0, messageObject);
} else if (MessageObject.isStickerDocument(document) || MessageObject.isAnimatedStickerDocument(document, true)) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 90);
photoParentObject = document;
if (currentPhotoObject != null && (currentPhotoObject.w == 0 || currentPhotoObject.h == 0)) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
currentPhotoObject.w = attribute.w;
currentPhotoObject.h = attribute.h;
break;
}
}
if (currentPhotoObject.w == 0 || currentPhotoObject.h == 0) {
currentPhotoObject.w = currentPhotoObject.h = AndroidUtilities.dp(150);
}
}
documentAttach = document;
documentAttachType = DOCUMENT_ATTACH_TYPE_STICKER;
} else if (drawInstantViewType == 6) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 320);
photoParentObject = document;
if (currentPhotoObject != null && (currentPhotoObject.w == 0 || currentPhotoObject.h == 0)) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
currentPhotoObject.w = attribute.w;
currentPhotoObject.h = attribute.h;
break;
}
}
if (currentPhotoObject.w == 0 || currentPhotoObject.h == 0) {
currentPhotoObject.w = currentPhotoObject.h = AndroidUtilities.dp(150);
}
}
documentAttach = document;
documentAttachType = DOCUMENT_ATTACH_TYPE_WALLPAPER;
String str = AndroidUtilities.formatFileSize(documentAttach.size);
durationWidth = (int) Math.ceil(Theme.chat_durationPaint.measureText(str));
videoInfoLayout = new StaticLayout(str, Theme.chat_durationPaint, durationWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else if (drawInstantViewType == 7) {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 700);
if (currentMessageObject.strippedThumb == null) {
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 40);
} else {
currentPhotoObjectThumbStripped = currentMessageObject.strippedThumb;
}
photoParentObject = document;
if (currentPhotoObject != null && (currentPhotoObject.w == 0 || currentPhotoObject.h == 0)) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
currentPhotoObject.w = attribute.w;
currentPhotoObject.h = attribute.h;
break;
}
}
if (currentPhotoObject.w == 0 || currentPhotoObject.h == 0) {
currentPhotoObject.w = currentPhotoObject.h = AndroidUtilities.dp(150);
}
}
documentAttach = document;
documentAttachType = DOCUMENT_ATTACH_TYPE_THEME;
} else {
calcBackgroundWidth(maxWidth, timeMore, maxChildWidth);
if (backgroundWidth < maxWidth + AndroidUtilities.dp(20)) {
backgroundWidth = maxWidth + AndroidUtilities.dp(20);
}
if (MessageObject.isVoiceDocument(document)) {
createDocumentLayout(backgroundWidth - AndroidUtilities.dp(10), messageObject);
mediaOffsetY = currentMessageObject.textHeight + AndroidUtilities.dp(8) + linkPreviewHeight;
totalHeight += AndroidUtilities.dp(30 + 14);
linkPreviewHeight += AndroidUtilities.dp(44);
maxWidth = maxWidth - AndroidUtilities.dp(86);
if (AndroidUtilities.isTablet()) {
maxChildWidth = Math.max(maxChildWidth, Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 52 : 0), AndroidUtilities.dp(220)) - AndroidUtilities.dp(30) + additinalWidth);
} else {
maxChildWidth = Math.max(maxChildWidth, Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 52 : 0), AndroidUtilities.dp(220)) - AndroidUtilities.dp(30) + additinalWidth);
}
calcBackgroundWidth(maxWidth, timeMore, maxChildWidth);
} else if (MessageObject.isMusicDocument(document)) {
int durationWidth = createDocumentLayout(backgroundWidth - AndroidUtilities.dp(10), messageObject);
mediaOffsetY = currentMessageObject.textHeight + AndroidUtilities.dp(8) + linkPreviewHeight;
totalHeight += AndroidUtilities.dp(42 + 14);
linkPreviewHeight += AndroidUtilities.dp(56);
maxWidth = maxWidth - AndroidUtilities.dp(86);
maxChildWidth = Math.max(maxChildWidth, durationWidth + additinalWidth + AndroidUtilities.dp(86 + 8));
if (songLayout != null && songLayout.getLineCount() > 0) {
maxChildWidth = (int) Math.max(maxChildWidth, songLayout.getLineWidth(0) + additinalWidth + AndroidUtilities.dp(86));
}
if (performerLayout != null && performerLayout.getLineCount() > 0) {
maxChildWidth = (int) Math.max(maxChildWidth, performerLayout.getLineWidth(0) + additinalWidth + AndroidUtilities.dp(86));
}
calcBackgroundWidth(maxWidth, timeMore, maxChildWidth);
} else {
createDocumentLayout(backgroundWidth - AndroidUtilities.dp(86 + 24 + 58), messageObject);
drawImageButton = true;
if (drawPhotoImage) {
totalHeight += AndroidUtilities.dp(86 + 14);
linkPreviewHeight += AndroidUtilities.dp(86);
photoImage.setImageCoords(0, totalHeight + namesOffset, AndroidUtilities.dp(86), AndroidUtilities.dp(86));
} else {
mediaOffsetY = currentMessageObject.textHeight + AndroidUtilities.dp(8) + linkPreviewHeight;
photoImage.setImageCoords(0, totalHeight + namesOffset - AndroidUtilities.dp(14), AndroidUtilities.dp(56), AndroidUtilities.dp(56));
totalHeight += AndroidUtilities.dp(50 + 14);
linkPreviewHeight += AndroidUtilities.dp(50);
if (docTitleLayout != null && docTitleLayout.getLineCount() > 1) {
int h = (docTitleLayout.getLineCount() - 1) * AndroidUtilities.dp(16);
totalHeight += h;
linkPreviewHeight += h;
}
}
}
}
} else if (photo != null) {
boolean isPhoto = type != null && type.equals("photo");
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, isPhoto || !smallImage ? AndroidUtilities.getPhotoSize() : maxPhotoWidth, !isPhoto);
photoParentObject = messageObject.photoThumbsObject;
checkOnlyButtonPressed = !isPhoto;
if (currentMessageObject.strippedThumb == null) {
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 40);
} else {
currentPhotoObjectThumbStripped = currentMessageObject.strippedThumb;
}
if (currentPhotoObjectThumb == currentPhotoObject) {
currentPhotoObjectThumb = null;
}
} else if (webDocument != null) {
if (!webDocument.mime_type.startsWith("image/")) {
webDocument = null;
}
drawImageButton = false;
}
if (documentAttachType != DOCUMENT_ATTACH_TYPE_MUSIC && documentAttachType != DOCUMENT_ATTACH_TYPE_AUDIO && documentAttachType != DOCUMENT_ATTACH_TYPE_DOCUMENT) {
if (currentPhotoObject != null || webDocument != null || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER || documentAttachType == DOCUMENT_ATTACH_TYPE_THEME) {
drawImageButton = photo != null && !smallImage || type != null && (type.equals("photo") || type.equals("document") && documentAttachType != DOCUMENT_ATTACH_TYPE_STICKER || type.equals("gif") || documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER);
if (linkPreviewHeight != 0) {
linkPreviewHeight += AndroidUtilities.dp(2);
totalHeight += AndroidUtilities.dp(2);
}
if (imageBackgroundSideColor != 0) {
maxPhotoWidth = AndroidUtilities.dp(208);
} else if (currentPhotoObject instanceof TLRPC.TL_photoSizeEmpty && currentPhotoObject.w != 0) {
maxPhotoWidth = currentPhotoObject.w;
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER || documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER || documentAttachType == DOCUMENT_ATTACH_TYPE_THEME) {
if (AndroidUtilities.isTablet()) {
maxPhotoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.5f);
} else {
maxPhotoWidth = (int) (getParentWidth() * 0.5f);
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND) {
maxPhotoWidth = AndroidUtilities.roundMessageSize;
photoImage.setAllowDecodeSingleFrame(true);
}
maxChildWidth = Math.max(maxChildWidth, maxPhotoWidth - (hasInvoicePreview ? AndroidUtilities.dp(12) : 0) + additinalWidth);
if (currentPhotoObject != null) {
currentPhotoObject.size = -1;
if (currentPhotoObjectThumb != null) {
currentPhotoObjectThumb.size = -1;
}
} else if (webDocument != null) {
webDocument.size = -1;
}
if (imageBackgroundSideColor != 0) {
imageBackgroundSideWidth = maxChildWidth - AndroidUtilities.dp(13);
}
int width;
int height;
if (smallImage || documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND) {
width = height = maxPhotoWidth;
} else {
if (hasGamePreview || hasInvoicePreview) {
if (hasInvoicePreview) {
width = 640;
height = 360;
for (int a = 0, N = webDocument.attributes.size(); a < N; a++) {
TLRPC.DocumentAttribute attribute = webDocument.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
width = attribute.w;
height = attribute.h;
break;
}
}
} else {
width = 640;
height = 360;
}
float scale = width / (float) (maxPhotoWidth - AndroidUtilities.dp(2));
width /= scale;
height /= scale;
} else {
if (drawInstantViewType == 7) {
width = 560;
height = 678;
} else if (currentPhotoObject != null) {
width = currentPhotoObject.w;
height = currentPhotoObject.h;
} else {
width = 30;
height = 50;
}
float scale = width / (float) (maxPhotoWidth - AndroidUtilities.dp(2));
width /= scale;
height /= scale;
if (site_name == null || site_name != null && !site_name.toLowerCase().equals("instagram") && documentAttachType == 0) {
if (height > AndroidUtilities.displaySize.y / 3) {
height = AndroidUtilities.displaySize.y / 3;
}
} else {
if (height > AndroidUtilities.displaySize.y / 2) {
height = AndroidUtilities.displaySize.y / 2;
}
}
if (imageBackgroundSideColor != 0) {
scale = height / (float) AndroidUtilities.dp(160);
width /= scale;
height /= scale;
}
if (height < AndroidUtilities.dp(60)) {
height = AndroidUtilities.dp(60);
}
}
}
if (isSmallImage) {
if (AndroidUtilities.dp(50) > linkPreviewHeight) {
totalHeight += AndroidUtilities.dp(50) - linkPreviewHeight + AndroidUtilities.dp(8);
linkPreviewHeight = AndroidUtilities.dp(50);
}
linkPreviewHeight -= AndroidUtilities.dp(8);
} else {
totalHeight += height + AndroidUtilities.dp(12);
linkPreviewHeight += height;
}
if (documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER && imageBackgroundSideColor == 0) {
photoImage.setImageCoords(0, 0, Math.max(maxChildWidth - AndroidUtilities.dp(13), width), height);
} else {
photoImage.setImageCoords(0, 0, width, height);
}
int w = (int) (width / AndroidUtilities.density);
int h = (int) (height / AndroidUtilities.density);
currentPhotoFilter = String.format(Locale.US, "%d_%d", w, h);
currentPhotoFilterThumb = String.format(Locale.US, "%d_%d_b", w, h);
if (webDocument != null) {
/*TODO*/
photoImage.setImage(ImageLocation.getForWebFile(webDocument), currentPhotoFilter, null, null, webDocument.size, null, messageObject, 1);
} else {
if (documentAttachType == DOCUMENT_ATTACH_TYPE_WALLPAPER) {
if (messageObject.mediaExists) {
photoImage.setImage(ImageLocation.getForDocument(documentAttach), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObject, document), "b1", 0, "jpg", messageObject, 1);
} else {
photoImage.setImage(null, null, ImageLocation.getForDocument(currentPhotoObject, document), "b1", 0, "jpg", messageObject, 1);
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_THEME) {
if (document instanceof DocumentObject.ThemeDocument) {
photoImage.setImage(ImageLocation.getForDocument(document), currentPhotoFilter, null, "b1", 0, "jpg", messageObject, 1);
} else {
photoImage.setImage(ImageLocation.getForDocument(currentPhotoObject, document), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObjectThumb, document), "b1", currentPhotoObjectThumbStripped, 0, "jpg", messageObject, 1);
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_STICKER) {
boolean isWebpSticker = messageObject.isSticker();
if (SharedConfig.loopStickers || (isWebpSticker && !messageObject.isVideoSticker())) {
photoImage.setAutoRepeat(1);
} else {
currentPhotoFilter = String.format(Locale.US, "%d_%d_nr_%s", w, h, messageObject.toString());
photoImage.setAutoRepeat(delegate != null && delegate.shouldRepeatSticker(messageObject) ? 2 : 3);
}
photoImage.setImage(ImageLocation.getForDocument(documentAttach), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObject, documentAttach), "b1", documentAttach.size, "webp", messageObject, 1);
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO) {
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
if (SharedConfig.autoplayVideo && (currentMessageObject.mediaExists || messageObject.canStreamVideo() && DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject))) {
photoImage.setAllowDecodeSingleFrame(true);
photoImage.setAllowStartAnimation(true);
photoImage.startAnimation();
photoImage.setImage(ImageLocation.getForDocument(documentAttach), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObjectThumb, documentAttach), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, documentAttach.size, null, messageObject, 0);
autoPlayingMedia = true;
} else {
if (currentPhotoObjectThumb != null || currentPhotoObjectThumbStripped != null) {
photoImage.setImage(ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
} else {
photoImage.setImage(null, null, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoObject instanceof TLRPC.TL_photoStrippedSize || "s".equals(currentPhotoObject.type) ? currentPhotoFilterThumb : currentPhotoFilter, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
}
}
} else if (documentAttachType == DOCUMENT_ATTACH_TYPE_GIF || documentAttachType == DOCUMENT_ATTACH_TYPE_ROUND) {
photoImage.setAllowDecodeSingleFrame(true);
boolean autoDownload = false;
if (MessageObject.isRoundVideoDocument(document)) {
photoImage.setRoundRadius(AndroidUtilities.roundMessageSize / 2);
canChangeRadius = false;
autoDownload = DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject);
} else if (MessageObject.isGifDocument(document, messageObject.hasValidGroupId())) {
autoDownload = DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject);
}
String filter = currentPhotoObject instanceof TLRPC.TL_photoStrippedSize || "s".equals(currentPhotoObject.type) ? currentPhotoFilterThumb : currentPhotoFilter;
if (messageObject.mediaExists || autoDownload) {
autoPlayingMedia = true;
TLRPC.VideoSize videoSize = MessageObject.getDocumentVideoThumb(document);
if (!messageObject.mediaExists && videoSize != null && (currentPhotoObject == null || currentPhotoObjectThumb == null)) {
photoImage.setImage(ImageLocation.getForDocument(document), document.size < 1024 * 32 ? null : ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForDocument(videoSize, documentAttach), null, ImageLocation.getForDocument(currentPhotoObject != null ? currentPhotoObject : currentPhotoObjectThumb, documentAttach), currentPhotoObject != null ? filter : currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
} else {
photoImage.setImage(ImageLocation.getForDocument(document), document.size < 1024 * 32 ? null : ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForDocument(currentPhotoObject, documentAttach), filter, ImageLocation.getForDocument(currentPhotoObjectThumb, documentAttach), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
}
} else {
photoImage.setImage(null, null, ImageLocation.getForDocument(currentPhotoObject, documentAttach), filter, 0, null, currentMessageObject, 0);
}
} else {
boolean photoExist = messageObject.mediaExists;
String fileName = FileLoader.getAttachFileName(currentPhotoObject);
if (hasGamePreview || photoExist || DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject) || FileLoader.getInstance(currentAccount).isLoadingFile(fileName)) {
photoNotSet = false;
photoImage.setImage(ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
} else {
photoNotSet = true;
if (currentPhotoObjectThumb != null || currentPhotoObjectThumbStripped != null) {
photoImage.setImage(null, null, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), String.format(Locale.US, "%d_%d_b", w, h), currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
} else {
photoImage.setImageBitmap((Drawable) null);
}
}
}
}
drawPhotoImage = true;
if (type != null && type.equals("video") && duration != 0) {
String str = AndroidUtilities.formatShortDuration(duration);
durationWidth = (int) Math.ceil(Theme.chat_durationPaint.measureText(str));
videoInfoLayout = new StaticLayout(str, Theme.chat_durationPaint, durationWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else if (hasGamePreview) {
boolean showGameOverlay = true;
try {
long bot_id = messageObject.messageOwner.via_bot_id != 0 ? messageObject.messageOwner.via_bot_id : messageObject.messageOwner.from_id.user_id;
if (bot_id != 0) {
TLRPC.User botUser = MessagesController.getInstance(currentAccount).getUser(bot_id);
if (botUser != null && botUser.username != null && botUser.username.equals("donate")) {
showGameOverlay = false;
}
}
} catch (Exception e) {
}
if (showGameOverlay) {
String str = LocaleController.getString("AttachGame", R.string.AttachGame).toUpperCase();
durationWidth = (int) Math.ceil(Theme.chat_gamePaint.measureText(str));
videoInfoLayout = new StaticLayout(str, Theme.chat_gamePaint, durationWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
}
} else {
photoImage.setImageBitmap((Drawable) null);
linkPreviewHeight -= AndroidUtilities.dp(6);
totalHeight += AndroidUtilities.dp(4);
}
if (hasInvoicePreview) {
CharSequence str;
if ((messageObject.messageOwner.media.flags & 4) != 0) {
str = LocaleController.getString("PaymentReceipt", R.string.PaymentReceipt).toUpperCase();
} else {
if (messageObject.messageOwner.media.test) {
str = LocaleController.getString("PaymentTestInvoice", R.string.PaymentTestInvoice).toUpperCase();
} else {
str = LocaleController.getString("PaymentInvoice", R.string.PaymentInvoice).toUpperCase();
}
}
String price = LocaleController.getInstance().formatCurrencyString(messageObject.messageOwner.media.total_amount, messageObject.messageOwner.media.currency);
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(price + " " + str);
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, price.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
durationWidth = (int) Math.ceil(Theme.chat_shipmentPaint.measureText(stringBuilder, 0, stringBuilder.length()));
videoInfoLayout = new StaticLayout(stringBuilder, Theme.chat_shipmentPaint, durationWidth + AndroidUtilities.dp(10), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!drawPhotoImage) {
totalHeight += AndroidUtilities.dp(6);
int timeWidthTotal = timeWidth + AndroidUtilities.dp(14 + (messageObject.isOutOwner() ? 20 : 0));
if (durationWidth + timeWidthTotal > maxWidth) {
maxChildWidth = Math.max(durationWidth, maxChildWidth);
totalHeight += AndroidUtilities.dp(12);
} else {
maxChildWidth = Math.max(durationWidth + timeWidthTotal, maxChildWidth);
}
}
}
if (hasGamePreview && messageObject.textHeight != 0) {
linkPreviewHeight += messageObject.textHeight + AndroidUtilities.dp(6);
totalHeight += AndroidUtilities.dp(4);
}
calcBackgroundWidth(maxWidth, timeMore, maxChildWidth);
}
createInstantViewButton();
} else {
photoImage.setImageBitmap((Drawable) null);
calcBackgroundWidth(maxWidth, timeMore, maxChildWidth);
}
} else if (messageObject.type == 16) {
createSelectorDrawable(0);
drawName = false;
drawForwardedName = false;
drawPhotoImage = false;
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
}
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(31);
int maxWidth = getMaxNameWidth() - AndroidUtilities.dp(50);
if (maxWidth < 0) {
maxWidth = AndroidUtilities.dp(10);
}
String text;
String time = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
TLRPC.TL_messageActionPhoneCall call = (TLRPC.TL_messageActionPhoneCall) messageObject.messageOwner.action;
boolean isMissed = call.reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed;
if (messageObject.isOutOwner()) {
if (isMissed) {
if (call.video) {
text = LocaleController.getString("CallMessageVideoOutgoingMissed", R.string.CallMessageVideoOutgoingMissed);
} else {
text = LocaleController.getString("CallMessageOutgoingMissed", R.string.CallMessageOutgoingMissed);
}
} else {
if (call.video) {
text = LocaleController.getString("CallMessageVideoOutgoing", R.string.CallMessageVideoOutgoing);
} else {
text = LocaleController.getString("CallMessageOutgoing", R.string.CallMessageOutgoing);
}
}
} else {
if (isMissed) {
if (call.video) {
text = LocaleController.getString("CallMessageVideoIncomingMissed", R.string.CallMessageVideoIncomingMissed);
} else {
text = LocaleController.getString("CallMessageIncomingMissed", R.string.CallMessageIncomingMissed);
}
} else if (call.reason instanceof TLRPC.TL_phoneCallDiscardReasonBusy) {
if (call.video) {
text = LocaleController.getString("CallMessageVideoIncomingDeclined", R.string.CallMessageVideoIncomingDeclined);
} else {
text = LocaleController.getString("CallMessageIncomingDeclined", R.string.CallMessageIncomingDeclined);
}
} else {
if (call.video) {
text = LocaleController.getString("CallMessageVideoIncoming", R.string.CallMessageVideoIncoming);
} else {
text = LocaleController.getString("CallMessageIncoming", R.string.CallMessageIncoming);
}
}
}
if (call.duration > 0) {
time += ", " + LocaleController.formatCallDuration(call.duration);
}
titleLayout = new StaticLayout(TextUtils.ellipsize(text, Theme.chat_audioTitlePaint, maxWidth, TextUtils.TruncateAt.END), Theme.chat_audioTitlePaint, maxWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
docTitleLayout = new StaticLayout(TextUtils.ellipsize(time, Theme.chat_contactPhonePaint, maxWidth, TextUtils.TruncateAt.END), Theme.chat_contactPhonePaint, maxWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
setMessageObjectInternal(messageObject);
totalHeight = AndroidUtilities.dp(65) + namesOffset;
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
} else if (messageObject.type == 12) {
drawName = messageObject.isFromGroup() && messageObject.isSupergroup() || messageObject.isImportedForward() && messageObject.messageOwner.fwd_from.from_id == null;
drawForwardedName = !isRepliesChat;
drawPhotoImage = true;
photoImage.setRoundRadius(AndroidUtilities.dp(22));
canChangeRadius = false;
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
}
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(31);
long uid = messageObject.messageOwner.media.user_id;
TLRPC.User user = null;
if (uid != 0) {
user = MessagesController.getInstance(currentAccount).getUser(uid);
}
int maxWidth = getMaxNameWidth() - AndroidUtilities.dp(80);
if (maxWidth < 0) {
maxWidth = AndroidUtilities.dp(10);
}
boolean hasName;
if (user != null) {
contactAvatarDrawable.setInfo(user);
hasName = true;
} else if (!TextUtils.isEmpty(messageObject.messageOwner.media.first_name) || !TextUtils.isEmpty(messageObject.messageOwner.media.last_name)) {
contactAvatarDrawable.setInfo(0, messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name);
hasName = true;
} else {
hasName = false;
}
photoImage.setForUserOrChat(user, hasName ? contactAvatarDrawable : Theme.chat_contactDrawable[messageObject.isOutOwner() ? 1 : 0], messageObject);
CharSequence phone;
if (!TextUtils.isEmpty(messageObject.vCardData)) {
phone = messageObject.vCardData;
drawInstantView = true;
drawInstantViewType = 5;
} else {
if (user != null && !TextUtils.isEmpty(user.phone)) {
phone = PhoneFormat.getInstance().format("+" + user.phone);
} else {
phone = messageObject.messageOwner.media.phone_number;
if (!TextUtils.isEmpty(phone)) {
phone = PhoneFormat.getInstance().format((String) phone);
} else {
phone = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
}
}
CharSequence currentNameString = ContactsController.formatName(messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name).replace('\n', ' ');
if (currentNameString.length() == 0) {
currentNameString = messageObject.messageOwner.media.phone_number;
if (currentNameString == null) {
currentNameString = "";
}
}
titleLayout = new StaticLayout(TextUtils.ellipsize(currentNameString, Theme.chat_contactNamePaint, maxWidth, TextUtils.TruncateAt.END), Theme.chat_contactNamePaint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
docTitleLayout = new StaticLayout(phone, Theme.chat_contactPhonePaint, maxWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false);
setMessageObjectInternal(messageObject);
if (drawForwardedName && messageObject.needDrawForwarded() && (currentPosition == null || currentPosition.minY == 0)) {
namesOffset += AndroidUtilities.dp(5);
} else if (drawNameLayout && messageObject.getReplyMsgId() == 0) {
namesOffset += AndroidUtilities.dp(7);
}
totalHeight = AndroidUtilities.dp(70 - 15) + namesOffset + docTitleLayout.getHeight();
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
if (drawInstantView) {
createInstantViewButton();
} else {
if (docTitleLayout.getLineCount() > 0) {
int timeLeft = backgroundWidth - AndroidUtilities.dp(40 + 18 + 44 + 8) - (int) Math.ceil(docTitleLayout.getLineWidth(docTitleLayout.getLineCount() - 1));
if (timeLeft < timeWidth) {
totalHeight += AndroidUtilities.dp(8);
}
}
}
if (!reactionsLayoutInBubble.isSmall) {
if (!reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.measure(backgroundWidth - AndroidUtilities.dp(32));
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY += -AndroidUtilities.dp(4);
if (backgroundWidth - AndroidUtilities.dp(32) - reactionsLayoutInBubble.lastLineX < timeWidth) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY += -AndroidUtilities.dp(12);
}
totalHeight += reactionsLayoutInBubble.totalHeight;
}
}
} else if (messageObject.type == 2) {
drawForwardedName = !isRepliesChat;
drawName = messageObject.isFromGroup() && messageObject.isSupergroup() || messageObject.isImportedForward() && messageObject.messageOwner.fwd_from.from_id == null;
int maxWidth;
if (AndroidUtilities.isTablet()) {
backgroundWidth = maxWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
} else {
backgroundWidth = maxWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
}
createDocumentLayout(backgroundWidth, messageObject);
setMessageObjectInternal(messageObject);
totalHeight = AndroidUtilities.dp(70) + namesOffset;
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
if (!reactionsLayoutInBubble.isSmall) {
reactionsLayoutInBubble.measure(maxWidth - AndroidUtilities.dp(24));
if (!reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height;
if (TextUtils.isEmpty(messageObject.caption)) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
} else {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(8);
}
measureTime(messageObject);
if (reactionsLayoutInBubble.width > backgroundWidth) {
backgroundWidth = reactionsLayoutInBubble.width;
}
if (reactionsLayoutInBubble.lastLineX + timeWidth + AndroidUtilities.dp(24) > backgroundWidth) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(12);
}
totalHeight += reactionsLayoutInBubble.totalHeight;
}
}
} else if (messageObject.type == 14) {
drawName = (messageObject.isFromGroup() && messageObject.isSupergroup() || messageObject.isImportedForward() && messageObject.messageOwner.fwd_from.from_id == null) && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_TOP) != 0);
int maxWidth;
if (AndroidUtilities.isTablet()) {
backgroundWidth = maxWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
} else {
backgroundWidth = maxWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(270));
}
createDocumentLayout(backgroundWidth, messageObject);
setMessageObjectInternal(messageObject);
totalHeight = AndroidUtilities.dp(82) + namesOffset;
if (currentPosition != null && currentMessagesGroup != null && currentMessagesGroup.messages.size() > 1) {
if ((currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0) {
totalHeight -= AndroidUtilities.dp(6);
mediaOffsetY -= AndroidUtilities.dp(6);
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
totalHeight -= AndroidUtilities.dp(6);
}
}
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
if (!reactionsLayoutInBubble.isSmall) {
reactionsLayoutInBubble.measure(maxWidth - AndroidUtilities.dp(24));
if (!reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(12);
measureTime(messageObject);
if (reactionsLayoutInBubble.width > backgroundWidth) {
backgroundWidth = reactionsLayoutInBubble.width;
}
if (reactionsLayoutInBubble.lastLineX + timeWidth + AndroidUtilities.dp(24) > backgroundWidth) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(12);
}
if (!messageObject.isRestrictedMessage && messageObject.caption != null) {
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(14);
}
totalHeight += reactionsLayoutInBubble.totalHeight;
}
}
} else if (messageObject.type == MessageObject.TYPE_POLL) {
if (timerParticles == null) {
timerParticles = new TimerParticles();
}
createSelectorDrawable(0);
drawName = true;
drawForwardedName = !isRepliesChat;
drawPhotoImage = false;
int maxWidth = Math.min(AndroidUtilities.dp(500), messageObject.getMaxMessageTextWidth());
backgroundWidth = maxWidth + AndroidUtilities.dp(31);
TLRPC.TL_messageMediaPoll media = (TLRPC.TL_messageMediaPoll) messageObject.messageOwner.media;
timerTransitionProgress = media.poll.close_date - ConnectionsManager.getInstance(currentAccount).getCurrentTime() < 60 ? 0.0f : 1.0f;
pollClosed = media.poll.closed;
pollVoted = messageObject.isVoted();
if (pollVoted) {
messageObject.checkedVotes.clear();
}
titleLayout = new StaticLayout(Emoji.replaceEmoji(media.poll.question, Theme.chat_audioTitlePaint.getFontMetricsInt(), AndroidUtilities.dp(16), false), Theme.chat_audioTitlePaint, maxWidth + AndroidUtilities.dp(2) - getExtraTextX() * 2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
boolean titleRtl = false;
if (titleLayout != null) {
for (int a = 0, N = titleLayout.getLineCount(); a < N; a++) {
if (titleLayout.getLineLeft(a) > 0) {
titleRtl = true;
break;
}
}
}
String title;
if (pollClosed) {
title = LocaleController.getString("FinalResults", R.string.FinalResults);
} else {
if (media.poll.quiz) {
if (media.poll.public_voters) {
title = LocaleController.getString("QuizPoll", R.string.QuizPoll);
} else {
title = LocaleController.getString("AnonymousQuizPoll", R.string.AnonymousQuizPoll);
}
} else if (media.poll.public_voters) {
title = LocaleController.getString("PublicPoll", R.string.PublicPoll);
} else {
title = LocaleController.getString("AnonymousPoll", R.string.AnonymousPoll);
}
}
docTitleLayout = new StaticLayout(TextUtils.ellipsize(title, Theme.chat_timePaint, maxWidth, TextUtils.TruncateAt.END), Theme.chat_timePaint, maxWidth + AndroidUtilities.dp(2) - getExtraTextX() * 2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (docTitleLayout != null && docTitleLayout.getLineCount() > 0) {
if (titleRtl && !LocaleController.isRTL) {
docTitleOffsetX = (int) Math.ceil(maxWidth - docTitleLayout.getLineWidth(0));
} else if (!titleRtl && LocaleController.isRTL) {
docTitleOffsetX = -(int) Math.ceil(docTitleLayout.getLineLeft(0));
} else {
docTitleOffsetX = 0;
}
}
int w = maxWidth - AndroidUtilities.dp(messageObject.isOutOwner() ? 28 : 8);
if (!isBot) {
TextPaint textPaint = !media.poll.public_voters && !media.poll.multiple_choice ? Theme.chat_livePaint : Theme.chat_locationAddressPaint;
CharSequence votes;
if (media.poll.quiz) {
votes = TextUtils.ellipsize(media.results.total_voters == 0 ? LocaleController.getString("NoVotesQuiz", R.string.NoVotesQuiz) : LocaleController.formatPluralString("Answer", media.results.total_voters), textPaint, w, TextUtils.TruncateAt.END);
} else {
votes = TextUtils.ellipsize(media.results.total_voters == 0 ? LocaleController.getString("NoVotes", R.string.NoVotes) : LocaleController.formatPluralString("Vote", media.results.total_voters), textPaint, w, TextUtils.TruncateAt.END);
}
infoLayout = new StaticLayout(votes, textPaint, w, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (infoLayout != null) {
if (!media.poll.public_voters && !media.poll.multiple_choice) {
infoX = (int) Math.ceil(infoLayout.getLineCount() > 0 ? -infoLayout.getLineLeft(0) : 0);
availableTimeWidth = (int) (maxWidth - infoLayout.getLineWidth(0) - AndroidUtilities.dp(16));
} else {
infoX = (int) ((backgroundWidth - AndroidUtilities.dp(28) - Math.ceil(infoLayout.getLineWidth(0))) / 2 - infoLayout.getLineLeft(0));
availableTimeWidth = maxWidth;
}
}
}
measureTime(messageObject);
lastPoll = media.poll;
lastPollResults = media.results.results;
lastPollResultsVoters = media.results.total_voters;
if (media.poll.multiple_choice && !pollVoted && !pollClosed || !isBot && (media.poll.public_voters && pollVoted || pollClosed && media.results != null && media.results.total_voters != 0 && media.poll.public_voters)) {
drawInstantView = true;
drawInstantViewType = 8;
createInstantViewButton();
}
if (media.poll.multiple_choice) {
createPollUI();
}
if (media.results != null) {
createPollUI();
int size = media.results.recent_voters.size();
for (int a = 0; a < pollAvatarImages.length; a++) {
if (!isBot && a < size) {
pollAvatarImages[a].setImageCoords(0, 0, AndroidUtilities.dp(16), AndroidUtilities.dp(16));
Long id = media.results.recent_voters.get(a);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id);
if (user != null) {
pollAvatarDrawables[a].setInfo(user);
pollAvatarImages[a].setForUserOrChat(user, pollAvatarDrawables[a]);
} else {
pollAvatarDrawables[a].setInfo(id, "", "");
}
pollAvatarImagesVisible[a] = true;
} else if (!pollUnvoteInProgress || size != 0) {
pollAvatarImages[a].setImageBitmap((Drawable) null);
pollAvatarImagesVisible[a] = false;
}
}
} else if (pollAvatarImages != null) {
for (int a = 0; a < pollAvatarImages.length; a++) {
pollAvatarImages[a].setImageBitmap((Drawable) null);
pollAvatarImagesVisible[a] = false;
}
}
int maxVote = 0;
if (!animatePollAnswer && pollVoteInProgress && vibrateOnPollVote) {
performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
animatePollAnswerAlpha = animatePollAnswer = attachedToWindow && (pollVoteInProgress || pollUnvoteInProgress);
ArrayList<PollButton> previousPollButtons = null;
ArrayList<PollButton> sortedPollButtons = new ArrayList<>();
if (!pollButtons.isEmpty()) {
previousPollButtons = new ArrayList<>(pollButtons);
pollButtons.clear();
if (!animatePollAnswer) {
animatePollAnswer = attachedToWindow && (pollVoted || pollClosed);
}
if (pollAnimationProgress > 0 && pollAnimationProgress < 1.0f) {
for (int b = 0, N2 = previousPollButtons.size(); b < N2; b++) {
PollButton button = previousPollButtons.get(b);
button.percent = (int) Math.ceil(button.prevPercent + (button.percent - button.prevPercent) * pollAnimationProgress);
button.percentProgress = button.prevPercentProgress + (button.percentProgress - button.prevPercentProgress) * pollAnimationProgress;
}
}
}
pollAnimationProgress = animatePollAnswer ? 0.0f : 1.0f;
byte[] votingFor;
if (!animatePollAnswerAlpha) {
pollVoteInProgress = false;
pollVoteInProgressNum = -1;
votingFor = SendMessagesHelper.getInstance(currentAccount).isSendingVote(currentMessageObject);
} else {
votingFor = null;
}
int height = titleLayout != null ? titleLayout.getHeight() : 0;
int restPercent = 100;
boolean hasDifferent = false;
int previousPercent = 0;
for (int a = 0, N = media.poll.answers.size(); a < N; a++) {
PollButton button = new PollButton();
button.answer = media.poll.answers.get(a);
button.title = new StaticLayout(Emoji.replaceEmoji(button.answer.text, Theme.chat_audioPerformerPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false), Theme.chat_audioPerformerPaint, maxWidth - AndroidUtilities.dp(33), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
button.y = height + AndroidUtilities.dp(52);
button.height = button.title.getHeight();
pollButtons.add(button);
sortedPollButtons.add(button);
height += button.height + AndroidUtilities.dp(26);
if (!media.results.results.isEmpty()) {
for (int b = 0, N2 = media.results.results.size(); b < N2; b++) {
TLRPC.TL_pollAnswerVoters answer = media.results.results.get(b);
if (Arrays.equals(button.answer.option, answer.option)) {
button.chosen = answer.chosen;
button.count = answer.voters;
button.correct = answer.correct;
if ((pollVoted || pollClosed) && media.results.total_voters > 0) {
button.decimal = 100 * (answer.voters / (float) media.results.total_voters);
button.percent = (int) button.decimal;
button.decimal -= button.percent;
} else {
button.percent = 0;
button.decimal = 0;
}
if (previousPercent == 0) {
previousPercent = button.percent;
} else if (button.percent != 0 && previousPercent != button.percent) {
hasDifferent = true;
}
restPercent -= button.percent;
maxVote = Math.max(button.percent, maxVote);
break;
}
}
}
if (previousPollButtons != null) {
for (int b = 0, N2 = previousPollButtons.size(); b < N2; b++) {
PollButton prevButton = previousPollButtons.get(b);
if (Arrays.equals(button.answer.option, prevButton.answer.option)) {
button.prevPercent = prevButton.percent;
button.prevPercentProgress = prevButton.percentProgress;
button.prevChosen = prevButton.chosen;
break;
}
}
}
if (votingFor != null && button.answer.option.length > 0 && Arrays.binarySearch(votingFor, button.answer.option[0]) >= 0) {
pollVoteInProgressNum = a;
pollVoteInProgress = true;
vibrateOnPollVote = true;
votingFor = null;
}
if (currentMessageObject.checkedVotes.contains(button.answer)) {
pollCheckBox[a].setChecked(true, false);
} else {
pollCheckBox[a].setChecked(false, false);
}
}
if (hasDifferent && restPercent != 0) {
Collections.sort(sortedPollButtons, (o1, o2) -> {
if (o1.decimal > o2.decimal) {
return -1;
} else if (o1.decimal < o2.decimal) {
return 1;
}
if (o1.decimal == o2.decimal) {
if (o1.percent > o2.percent) {
return 1;
} else if (o1.percent < o2.percent) {
return -1;
}
}
return 0;
});
for (int a = 0, N = Math.min(restPercent, sortedPollButtons.size()); a < N; a++) {
sortedPollButtons.get(a).percent += 1;
}
}
int width = backgroundWidth - AndroidUtilities.dp(76);
for (int b = 0, N2 = pollButtons.size(); b < N2; b++) {
PollButton button = pollButtons.get(b);
button.percentProgress = Math.max(AndroidUtilities.dp(5) / (float) width, maxVote != 0 ? button.percent / (float) maxVote : 0);
}
setMessageObjectInternal(messageObject);
if (isBot && !drawInstantView) {
height -= AndroidUtilities.dp(10);
} else if (media.poll.public_voters || media.poll.multiple_choice) {
height += AndroidUtilities.dp(13);
}
totalHeight = AndroidUtilities.dp(46 + 27) + namesOffset + height;
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
insantTextNewLine = false;
if (media.poll.public_voters || media.poll.multiple_choice) {
int instantTextWidth = 0;
for (int a = 0; a < 3; a++) {
String str;
if (a == 0) {
str = LocaleController.getString("PollViewResults", R.string.PollViewResults);
} else if (a == 1) {
str = LocaleController.getString("PollSubmitVotes", R.string.PollSubmitVotes);
} else {
str = LocaleController.getString("NoVotes", R.string.NoVotes);
}
instantTextWidth = Math.max(instantTextWidth, (int) Math.ceil(Theme.chat_instantViewPaint.measureText(str)));
}
int timeWidthTotal = timeWidth + (messageObject.isOutOwner() ? AndroidUtilities.dp(20) : 0) + getExtraTimeX();
if (!reactionsLayoutInBubble.isSmall && reactionsLayoutInBubble.isEmpty && timeWidthTotal >= (backgroundWidth - AndroidUtilities.dp(76) - instantTextWidth) / 2) {
totalHeight += AndroidUtilities.dp(18);
insantTextNewLine = true;
}
}
if (!reactionsLayoutInBubble.isSmall) {
if (!reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.measure(maxWidth);
totalHeight += reactionsLayoutInBubble.height + AndroidUtilities.dp(12);
int timeWidthTotal = timeWidth + (messageObject.isOutOwner() ? AndroidUtilities.dp(20) : 0) + getExtraTimeX();
if (timeWidthTotal >= (backgroundWidth - AndroidUtilities.dp(24) - reactionsLayoutInBubble.lastLineX)) {
totalHeight += AndroidUtilities.dp(16);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(16);
}
}
}
} else {
drawForwardedName = messageObject.messageOwner.fwd_from != null && !(messageObject.isAnyKindOfSticker() && messageObject.isDice());
if (!messageObject.isAnyKindOfSticker() && messageObject.type != MessageObject.TYPE_ROUND_VIDEO) {
drawName = (messageObject.isFromGroup() && messageObject.isSupergroup() || messageObject.isImportedForward() && messageObject.messageOwner.fwd_from.from_id == null) && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_TOP) != 0);
}
mediaBackground = isMedia = messageObject.type != 9;
drawImageButton = true;
drawPhotoImage = true;
int photoWidth = 0;
int photoHeight = 0;
int additionHeight = 0;
if (messageObject.gifState != 2 && !SharedConfig.autoplayGifs && (messageObject.type == 8 || messageObject.type == MessageObject.TYPE_ROUND_VIDEO)) {
messageObject.gifState = 1;
}
photoImage.setAllowDecodeSingleFrame(true);
if (messageObject.isVideo()) {
photoImage.setAllowStartAnimation(true);
} else if (messageObject.isRoundVideo()) {
MessageObject playingMessage = MediaController.getInstance().getPlayingMessageObject();
photoImage.setAllowStartAnimation(playingMessage == null || !playingMessage.isRoundVideo());
} else {
photoImage.setAllowStartAnimation(messageObject.gifState == 0);
}
photoImage.setForcePreview(messageObject.needDrawBluredPreview());
if (messageObject.type == 9) {
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(300));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(300));
}
if (checkNeedDrawShareButton(messageObject)) {
backgroundWidth -= AndroidUtilities.dp(20);
}
int maxTextWidth = 0;
int maxWidth = backgroundWidth - AndroidUtilities.dp(86 + 52);
int widthForCaption = 0;
createDocumentLayout(maxWidth, messageObject);
int width = backgroundWidth - AndroidUtilities.dp(31);
widthForCaption = width - AndroidUtilities.dp(10) - getExtraTextX() * 2;
if (!messageObject.isRestrictedMessage && !TextUtils.isEmpty(messageObject.caption)) {
try {
currentCaption = messageObject.caption;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
captionLayout = StaticLayout.Builder.obtain(messageObject.caption, 0, messageObject.caption.length(), Theme.chat_msgTextPaint, widthForCaption).setBreakStrategy(StaticLayout.BREAK_STRATEGY_HIGH_QUALITY).setHyphenationFrequency(StaticLayout.HYPHENATION_FREQUENCY_NONE).setAlignment(Layout.Alignment.ALIGN_NORMAL).build();
} else {
captionLayout = new StaticLayout(messageObject.caption, Theme.chat_msgTextPaint, widthForCaption, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
updateCaptionSpoilers();
} catch (Exception e) {
FileLog.e(e);
}
}
if (docTitleLayout != null) {
for (int a = 0, N = docTitleLayout.getLineCount(); a < N; a++) {
maxTextWidth = Math.max(maxTextWidth, (int) Math.ceil(docTitleLayout.getLineWidth(a) + docTitleLayout.getLineLeft(a)) + AndroidUtilities.dp(86 + (drawPhotoImage ? 52 : 22)));
}
}
if (infoLayout != null) {
for (int a = 0, N = infoLayout.getLineCount(); a < N; a++) {
maxTextWidth = Math.max(maxTextWidth, infoWidth + AndroidUtilities.dp(86 + (drawPhotoImage ? 52 : 22)));
}
}
if (captionLayout != null) {
for (int a = 0, N = captionLayout.getLineCount(); a < N; a++) {
int w = (int) Math.ceil(Math.min(widthForCaption, captionLayout.getLineWidth(a) + captionLayout.getLineLeft(a))) + AndroidUtilities.dp(31);
if (w > maxTextWidth) {
maxTextWidth = w;
}
}
}
if (!reactionsLayoutInBubble.isSmall) {
reactionsLayoutInBubble.measure(widthForCaption);
if (!reactionsLayoutInBubble.isEmpty && reactionsLayoutInBubble.width + AndroidUtilities.dp(31) > maxTextWidth) {
maxTextWidth = reactionsLayoutInBubble.width + AndroidUtilities.dp(31);
}
}
if (maxTextWidth > 0 && currentPosition == null) {
backgroundWidth = maxTextWidth;
maxWidth = maxTextWidth - AndroidUtilities.dp(31);
}
availableTimeWidth = maxWidth;
if (drawPhotoImage) {
photoWidth = AndroidUtilities.dp(86);
photoHeight = AndroidUtilities.dp(86);
availableTimeWidth -= photoWidth;
} else {
photoWidth = AndroidUtilities.dp(56);
photoHeight = AndroidUtilities.dp(56);
if (docTitleLayout != null && docTitleLayout.getLineCount() > 1) {
photoHeight += (docTitleLayout.getLineCount() - 1) * AndroidUtilities.dp(16);
}
if (TextUtils.isEmpty(messageObject.caption) && infoLayout != null) {
int lineCount = infoLayout.getLineCount();
measureTime(messageObject);
int timeLeft = backgroundWidth - AndroidUtilities.dp(40 + 18 + 56 + 8) - infoWidth;
if (reactionsLayoutInBubble.isSmall || reactionsLayoutInBubble.isEmpty) {
if (timeLeft < timeWidth) {
photoHeight += AndroidUtilities.dp(12);
} else if (lineCount == 1) {
photoHeight += AndroidUtilities.dp(4);
}
}
}
}
if (!reactionsLayoutInBubble.isSmall && !reactionsLayoutInBubble.isEmpty) {
if (!drawPhotoImage) {
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(2);
}
if (captionLayout != null && currentPosition != null && currentMessagesGroup != null && currentMessagesGroup.isDocuments) {
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(10);
} else if (!drawPhotoImage && !TextUtils.isEmpty(messageObject.caption) && ((docTitleLayout != null && docTitleLayout.getLineCount() > 1) || currentMessageObject.hasValidReplyMessageObject())) {
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(10);
}
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(8);
measureTime(messageObject);
if (drawPhotoImage && captionLayout == null) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(8);
}
int timeLeft = backgroundWidth - reactionsLayoutInBubble.lastLineX - AndroidUtilities.dp(24);
if (timeLeft < timeWidth) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(12);
}
additionHeight += reactionsLayoutInBubble.totalHeight;
}
} else if (messageObject.type == MessageObject.TYPE_GEO) {
TLRPC.GeoPoint point = messageObject.messageOwner.media.geo;
double lat = point.lat;
double lon = point._long;
int provider;
if ((int) messageObject.getDialogId() == 0) {
if (SharedConfig.mapPreviewType == 0) {
provider = -1;
} else if (SharedConfig.mapPreviewType == 1) {
provider = 4;
} else if (SharedConfig.mapPreviewType == 3) {
provider = 1;
} else {
provider = -1;
}
} else {
provider = -1;
}
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeoLive) {
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
}
backgroundWidth -= AndroidUtilities.dp(4);
if (checkNeedDrawShareButton(messageObject)) {
backgroundWidth -= AndroidUtilities.dp(20);
}
int maxWidth = backgroundWidth - AndroidUtilities.dp(37);
availableTimeWidth = maxWidth;
maxWidth -= AndroidUtilities.dp(54);
photoWidth = backgroundWidth - AndroidUtilities.dp(17);
photoHeight = AndroidUtilities.dp(195);
int offset = 268435456;
double rad = offset / Math.PI;
double y = Math.round(offset - rad * Math.log((1 + Math.sin(lat * Math.PI / 180.0)) / (1 - Math.sin(lat * Math.PI / 180.0))) / 2) - (AndroidUtilities.dp(10.3f) << (21 - 15));
lat = (Math.PI / 2.0 - 2 * Math.atan(Math.exp((y - offset) / rad))) * 180.0 / Math.PI;
currentUrl = AndroidUtilities.formapMapUrl(currentAccount, lat, lon, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), false, 15, provider);
lastWebFile = currentWebFile;
currentWebFile = WebFile.createWithGeoPoint(lat, lon, point.access_hash, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), 15, Math.min(2, (int) Math.ceil(AndroidUtilities.density)));
if (!(locationExpired = isCurrentLocationTimeExpired(messageObject))) {
photoImage.setCrossfadeWithOldImage(true);
mediaBackground = false;
additionHeight = AndroidUtilities.dp(56);
AndroidUtilities.runOnUIThread(invalidateRunnable, 1000);
scheduledInvalidate = true;
} else {
backgroundWidth -= AndroidUtilities.dp(9);
}
docTitleLayout = new StaticLayout(TextUtils.ellipsize(LocaleController.getString("AttachLiveLocation", R.string.AttachLiveLocation), Theme.chat_locationTitlePaint, maxWidth, TextUtils.TruncateAt.END), Theme.chat_locationTitlePaint, maxWidth + AndroidUtilities.dp(2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
updateCurrentUserAndChat();
if (currentUser != null) {
contactAvatarDrawable.setInfo(currentUser);
locationImageReceiver.setForUserOrChat(currentUser, contactAvatarDrawable);
} else if (currentChat != null) {
if (currentChat.photo != null) {
currentPhoto = currentChat.photo.photo_small;
}
contactAvatarDrawable.setInfo(currentChat);
locationImageReceiver.setForUserOrChat(currentChat, contactAvatarDrawable);
} else {
locationImageReceiver.setImage(null, null, contactAvatarDrawable, null, null, 0);
}
infoLayout = new StaticLayout(TextUtils.ellipsize(LocaleController.formatLocationUpdateDate(messageObject.messageOwner.edit_date != 0 ? messageObject.messageOwner.edit_date : messageObject.messageOwner.date), Theme.chat_locationAddressPaint, maxWidth + AndroidUtilities.dp(2), TextUtils.TruncateAt.END), Theme.chat_locationAddressPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} else if (!TextUtils.isEmpty(messageObject.messageOwner.media.title)) {
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
}
backgroundWidth -= AndroidUtilities.dp(4);
if (checkNeedDrawShareButton(messageObject)) {
backgroundWidth -= AndroidUtilities.dp(20);
}
int maxWidth = backgroundWidth - AndroidUtilities.dp(34);
availableTimeWidth = maxWidth;
photoWidth = backgroundWidth - AndroidUtilities.dp(17);
photoHeight = AndroidUtilities.dp(195);
mediaBackground = false;
currentUrl = AndroidUtilities.formapMapUrl(currentAccount, lat, lon, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), true, 15, provider);
currentWebFile = WebFile.createWithGeoPoint(point, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), 15, Math.min(2, (int) Math.ceil(AndroidUtilities.density)));
docTitleLayout = StaticLayoutEx.createStaticLayout(messageObject.messageOwner.media.title, Theme.chat_locationTitlePaint, maxWidth + AndroidUtilities.dp(4), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, maxWidth, 1);
additionHeight += AndroidUtilities.dp(50);
int lineCount = docTitleLayout.getLineCount();
if (!TextUtils.isEmpty(messageObject.messageOwner.media.address)) {
infoLayout = StaticLayoutEx.createStaticLayout(messageObject.messageOwner.media.address, Theme.chat_locationAddressPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, maxWidth, 1);
measureTime(messageObject);
int timeLeft = backgroundWidth - (int) Math.ceil(infoLayout.getLineWidth(0)) - AndroidUtilities.dp(24);
boolean isRtl = infoLayout.getLineLeft(0) > 0;
if (isRtl || timeLeft < timeWidth + AndroidUtilities.dp(20 + (messageObject.isOutOwner() ? 20 : 0))) {
additionHeight += AndroidUtilities.dp(isRtl ? 10 : 8);
}
} else {
infoLayout = null;
}
} else {
if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
} else {
backgroundWidth = Math.min(getParentWidth() - AndroidUtilities.dp(drawAvatar ? 102 : 50), AndroidUtilities.dp(252 + 37));
}
backgroundWidth -= AndroidUtilities.dp(4);
if (checkNeedDrawShareButton(messageObject)) {
backgroundWidth -= AndroidUtilities.dp(20);
}
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(34);
photoWidth = backgroundWidth - AndroidUtilities.dp(8);
photoHeight = AndroidUtilities.dp(195);
currentUrl = AndroidUtilities.formapMapUrl(currentAccount, lat, lon, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), true, 15, provider);
currentWebFile = WebFile.createWithGeoPoint(point, (int) (photoWidth / AndroidUtilities.density), (int) (photoHeight / AndroidUtilities.density), 15, Math.min(2, (int) Math.ceil(AndroidUtilities.density)));
}
if ((int) messageObject.getDialogId() == 0) {
if (SharedConfig.mapPreviewType == 0) {
currentMapProvider = 2;
} else if (SharedConfig.mapPreviewType == 1) {
currentMapProvider = 1;
} else if (SharedConfig.mapPreviewType == 3) {
currentMapProvider = 1;
} else {
currentMapProvider = -1;
}
} else {
currentMapProvider = MessagesController.getInstance(messageObject.currentAccount).mapProvider;
// default to Telegram
if (currentMapProvider != -1) {
currentMapProvider = 2;
}
}
if (currentMapProvider == -1) {
photoImage.setImage(null, null, null, null, messageObject, 0);
} else if (currentMapProvider == 2) {
if (currentWebFile != null) {
ImageLocation lastLocation = lastWebFile == null ? null : ImageLocation.getForWebFile(lastWebFile);
photoImage.setImage(ImageLocation.getForWebFile(currentWebFile), null, lastLocation, null, (Drawable) null, messageObject, 0);
}
} else {
if (currentMapProvider == 3 || currentMapProvider == 4) {
ImageLoader.getInstance().addTestWebFile(currentUrl, currentWebFile);
addedForTest = true;
}
if (currentUrl != null) {
photoImage.setImage(currentUrl, null, null, null, 0);
}
}
if (!reactionsLayoutInBubble.isSmall && !reactionsLayoutInBubble.isEmpty) {
reactionsLayoutInBubble.measure(backgroundWidth - AndroidUtilities.dp(16));
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(14);
measureTime(messageObject);
if (reactionsLayoutInBubble.lastLineX + timeWidth + AndroidUtilities.dp(24) > backgroundWidth) {
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(12);
}
additionHeight += reactionsLayoutInBubble.totalHeight;
}
} else if (messageObject.isAnyKindOfSticker()) {
drawBackground = false;
boolean isWebpSticker = messageObject.type == MessageObject.TYPE_STICKER;
for (int a = 0; a < messageObject.getDocument().attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageObject.getDocument().attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
photoWidth = attribute.w;
photoHeight = attribute.h;
break;
}
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
photoWidth = attribute.w;
photoHeight = attribute.h;
break;
}
}
if ((messageObject.isAnimatedSticker() || messageObject.isVideoSticker()) && photoWidth == 0 && photoHeight == 0) {
photoWidth = photoHeight = 512;
}
float maxHeight;
int maxWidth;
if (AndroidUtilities.isTablet()) {
maxHeight = maxWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.4f);
} else {
maxHeight = maxWidth = (int) (Math.min(getParentWidth(), AndroidUtilities.displaySize.y) * 0.5f);
}
String filter;
if (messageObject.isAnimatedEmoji() || messageObject.isDice()) {
float zoom = MessagesController.getInstance(currentAccount).animatedEmojisZoom;
photoWidth = (int) ((photoWidth / 512.0f) * maxWidth * zoom);
photoHeight = (int) ((photoHeight / 512.0f) * maxHeight * zoom);
} else {
if (photoWidth == 0) {
photoHeight = (int) maxHeight;
photoWidth = photoHeight + AndroidUtilities.dp(100);
}
photoHeight *= maxWidth / (float) photoWidth;
photoWidth = (int) maxWidth;
if (photoHeight > maxHeight) {
photoWidth *= maxHeight / photoHeight;
photoHeight = (int) maxHeight;
}
}
Object parentObject = messageObject;
int w = (int) (photoWidth / AndroidUtilities.density);
int h = (int) (photoHeight / AndroidUtilities.density);
boolean shouldRepeatSticker = delegate != null && delegate.shouldRepeatSticker(messageObject);
if (currentMessageObject.strippedThumb == null) {
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 40);
} else {
currentPhotoObjectThumbStripped = currentMessageObject.strippedThumb;
}
photoParentObject = messageObject.photoThumbsObject;
if (messageObject.isDice()) {
filter = String.format(Locale.US, "%d_%d_dice_%s_%s", w, h, messageObject.getDiceEmoji(), messageObject.toString());
photoImage.setAutoRepeat(2);
String emoji = currentMessageObject.getDiceEmoji();
TLRPC.TL_messages_stickerSet stickerSet = MediaDataController.getInstance(currentAccount).getStickerSetByEmojiOrName(emoji);
if (stickerSet != null) {
if (stickerSet.documents.size() > 0) {
int value = currentMessageObject.getDiceValue();
if (value <= 0) {
TLRPC.Document document = stickerSet.documents.get(0);
if ("\uD83C\uDFB0".equals(emoji)) {
currentPhotoObjectThumb = null;
} else {
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(document.thumbs, 40);
}
photoParentObject = document;
}
}
}
} else if (messageObject.isAnimatedEmoji()) {
filter = String.format(Locale.US, "%d_%d_nr_%s" + messageObject.emojiAnimatedStickerColor, w, h, messageObject.toString());
photoImage.setAutoRepeat(shouldRepeatSticker ? 2 : 3);
parentObject = MessageObject.getInputStickerSet(messageObject.emojiAnimatedSticker);
} else if (SharedConfig.loopStickers || (isWebpSticker && !messageObject.isVideoSticker())) {
filter = String.format(Locale.US, "%d_%d", w, h);
photoImage.setAutoRepeat(1);
} else {
filter = String.format(Locale.US, "%d_%d_nr_%s", w, h, messageObject.toString());
photoImage.setAutoRepeat(shouldRepeatSticker ? 2 : 3);
}
documentAttachType = DOCUMENT_ATTACH_TYPE_STICKER;
availableTimeWidth = photoWidth - AndroidUtilities.dp(14);
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
photoImage.setRoundRadius(0);
canChangeRadius = false;
if (messageObject.isVideoSticker()) {
// photoImage.setAspectFit(true);
photoImage.setImage(ImageLocation.getForDocument(messageObject.getDocument()), ImageLoader.AUTOPLAY_FILTER, null, null, messageObject.pathThumb, messageObject.getDocument().size, isWebpSticker ? "webp" : null, parentObject, 1);
} else if (messageObject.pathThumb != null) {
photoImage.setImage(ImageLocation.getForDocument(messageObject.getDocument()), filter, messageObject.pathThumb, messageObject.getDocument().size, isWebpSticker ? "webp" : null, parentObject, 1);
} else if (messageObject.attachPathExists) {
photoImage.setImage(ImageLocation.getForPath(messageObject.messageOwner.attachPath), filter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), "b1", currentPhotoObjectThumbStripped, messageObject.getDocument().size, isWebpSticker ? "webp" : null, parentObject, 1);
} else if (messageObject.getDocument().id != 0) {
photoImage.setImage(ImageLocation.getForDocument(messageObject.getDocument()), filter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), "b1", currentPhotoObjectThumbStripped, messageObject.getDocument().size, isWebpSticker ? "webp" : null, parentObject, 1);
} else {
photoImage.setImage(null, null, null, null, messageObject, 0);
}
if (!reactionsLayoutInBubble.isSmall) {
reactionsLayoutInBubble.measure(maxWidth);
reactionsLayoutInBubble.drawServiceShaderBackground = true;
reactionsLayoutInBubble.totalHeight = reactionsLayoutInBubble.height + AndroidUtilities.dp(8);
additionHeight += reactionsLayoutInBubble.totalHeight;
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(4);
}
} else {
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize());
photoParentObject = messageObject.photoThumbsObject;
boolean useFullWidth = false;
if (messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
documentAttach = messageObject.getDocument();
documentAttachType = DOCUMENT_ATTACH_TYPE_ROUND;
} else {
if (AndroidUtilities.isTablet()) {
photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
} else {
if (currentPhotoObject != null && (messageObject.type == MessageObject.TYPE_PHOTO || messageObject.type == MessageObject.TYPE_VIDEO || messageObject.type == 8) && currentPhotoObject.w >= currentPhotoObject.h) {
photoWidth = Math.min(getParentWidth(), AndroidUtilities.displaySize.y) - AndroidUtilities.dp(64 + (checkNeedDrawShareButton(messageObject) ? 10 : 0));
useFullWidth = true;
} else {
photoWidth = (int) (Math.min(getParentWidth(), AndroidUtilities.displaySize.y) * 0.7f);
}
}
}
photoHeight = photoWidth + AndroidUtilities.dp(100);
if (!useFullWidth) {
if (messageObject.type != 5 && checkNeedDrawShareButton(messageObject)) {
photoWidth -= AndroidUtilities.dp(20);
}
if (photoWidth > AndroidUtilities.getPhotoSize()) {
photoWidth = AndroidUtilities.getPhotoSize();
}
if (photoHeight > AndroidUtilities.getPhotoSize()) {
photoHeight = AndroidUtilities.getPhotoSize();
}
} else if (drawAvatar) {
photoWidth -= AndroidUtilities.dp(52);
}
boolean needQualityPreview = false;
if (messageObject.type == MessageObject.TYPE_PHOTO) {
// photo
updateSecretTimeText(messageObject);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 40);
} else if (messageObject.type == MessageObject.TYPE_VIDEO || messageObject.type == 8) {
// video, gif
createDocumentLayout(0, messageObject);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 40);
updateSecretTimeText(messageObject);
needQualityPreview = true;
} else if (messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 40);
needQualityPreview = true;
}
if (currentMessageObject.strippedThumb != null) {
currentPhotoObjectThumb = null;
currentPhotoObjectThumbStripped = currentMessageObject.strippedThumb;
}
int w;
int h;
if (messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
if (isPlayingRound) {
w = h = AndroidUtilities.roundPlayingMessageSize;
} else {
w = h = AndroidUtilities.roundMessageSize;
}
} else {
TLRPC.PhotoSize size = currentPhotoObject != null ? currentPhotoObject : currentPhotoObjectThumb;
int imageW = 0;
int imageH = 0;
if (size != null && !(size instanceof TLRPC.TL_photoStrippedSize)) {
imageW = size.w;
imageH = size.h;
} else if (documentAttach != null) {
for (int a = 0, N = documentAttach.attributes.size(); a < N; a++) {
TLRPC.DocumentAttribute attribute = documentAttach.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
imageW = attribute.w;
imageH = attribute.h;
}
}
}
Point point = getMessageSize(imageW, imageH, photoWidth, photoHeight);
w = (int) point.x;
h = (int) point.y;
}
if (currentPhotoObject != null && "s".equals(currentPhotoObject.type)) {
currentPhotoObject = null;
}
if (currentPhotoObject != null && currentPhotoObject == currentPhotoObjectThumb) {
if (messageObject.type == MessageObject.TYPE_PHOTO) {
currentPhotoObjectThumb = null;
currentPhotoObjectThumbStripped = null;
} else {
currentPhotoObject = null;
}
}
if (needQualityPreview) {
if (!messageObject.needDrawBluredPreview() && (currentPhotoObject == null || currentPhotoObject == currentPhotoObjectThumb) && (currentPhotoObjectThumb == null || !"m".equals(currentPhotoObjectThumb.type))) {
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
}
}
if (currentMessagesGroup == null && messageObject.caption != null) {
mediaBackground = false;
}
if ((w == 0 || h == 0) && messageObject.type == 8) {
for (int a = 0; a < messageObject.getDocument().attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageObject.getDocument().attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
float scale = (float) attribute.w / (float) photoWidth;
w = (int) (attribute.w / scale);
h = (int) (attribute.h / scale);
if (h > photoHeight) {
float scale2 = h;
h = photoHeight;
scale2 /= h;
w = (int) (w / scale2);
} else if (h < AndroidUtilities.dp(120)) {
h = AndroidUtilities.dp(120);
float hScale = (float) attribute.h / h;
if (attribute.w / hScale < photoWidth) {
w = (int) (attribute.w / hScale);
}
}
break;
}
}
}
if (w == 0 || h == 0) {
w = h = AndroidUtilities.dp(150);
}
if (messageObject.type == MessageObject.TYPE_VIDEO) {
if (w < infoWidth + AndroidUtilities.dp(16 + 24)) {
w = infoWidth + AndroidUtilities.dp(16 + 24);
}
}
if (commentLayout != null && drawSideButton != 3 && w < totalCommentWidth + AndroidUtilities.dp(10)) {
w = totalCommentWidth + AndroidUtilities.dp(10);
}
if (currentMessagesGroup != null) {
int firstLineWidth = 0;
int dWidth = getGroupPhotosWidth();
for (int a = 0; a < currentMessagesGroup.posArray.size(); a++) {
MessageObject.GroupedMessagePosition position = currentMessagesGroup.posArray.get(a);
if (position.minY == 0) {
firstLineWidth += Math.ceil((position.pw + position.leftSpanOffset) / 1000.0f * dWidth);
} else {
break;
}
}
availableTimeWidth = firstLineWidth - AndroidUtilities.dp(35);
} else {
availableTimeWidth = photoWidth - AndroidUtilities.dp(14);
}
if (messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
availableTimeWidth = (int) (AndroidUtilities.roundMessageSize - Math.ceil(Theme.chat_audioTimePaint.measureText("00:00")) - AndroidUtilities.dp(46));
}
measureTime(messageObject);
int timeWidthTotal = timeWidth + AndroidUtilities.dp((SharedConfig.bubbleRadius >= 10 ? 22 : 18) + (messageObject.isOutOwner() ? 20 : 0));
if (w < timeWidthTotal) {
w = timeWidthTotal;
}
if (messageObject.isRoundVideo()) {
w = h = Math.min(w, h);
drawBackground = false;
photoImage.setRoundRadius(w / 2);
canChangeRadius = false;
} else if (messageObject.needDrawBluredPreview()) {
if (AndroidUtilities.isTablet()) {
w = h = (int) (AndroidUtilities.getMinTabletSide() * 0.5f);
} else {
w = h = (int) (Math.min(getParentWidth(), AndroidUtilities.displaySize.y) * 0.5f);
}
}
int widthForCaption = 0;
boolean fixPhotoWidth = false;
if (currentMessagesGroup != null) {
float maxHeight = Math.max(getParentWidth(), AndroidUtilities.displaySize.y) * 0.5f;
int dWidth = getGroupPhotosWidth();
w = (int) Math.ceil(currentPosition.pw / 1000.0f * dWidth);
if (currentPosition.minY != 0 && (messageObject.isOutOwner() && (currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0 || !messageObject.isOutOwner() && (currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0)) {
int firstLineWidth = 0;
int currentLineWidth = 0;
for (int a = 0; a < currentMessagesGroup.posArray.size(); a++) {
MessageObject.GroupedMessagePosition position = currentMessagesGroup.posArray.get(a);
if (position.minY == 0) {
firstLineWidth += Math.ceil(position.pw / 1000.0f * dWidth) + (position.leftSpanOffset != 0 ? Math.ceil(position.leftSpanOffset / 1000.0f * dWidth) : 0);
} else if (position.minY == currentPosition.minY) {
currentLineWidth += Math.ceil((position.pw) / 1000.0f * dWidth) + (position.leftSpanOffset != 0 ? Math.ceil(position.leftSpanOffset / 1000.0f * dWidth) : 0);
} else if (position.minY > currentPosition.minY) {
break;
}
}
w += firstLineWidth - currentLineWidth;
}
w -= AndroidUtilities.dp(9);
if (isAvatarVisible) {
w -= AndroidUtilities.dp(48);
}
if (currentPosition.siblingHeights != null) {
h = 0;
for (int a = 0; a < currentPosition.siblingHeights.length; a++) {
h += (int) Math.ceil(maxHeight * currentPosition.siblingHeights[a]);
}
// TODO fix
h += (currentPosition.maxY - currentPosition.minY) * Math.round(7 * AndroidUtilities.density);
} else {
h = (int) Math.ceil(maxHeight * currentPosition.ph);
}
backgroundWidth = w;
if ((currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0 && (currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0) {
w -= AndroidUtilities.dp(8);
} else if ((currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) == 0 && (currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) == 0) {
w -= AndroidUtilities.dp(11);
} else if ((currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0) {
w -= AndroidUtilities.dp(10);
} else {
w -= AndroidUtilities.dp(9);
}
photoWidth = w;
if (!currentPosition.edge) {
photoWidth += AndroidUtilities.dp(10);
}
photoHeight = h;
widthForCaption += photoWidth - AndroidUtilities.dp(10);
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0 || currentMessagesGroup.hasSibling && (currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0) {
widthForCaption += getAdditionalWidthForPosition(currentPosition);
int count = currentMessagesGroup.messages.size();
for (int i = 0; i < count; i++) {
MessageObject m = currentMessagesGroup.messages.get(i);
MessageObject.GroupedMessagePosition rowPosition = currentMessagesGroup.posArray.get(i);
if (rowPosition != currentPosition && (rowPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
w = (int) Math.ceil(rowPosition.pw / 1000.0f * dWidth);
if (rowPosition.minY != 0 && (messageObject.isOutOwner() && (rowPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0 || !messageObject.isOutOwner() && (rowPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0)) {
int firstLineWidth = 0;
int currentLineWidth = 0;
for (int a = 0; a < currentMessagesGroup.posArray.size(); a++) {
MessageObject.GroupedMessagePosition position = currentMessagesGroup.posArray.get(a);
if (position.minY == 0) {
firstLineWidth += Math.ceil(position.pw / 1000.0f * dWidth) + (position.leftSpanOffset != 0 ? Math.ceil(position.leftSpanOffset / 1000.0f * dWidth) : 0);
} else if (position.minY == rowPosition.minY) {
currentLineWidth += Math.ceil((position.pw) / 1000.0f * dWidth) + (position.leftSpanOffset != 0 ? Math.ceil(position.leftSpanOffset / 1000.0f * dWidth) : 0);
} else if (position.minY > rowPosition.minY) {
break;
}
}
w += firstLineWidth - currentLineWidth;
}
w -= AndroidUtilities.dp(9);
if ((rowPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0 && (rowPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0) {
w -= AndroidUtilities.dp(8);
} else if ((rowPosition.flags & MessageObject.POSITION_FLAG_RIGHT) == 0 && (rowPosition.flags & MessageObject.POSITION_FLAG_LEFT) == 0) {
w -= AndroidUtilities.dp(11);
} else if ((rowPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0) {
w -= AndroidUtilities.dp(10);
} else {
w -= AndroidUtilities.dp(9);
}
if (isChat && !isThreadPost && !m.isOutOwner() && m.needDrawAvatar() && (rowPosition == null || rowPosition.edge)) {
w -= AndroidUtilities.dp(48);
}
w += getAdditionalWidthForPosition(rowPosition);
if (!rowPosition.edge) {
w += AndroidUtilities.dp(10);
}
widthForCaption += w;
if (rowPosition.minX < currentPosition.minX || currentMessagesGroup.hasSibling && rowPosition.minY != rowPosition.maxY) {
captionOffsetX -= w;
}
}
if (m.caption != null) {
if (currentCaption != null) {
currentCaption = null;
break;
} else {
currentCaption = m.caption;
}
}
}
}
} else {
photoHeight = h;
photoWidth = w;
currentCaption = messageObject.caption;
int minCaptionWidth;
if (AndroidUtilities.isTablet()) {
minCaptionWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.65f);
} else {
minCaptionWidth = (int) (Math.min(getParentWidth(), AndroidUtilities.displaySize.y) * 0.65f);
}
if (!messageObject.needDrawBluredPreview() && (currentCaption != null || (!reactionsLayoutInBubble.isEmpty && !reactionsLayoutInBubble.isSmall)) && photoWidth < minCaptionWidth) {
widthForCaption = minCaptionWidth;
fixPhotoWidth = true;
} else {
widthForCaption = photoWidth - AndroidUtilities.dp(10);
}
backgroundWidth = photoWidth + AndroidUtilities.dp(8);
if (!mediaBackground) {
backgroundWidth += AndroidUtilities.dp(9);
}
}
if (currentCaption != null) {
try {
widthForCaption -= getExtraTextX() * 2;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
captionLayout = StaticLayout.Builder.obtain(currentCaption, 0, currentCaption.length(), Theme.chat_msgTextPaint, widthForCaption).setBreakStrategy(StaticLayout.BREAK_STRATEGY_HIGH_QUALITY).setHyphenationFrequency(StaticLayout.HYPHENATION_FREQUENCY_NONE).setAlignment(Layout.Alignment.ALIGN_NORMAL).build();
} else {
captionLayout = new StaticLayout(currentCaption, Theme.chat_msgTextPaint, widthForCaption, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
updateCaptionSpoilers();
int lineCount = captionLayout.getLineCount();
if (lineCount > 0) {
if (fixPhotoWidth) {
captionWidth = 0;
for (int a = 0; a < lineCount; a++) {
captionWidth = (int) Math.max(captionWidth, Math.ceil(captionLayout.getLineWidth(a)));
if (captionLayout.getLineLeft(a) != 0) {
captionWidth = widthForCaption;
break;
}
}
if (captionWidth > widthForCaption) {
captionWidth = widthForCaption;
}
} else {
captionWidth = widthForCaption;
}
captionHeight = captionLayout.getHeight();
addedCaptionHeight = captionHeight + AndroidUtilities.dp(9);
if (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) {
additionHeight += addedCaptionHeight;
int widthToCheck = Math.max(captionWidth, photoWidth - AndroidUtilities.dp(10));
float lastLineWidth = captionLayout.getLineWidth(captionLayout.getLineCount() - 1) + captionLayout.getLineLeft(captionLayout.getLineCount() - 1);
if ((reactionsLayoutInBubble.isEmpty || reactionsLayoutInBubble.isSmall) && !shouldDrawTimeOnMedia() && widthToCheck + AndroidUtilities.dp(2) - lastLineWidth < timeWidthTotal + getExtraTimeX()) {
additionHeight += AndroidUtilities.dp(14);
addedCaptionHeight += AndroidUtilities.dp(14);
captionNewLine = 1;
}
} else {
captionLayout = null;
updateCaptionSpoilers();
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (!reactionsLayoutInBubble.isSmall) {
boolean useBackgroundWidth = backgroundWidth - AndroidUtilities.dp(24) > widthForCaption;
int maxWidth = Math.max(backgroundWidth - AndroidUtilities.dp(36), widthForCaption);
reactionsLayoutInBubble.measure(maxWidth);
if (!reactionsLayoutInBubble.isEmpty) {
if (shouldDrawTimeOnMedia()) {
reactionsLayoutInBubble.drawServiceShaderBackground = true;
}
int heightLocal = reactionsLayoutInBubble.height;
if (captionLayout == null) {
heightLocal += AndroidUtilities.dp(12);
heightLocal += AndroidUtilities.dp(4);
} else {
heightLocal += AndroidUtilities.dp(12);
reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(12);
}
reactionsLayoutInBubble.totalHeight = heightLocal;
additionHeight += reactionsLayoutInBubble.totalHeight;
if (!shouldDrawTimeOnMedia()) {
int widthToCheck = Math.min(maxWidth, reactionsLayoutInBubble.width + timeWidthTotal + getExtraTimeX() + AndroidUtilities.dp(2));
float lastLineWidth = reactionsLayoutInBubble.lastLineX;
if (!shouldDrawTimeOnMedia() && widthToCheck - lastLineWidth < timeWidthTotal + getExtraTimeX()) {
additionHeight += AndroidUtilities.dp(14);
reactionsLayoutInBubble.totalHeight += AndroidUtilities.dp(14);
reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(14);
captionNewLine = 1;
if (!useBackgroundWidth && captionWidth < reactionsLayoutInBubble.width) {
captionWidth = reactionsLayoutInBubble.width;
}
} else if (!useBackgroundWidth) {
if (reactionsLayoutInBubble.lastLineX + timeWidthTotal > captionWidth) {
captionWidth = reactionsLayoutInBubble.lastLineX + timeWidthTotal;
}
if (reactionsLayoutInBubble.width > captionWidth) {
captionWidth = reactionsLayoutInBubble.width;
}
}
}
}
}
int minWidth = (int) (Theme.chat_infoPaint.measureText("100%") + AndroidUtilities.dp(100));
if (currentMessagesGroup == null && (documentAttachType == DOCUMENT_ATTACH_TYPE_VIDEO || documentAttachType == DOCUMENT_ATTACH_TYPE_GIF) && photoWidth < minWidth) {
photoWidth = minWidth;
backgroundWidth = photoWidth + AndroidUtilities.dp(8);
if (!mediaBackground) {
backgroundWidth += AndroidUtilities.dp(9);
}
}
if (fixPhotoWidth && photoWidth < captionWidth + AndroidUtilities.dp(10)) {
photoWidth = captionWidth + AndroidUtilities.dp(10);
backgroundWidth = photoWidth + AndroidUtilities.dp(8);
if (!mediaBackground) {
backgroundWidth += AndroidUtilities.dp(9);
}
}
if (messageChanged || messageIdChanged || dataChanged) {
currentPhotoFilter = currentPhotoFilterThumb = String.format(Locale.US, "%d_%d", (int) (w / AndroidUtilities.density), (int) (h / AndroidUtilities.density));
if (messageObject.photoThumbs != null && messageObject.photoThumbs.size() > 1 || messageObject.type == MessageObject.TYPE_VIDEO || messageObject.type == 8 || messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
if (messageObject.needDrawBluredPreview()) {
currentPhotoFilter += "_b2";
currentPhotoFilterThumb += "_b2";
} else {
currentPhotoFilterThumb += "_b";
}
}
} else {
String filterNew = String.format(Locale.US, "%d_%d", (int) (w / AndroidUtilities.density), (int) (h / AndroidUtilities.density));
if (!messageObject.needDrawBluredPreview() && !filterNew.equals(currentPhotoFilter)) {
ImageLocation location = ImageLocation.getForObject(currentPhotoObject, photoParentObject);
if (location != null) {
String key = location.getKey(photoParentObject, null, false) + "@" + currentPhotoFilter;
if (ImageLoader.getInstance().isInMemCache(key, false)) {
currentPhotoObjectThumb = currentPhotoObject;
currentPhotoFilterThumb = currentPhotoFilter;
currentPhotoFilter = filterNew;
}
}
}
}
boolean noSize = false;
if (messageObject.type == MessageObject.TYPE_VIDEO || messageObject.type == 8 || messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
noSize = true;
}
if (currentPhotoObject != null && !noSize && currentPhotoObject.size == 0) {
currentPhotoObject.size = -1;
}
if (currentPhotoObjectThumb != null && !noSize && currentPhotoObjectThumb.size == 0) {
currentPhotoObjectThumb.size = -1;
}
if (SharedConfig.autoplayVideo && messageObject.type == MessageObject.TYPE_VIDEO && !messageObject.needDrawBluredPreview() && (currentMessageObject.mediaExists || messageObject.canStreamVideo() && DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject))) {
if (currentPosition != null) {
autoPlayingMedia = (currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) != 0 && (currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) != 0;
} else {
autoPlayingMedia = true;
}
}
if (autoPlayingMedia) {
photoImage.setAllowStartAnimation(true);
photoImage.startAnimation();
TLRPC.Document document = messageObject.getDocument();
if (currentMessageObject.videoEditedInfo != null && currentMessageObject.videoEditedInfo.canAutoPlaySourceVideo()) {
photoImage.setImage(ImageLocation.getForPath(currentMessageObject.videoEditedInfo.originalPath), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObjectThumb, document), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, messageObject.getDocument().size, null, messageObject, 0);
photoImage.setMediaStartEndTime(currentMessageObject.videoEditedInfo.startTime / 1000, currentMessageObject.videoEditedInfo.endTime / 1000);
} else {
if (!messageIdChanged && !dataChanged) {
photoImage.setCrossfadeWithOldImage(true);
}
photoImage.setImage(ImageLocation.getForDocument(document), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForDocument(currentPhotoObjectThumb, document), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, messageObject.getDocument().size, null, messageObject, 0);
}
} else if (messageObject.type == MessageObject.TYPE_PHOTO) {
if (messageObject.useCustomPhoto) {
photoImage.setImageBitmap(getResources().getDrawable(R.drawable.theme_preview_image));
} else {
if (currentPhotoObject != null) {
boolean photoExist = true;
String fileName = FileLoader.getAttachFileName(currentPhotoObject);
if (messageObject.mediaExists) {
DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this);
} else {
photoExist = false;
}
if (photoExist || !currentMessageObject.loadingCancelled && DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject) || FileLoader.getInstance(currentAccount).isLoadingFile(fileName)) {
photoImage.setImage(ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, currentPhotoObject.size, null, currentMessageObject, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else {
photoNotSet = true;
if (currentPhotoObjectThumb != null || currentPhotoObjectThumbStripped != null) {
photoImage.setImage(null, null, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, currentMessageObject, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
} else {
photoImage.setImageBitmap((Drawable) null);
}
}
} else {
photoImage.setImageBitmap((Drawable) null);
}
}
} else if (messageObject.type == 8 || messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
String fileName = FileLoader.getAttachFileName(messageObject.getDocument());
int localFile = 0;
if (messageObject.attachPathExists) {
DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this);
localFile = 1;
} else if (messageObject.mediaExists) {
localFile = 2;
}
boolean autoDownload = false;
TLRPC.Document document = messageObject.getDocument();
if (MessageObject.isGifDocument(document, messageObject.hasValidGroupId()) || messageObject.type == MessageObject.TYPE_ROUND_VIDEO) {
autoDownload = DownloadController.getInstance(currentAccount).canDownloadMedia(currentMessageObject);
}
TLRPC.VideoSize videoSize = MessageObject.getDocumentVideoThumb(document);
if (((MessageObject.isGifDocument(document, messageObject.hasValidGroupId()) && messageObject.videoEditedInfo == null) || (!messageObject.isSending() && !messageObject.isEditing())) && (localFile != 0 || FileLoader.getInstance(currentAccount).isLoadingFile(fileName) || autoDownload)) {
if (localFile != 1 && !messageObject.needDrawBluredPreview() && (localFile != 0 || messageObject.canStreamVideo() && autoDownload)) {
autoPlayingMedia = true;
if (!messageIdChanged) {
photoImage.setCrossfadeWithOldImage(true);
photoImage.setCrossfadeDuration(250);
}
if (localFile == 0 && videoSize != null && (currentPhotoObject == null || currentPhotoObjectThumb == null)) {
photoImage.setImage(ImageLocation.getForDocument(document), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForDocument(videoSize, documentAttach), null, ImageLocation.getForDocument(currentPhotoObject != null ? currentPhotoObject : currentPhotoObjectThumb, documentAttach), currentPhotoObject != null ? currentPhotoFilter : currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
} else {
if (isRoundVideo && !messageIdChanged && photoImage.hasStaticThumb()) {
photoImage.setImage(ImageLocation.getForDocument(document), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, null, null, photoImage.getStaticThumb(), document.size, null, messageObject, 0);
} else {
photoImage.setImage(ImageLocation.getForDocument(document), ImageLoader.AUTOPLAY_FILTER, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
}
}
} else if (localFile == 1) {
photoImage.setImage(ImageLocation.getForPath(messageObject.isSendError() ? null : messageObject.messageOwner.attachPath), null, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
} else {
if (videoSize != null && (currentPhotoObject == null || currentPhotoObjectThumb == null)) {
photoImage.setImage(ImageLocation.getForDocument(document), null, ImageLocation.getForDocument(videoSize, documentAttach), null, ImageLocation.getForDocument(currentPhotoObject != null ? currentPhotoObject : currentPhotoObjectThumb, documentAttach), currentPhotoObject != null ? currentPhotoFilter : currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
} else {
photoImage.setImage(ImageLocation.getForDocument(document), null, ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, document.size, null, messageObject, 0);
}
}
} else {
if (messageObject.videoEditedInfo != null && messageObject.type == MessageObject.TYPE_ROUND_VIDEO && !currentMessageObject.needDrawBluredPreview()) {
photoImage.setImage(ImageLocation.getForPath(messageObject.videoEditedInfo.originalPath), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
photoImage.setMediaStartEndTime(currentMessageObject.videoEditedInfo.startTime / 1000, currentMessageObject.videoEditedInfo.endTime / 1000);
} else {
if (!messageIdChanged && !currentMessageObject.needDrawBluredPreview()) {
photoImage.setCrossfadeWithOldImage(true);
photoImage.setCrossfadeDuration(250);
}
photoImage.setImage(ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, 0);
}
}
} else {
if (messageObject.videoEditedInfo != null && messageObject.type == MessageObject.TYPE_ROUND_VIDEO && !currentMessageObject.needDrawBluredPreview()) {
photoImage.setImage(ImageLocation.getForPath(messageObject.videoEditedInfo.originalPath), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
photoImage.setMediaStartEndTime(currentMessageObject.videoEditedInfo.startTime / 1000, currentMessageObject.videoEditedInfo.endTime / 1000);
} else {
if (!messageIdChanged && !currentMessageObject.needDrawBluredPreview()) {
photoImage.setCrossfadeWithOldImage(true);
photoImage.setCrossfadeDuration(250);
}
photoImage.setImage(ImageLocation.getForObject(currentPhotoObject, photoParentObject), currentPhotoFilter, ImageLocation.getForObject(currentPhotoObjectThumb, photoParentObject), currentPhotoFilterThumb, currentPhotoObjectThumbStripped, 0, null, messageObject, currentMessageObject.shouldEncryptPhotoOrVideo() ? 2 : 0);
}
}
}
setMessageObjectInternal(messageObject);
if (drawForwardedName && messageObject.needDrawForwarded() && (currentPosition == null || currentPosition.minY == 0)) {
if (messageObject.type != 5) {
namesOffset += AndroidUtilities.dp(5);
}
} else if (drawNameLayout && (messageObject.getReplyMsgId() == 0 || isThreadChat && messageObject.getReplyTopMsgId() == 0)) {
namesOffset += AndroidUtilities.dp(7);
}
totalHeight = photoHeight + AndroidUtilities.dp(14) + namesOffset + additionHeight;
if (currentPosition != null && (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0 && !currentMessageObject.isDocument()) {
totalHeight -= AndroidUtilities.dp(3);
}
if (currentMessageObject.isDice()) {
totalHeight += AndroidUtilities.dp(21);
additionalTimeOffsetY = AndroidUtilities.dp(21);
}
int additionalTop = 0;
if (currentPosition != null && !currentMessageObject.isDocument()) {
photoWidth += getAdditionalWidthForPosition(currentPosition);
if ((currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0) {
photoHeight += AndroidUtilities.dp(4);
additionalTop -= AndroidUtilities.dp(4);
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
photoHeight += AndroidUtilities.dp(1);
}
}
if (drawPinnedTop) {
namesOffset -= AndroidUtilities.dp(1);
}
int y;
if (namesOffset > 0) {
y = AndroidUtilities.dp(7);
totalHeight -= AndroidUtilities.dp(2);
} else {
y = AndroidUtilities.dp(5);
totalHeight -= AndroidUtilities.dp(4);
}
if (currentPosition != null && currentMessagesGroup.isDocuments && currentMessagesGroup.messages.size() > 1) {
if ((currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0) {
totalHeight -= AndroidUtilities.dp(drawPhotoImage ? 3 : 6);
mediaOffsetY -= AndroidUtilities.dp(drawPhotoImage ? 3 : 6);
y -= AndroidUtilities.dp(drawPhotoImage ? 3 : 6);
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
totalHeight -= AndroidUtilities.dp(drawPhotoImage ? 3 : 6);
}
}
photoImage.setImageCoords(0, y + namesOffset + additionalTop, photoWidth, photoHeight);
invalidate();
}
//
if ((currentPosition == null || currentMessageObject.isMusic() || currentMessageObject.isDocument()) && !messageObject.isAnyKindOfSticker() && addedCaptionHeight == 0) {
if (!messageObject.isRestrictedMessage && captionLayout == null && messageObject.caption != null) {
try {
currentCaption = messageObject.caption;
int width = backgroundWidth - AndroidUtilities.dp(31);
int widthForCaption = width - AndroidUtilities.dp(10) - getExtraTextX() * 2;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
captionLayout = StaticLayout.Builder.obtain(messageObject.caption, 0, messageObject.caption.length(), Theme.chat_msgTextPaint, widthForCaption).setBreakStrategy(StaticLayout.BREAK_STRATEGY_HIGH_QUALITY).setHyphenationFrequency(StaticLayout.HYPHENATION_FREQUENCY_NONE).setAlignment(Layout.Alignment.ALIGN_NORMAL).build();
} else {
captionLayout = new StaticLayout(messageObject.caption, Theme.chat_msgTextPaint, widthForCaption, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
updateCaptionSpoilers();
} catch (Exception e) {
FileLog.e(e);
}
}
if (captionLayout != null) {
try {
int width = backgroundWidth - AndroidUtilities.dp(31);
if (captionLayout != null && captionLayout.getLineCount() > 0) {
captionWidth = width;
captionHeight = captionLayout.getHeight();
totalHeight += captionHeight + AndroidUtilities.dp(9);
if ((reactionsLayoutInBubble.isEmpty || reactionsLayoutInBubble.isSmall) && (currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0)) {
int timeWidthTotal = timeWidth + (messageObject.isOutOwner() ? AndroidUtilities.dp(20) : 0) + getExtraTimeX();
float lastLineWidth = captionLayout.getLineWidth(captionLayout.getLineCount() - 1) + captionLayout.getLineLeft(captionLayout.getLineCount() - 1);
if (width - AndroidUtilities.dp(8) - lastLineWidth < timeWidthTotal) {
totalHeight += AndroidUtilities.dp(14);
captionHeight += AndroidUtilities.dp(14);
captionNewLine = 2;
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
if ((currentPosition == null || (currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) != 0) && captionLayout == null && widthBeforeNewTimeLine != -1 && availableTimeWidth - widthBeforeNewTimeLine < timeWidth) {
totalHeight += AndroidUtilities.dp(14);
}
if (currentMessageObject.eventId != 0 && !currentMessageObject.isMediaEmpty() && currentMessageObject.messageOwner.media.webpage != null) {
int linkPreviewMaxWidth = backgroundWidth - AndroidUtilities.dp(41);
hasOldCaptionPreview = true;
linkPreviewHeight = 0;
TLRPC.WebPage webPage = currentMessageObject.messageOwner.media.webpage;
try {
int width = siteNameWidth = (int) Math.ceil(Theme.chat_replyNamePaint.measureText(webPage.site_name) + 1);
siteNameLayout = new StaticLayout(webPage.site_name, Theme.chat_replyNamePaint, Math.min(width, linkPreviewMaxWidth), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
siteNameRtl = siteNameLayout.getLineLeft(0) != 0;
int height = siteNameLayout.getLineBottom(siteNameLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
} catch (Exception e) {
FileLog.e(e);
}
try {
descriptionX = 0;
if (linkPreviewHeight != 0) {
totalHeight += AndroidUtilities.dp(2);
}
descriptionLayout = StaticLayoutEx.createStaticLayout(webPage.description, Theme.chat_replyTextPaint, linkPreviewMaxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, AndroidUtilities.dp(1), false, TextUtils.TruncateAt.END, linkPreviewMaxWidth, 6);
int height = descriptionLayout.getLineBottom(descriptionLayout.getLineCount() - 1);
linkPreviewHeight += height;
totalHeight += height;
boolean hasNonRtl = false;
for (int a = 0; a < descriptionLayout.getLineCount(); a++) {
int lineLeft = (int) Math.ceil(descriptionLayout.getLineLeft(a));
if (lineLeft != 0) {
if (descriptionX == 0) {
descriptionX = -lineLeft;
} else {
descriptionX = Math.max(descriptionX, -lineLeft);
}
} else {
hasNonRtl = true;
}
}
if (hasNonRtl) {
descriptionX = 0;
}
} catch (Exception e) {
FileLog.e(e);
}
if (messageObject.type == MessageObject.TYPE_PHOTO || messageObject.type == MessageObject.TYPE_VIDEO) {
totalHeight += AndroidUtilities.dp(6);
}
totalHeight += AndroidUtilities.dp(17);
if (captionNewLine != 0) {
totalHeight -= AndroidUtilities.dp(14);
if (captionNewLine == 2) {
captionHeight -= AndroidUtilities.dp(14);
}
}
}
if (messageObject.isSponsored()) {
drawInstantView = true;
if (messageObject.sponsoredChannelPost != 0) {
drawInstantViewType = 12;
} else {
drawInstantViewType = 1;
}
long id = MessageObject.getPeerId(messageObject.messageOwner.from_id);
if (id > 0) {
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(id);
if (user != null && user.bot) {
drawInstantViewType = 10;
}
}
createInstantViewButton();
}
botButtons.clear();
if (messageIdChanged) {
botButtonsByData.clear();
botButtonsByPosition.clear();
botButtonsLayout = null;
}
if (!messageObject.isRestrictedMessage && currentPosition == null && (messageObject.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup)) {
int rows;
if (messageObject.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) {
rows = messageObject.messageOwner.reply_markup.rows.size();
} else {
rows = 1;
}
substractBackgroundHeight = keyboardHeight = AndroidUtilities.dp(44 + 4) * rows + AndroidUtilities.dp(1);
widthForButtons = backgroundWidth - AndroidUtilities.dp(mediaBackground ? 0 : 9);
boolean fullWidth = false;
if (messageObject.wantedBotKeyboardWidth > widthForButtons) {
int maxButtonWidth = -AndroidUtilities.dp(drawAvatar ? 62 : 10);
if (AndroidUtilities.isTablet()) {
maxButtonWidth += AndroidUtilities.getMinTabletSide();
} else {
maxButtonWidth += Math.min(getParentWidth(), AndroidUtilities.displaySize.y) - AndroidUtilities.dp(5);
}
widthForButtons = Math.max(backgroundWidth, Math.min(messageObject.wantedBotKeyboardWidth, maxButtonWidth));
}
int maxButtonsWidth = 0;
HashMap<String, BotButton> oldByData = new HashMap<>(botButtonsByData);
HashMap<String, BotButton> oldByPosition;
if (messageObject.botButtonsLayout != null && botButtonsLayout != null && botButtonsLayout.equals(messageObject.botButtonsLayout.toString())) {
oldByPosition = new HashMap<>(botButtonsByPosition);
} else {
if (messageObject.botButtonsLayout != null) {
botButtonsLayout = messageObject.botButtonsLayout.toString();
}
oldByPosition = null;
}
botButtonsByData.clear();
if (messageObject.messageOwner.reply_markup instanceof TLRPC.TL_replyInlineMarkup) {
for (int a = 0; a < rows; a++) {
TLRPC.TL_keyboardButtonRow row = messageObject.messageOwner.reply_markup.rows.get(a);
int buttonsCount = row.buttons.size();
if (buttonsCount == 0) {
continue;
}
int buttonWidth = (widthForButtons - AndroidUtilities.dp(5) * (buttonsCount - 1) - AndroidUtilities.dp(2)) / buttonsCount;
for (int b = 0; b < row.buttons.size(); b++) {
BotButton botButton = new BotButton();
botButton.button = row.buttons.get(b);
String key = Utilities.bytesToHex(botButton.button.data);
String position = a + "" + b;
BotButton oldButton;
if (oldByPosition != null) {
oldButton = oldByPosition.get(position);
} else {
oldButton = oldByData.get(key);
}
if (oldButton != null) {
botButton.progressAlpha = oldButton.progressAlpha;
botButton.angle = oldButton.angle;
botButton.lastUpdateTime = oldButton.lastUpdateTime;
} else {
botButton.lastUpdateTime = System.currentTimeMillis();
}
botButtonsByData.put(key, botButton);
botButtonsByPosition.put(position, botButton);
botButton.x = b * (buttonWidth + AndroidUtilities.dp(5));
botButton.y = a * AndroidUtilities.dp(44 + 4) + AndroidUtilities.dp(5);
botButton.width = buttonWidth;
botButton.height = AndroidUtilities.dp(44);
CharSequence buttonText;
TextPaint botButtonPaint = (TextPaint) getThemedPaint(Theme.key_paint_chatBotButton);
if (botButton.button instanceof TLRPC.TL_keyboardButtonBuy && (messageObject.messageOwner.media.flags & 4) != 0) {
buttonText = LocaleController.getString("PaymentReceipt", R.string.PaymentReceipt);
} else {
buttonText = Emoji.replaceEmoji(botButton.button.text, botButtonPaint.getFontMetricsInt(), AndroidUtilities.dp(15), false);
buttonText = TextUtils.ellipsize(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), TextUtils.TruncateAt.END);
}
botButton.title = new StaticLayout(buttonText, botButtonPaint, buttonWidth - AndroidUtilities.dp(10), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
botButtons.add(botButton);
if (b == row.buttons.size() - 1) {
maxButtonsWidth = Math.max(maxButtonsWidth, botButton.x + botButton.width);
}
}
}
}
widthForButtons = maxButtonsWidth;
} else {
substractBackgroundHeight = 0;
keyboardHeight = 0;
}
if (drawCommentButton) {
totalHeight += AndroidUtilities.dp(shouldDrawTimeOnMedia() ? 41.3f : 43);
createSelectorDrawable(1);
}
if (drawPinnedBottom && drawPinnedTop) {
totalHeight -= AndroidUtilities.dp(2);
} else if (drawPinnedBottom) {
totalHeight -= AndroidUtilities.dp(1);
} else if (drawPinnedTop && pinnedBottom && currentPosition != null && currentPosition.siblingHeights == null) {
totalHeight -= AndroidUtilities.dp(1);
}
if (messageObject.isAnyKindOfSticker() && totalHeight < AndroidUtilities.dp(70)) {
additionalTimeOffsetY = AndroidUtilities.dp(70) - totalHeight;
totalHeight += additionalTimeOffsetY;
} else if (messageObject.isAnimatedEmoji()) {
additionalTimeOffsetY = AndroidUtilities.dp(16);
totalHeight += AndroidUtilities.dp(16);
}
if (!drawPhotoImage) {
photoImage.setImageBitmap((Drawable) null);
}
if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) {
if (MessageObject.isDocumentHasThumb(documentAttach)) {
TLRPC.PhotoSize thumb = FileLoader.getClosestPhotoSizeWithSize(documentAttach.thumbs, 90);
radialProgress.setImageOverlay(thumb, documentAttach, messageObject);
} else {
String artworkUrl = messageObject.getArtworkUrl(true);
if (!TextUtils.isEmpty(artworkUrl)) {
radialProgress.setImageOverlay(artworkUrl);
} else {
radialProgress.setImageOverlay(null, null, null);
}
}
} else {
radialProgress.setImageOverlay(null, null, null);
}
if (canChangeRadius) {
int tl, tr, bl, br;
int minRad = AndroidUtilities.dp(4);
int rad;
if (SharedConfig.bubbleRadius > 2) {
rad = AndroidUtilities.dp(SharedConfig.bubbleRadius - 2);
} else {
rad = AndroidUtilities.dp(SharedConfig.bubbleRadius);
}
int nearRad = Math.min(AndroidUtilities.dp(3), rad);
tl = tr = bl = br = rad;
if (minRad > tl) {
minRad = tl;
}
if (hasLinkPreview || hasGamePreview || hasInvoicePreview) {
tl = tr = bl = br = minRad;
}
if (forwardedNameLayout[0] != null || replyNameLayout != null || drawNameLayout) {
tl = tr = minRad;
}
if (captionLayout != null || drawCommentButton) {
bl = br = minRad;
}
if (documentAttachType == DOCUMENT_ATTACH_TYPE_DOCUMENT) {
tr = br = minRad;
}
if (currentPosition != null && currentMessagesGroup != null) {
if ((currentPosition.flags & MessageObject.POSITION_FLAG_RIGHT) == 0) {
tr = br = minRad;
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_LEFT) == 0) {
tl = bl = minRad;
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_BOTTOM) == 0) {
bl = br = minRad;
}
if ((currentPosition.flags & MessageObject.POSITION_FLAG_TOP) == 0) {
tl = tr = minRad;
}
}
if (pinnedTop) {
if (currentMessageObject.isOutOwner()) {
tr = nearRad;
} else {
tl = nearRad;
}
}
if (pinnedBottom) {
if (currentMessageObject.isOutOwner()) {
br = nearRad;
} else {
bl = nearRad;
}
}
if (!mediaBackground && !currentMessageObject.isOutOwner()) {
bl = nearRad;
}
photoImage.setRoundRadius(tl, tr, br, bl);
}
}
if (messageIdChanged) {
currentUrl = null;
currentWebFile = null;
lastWebFile = null;
loadingProgressLayout = null;
animatingLoadingProgressProgress = 0;
lastLoadingSizeTotal = 0;
selectedBackgroundProgress = 0f;
if (statusDrawableAnimator != null) {
statusDrawableAnimator.removeAllListeners();
statusDrawableAnimator.cancel();
}
transitionParams.lastStatusDrawableParams = -1;
statusDrawableAnimationInProgress = false;
if (documentAttachType == DOCUMENT_ATTACH_TYPE_MUSIC) {
boolean showSeekbar = MediaController.getInstance().isPlayingMessage(currentMessageObject);
toSeekBarProgress = showSeekbar ? 1f : 0f;
}
seekBarWaveform.setProgress(0);
}
updateWaveform();
updateButtonState(false, dataChanged && !messageObject.cancelEditing, true);
if (!currentMessageObject.loadingCancelled && buttonState == 2 && documentAttachType == DOCUMENT_ATTACH_TYPE_AUDIO && DownloadController.getInstance(currentAccount).canDownloadMedia(messageObject)) {
FileLoader.getInstance(currentAccount).loadFile(documentAttach, currentMessageObject, 1, 0);
buttonState = 4;
radialProgress.setIcon(getIconForCurrentState(), false, false);
}
if (delegate != null && delegate.getTextSelectionHelper() != null && !messageIdChanged && messageChanged && messageObject != null) {
delegate.getTextSelectionHelper().checkDataChanged(messageObject);
}
accessibilityVirtualViewBounds.clear();
transitionParams.updatePhotoImageX = true;
updateFlagSecure();
}
Aggregations