use of org.telegram.ui.ActionBar.ActionBarMenuItem in project Telegram-FOSS by Telegram-FOSS-Team.
the class ArticleViewer method setParentActivity.
public void setParentActivity(Activity activity, BaseFragment fragment) {
parentFragment = fragment;
currentAccount = UserConfig.selectedAccount;
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingProgressDidChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
if (parentActivity == activity) {
updatePaintColors();
refreshThemeColors();
return;
}
parentActivity = activity;
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("articles", Activity.MODE_PRIVATE);
selectedFont = sharedPreferences.getInt("font_type", 0);
createPaint(false);
backgroundPaint = new Paint();
layerShadowDrawable = activity.getResources().getDrawable(R.drawable.layer_shadow);
slideDotDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_small);
slideDotBigDrawable = activity.getResources().getDrawable(R.drawable.slide_dot_big);
scrimPaint = new Paint();
windowView = new WindowView(activity);
windowView.setWillNotDraw(false);
windowView.setClipChildren(true);
windowView.setFocusable(false);
containerView = new FrameLayout(activity) {
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
if (windowView.movingPage) {
int width = getMeasuredWidth();
int translationX = (int) listView[0].getTranslationX();
int clipLeft = 0;
int clipRight = width;
if (child == listView[1]) {
clipRight = translationX;
} else if (child == listView[0]) {
clipLeft = translationX;
}
final int restoreCount = canvas.save();
canvas.clipRect(clipLeft, 0, clipRight, getHeight());
final boolean result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(restoreCount);
if (translationX != 0) {
if (child == listView[0]) {
final float alpha = Math.max(0, Math.min((width - translationX) / (float) AndroidUtilities.dp(20), 1.0f));
layerShadowDrawable.setBounds(translationX - layerShadowDrawable.getIntrinsicWidth(), child.getTop(), translationX, child.getBottom());
layerShadowDrawable.setAlpha((int) (0xff * alpha));
layerShadowDrawable.draw(canvas);
} else if (child == listView[1]) {
float opacity = Math.min(0.8f, (width - translationX) / (float) width);
if (opacity < 0) {
opacity = 0;
}
scrimPaint.setColor((int) (((0x99000000 & 0xff000000) >>> 24) * opacity) << 24);
canvas.drawRect(clipLeft, 0, clipRight, getHeight(), scrimPaint);
}
}
return result;
} else {
return super.drawChild(canvas, child, drawingTime);
}
}
};
windowView.addView(containerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
// containerView.setFitsSystemWindows(true);
if (Build.VERSION.SDK_INT >= 21) {
windowView.setFitsSystemWindows(true);
containerView.setOnApplyWindowInsetsListener((v, insets) -> {
if (Build.VERSION.SDK_INT >= 30) {
return WindowInsets.CONSUMED;
} else {
return insets.consumeSystemWindowInsets();
}
});
}
fullscreenVideoContainer = new FrameLayout(activity);
fullscreenVideoContainer.setBackgroundColor(0xff000000);
fullscreenVideoContainer.setVisibility(View.INVISIBLE);
windowView.addView(fullscreenVideoContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
fullscreenAspectRatioView = new AspectRatioFrameLayout(activity);
fullscreenAspectRatioView.setVisibility(View.GONE);
fullscreenVideoContainer.addView(fullscreenAspectRatioView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));
fullscreenTextureView = new TextureView(activity);
listView = new RecyclerListView[2];
adapter = new WebpageAdapter[2];
layoutManager = new LinearLayoutManager[2];
for (int i = 0; i < listView.length; i++) {
WebpageAdapter webpageAdapter = adapter[i] = new WebpageAdapter(parentActivity);
listView[i] = new RecyclerListView(activity) {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int count = getChildCount();
for (int a = 0; a < count; a++) {
View child = getChildAt(a);
if (child.getTag() instanceof Integer) {
Integer tag = (Integer) child.getTag();
if (tag == 90) {
int bottom = child.getBottom();
if (bottom < getMeasuredHeight()) {
int height = getMeasuredHeight();
child.layout(0, height - child.getMeasuredHeight(), child.getMeasuredWidth(), height);
break;
}
}
}
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
pressedLink = null;
pressedLinkOwnerLayout = null;
pressedLinkOwnerView = null;
} else if (pressedLinkOwnerLayout != null && pressedLink != null && e.getAction() == MotionEvent.ACTION_UP) {
checkLayoutForLinks(webpageAdapter, e, pressedLinkOwnerView, pressedLinkOwnerLayout, 0, 0);
}
return super.onInterceptTouchEvent(e);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (pressedLinkOwnerLayout != null && pressedLink == null && (popupWindow == null || !popupWindow.isShowing()) && (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL)) {
pressedLink = null;
pressedLinkOwnerLayout = null;
pressedLinkOwnerView = null;
}
return super.onTouchEvent(e);
}
@Override
public void setTranslationX(float translationX) {
super.setTranslationX(translationX);
if (windowView.movingPage) {
containerView.invalidate();
float progress = translationX / getMeasuredWidth();
setCurrentHeaderHeight((int) (windowView.startMovingHeaderHeight + (AndroidUtilities.dp(56) - windowView.startMovingHeaderHeight) * progress));
}
}
};
((DefaultItemAnimator) listView[i].getItemAnimator()).setDelayAnimations(false);
listView[i].setLayoutManager(layoutManager[i] = new LinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false));
listView[i].setAdapter(webpageAdapter);
listView[i].setClipToPadding(false);
listView[i].setVisibility(i == 0 ? View.VISIBLE : View.GONE);
listView[i].setPadding(0, AndroidUtilities.dp(56), 0, 0);
listView[i].setTopGlowOffset(AndroidUtilities.dp(56));
containerView.addView(listView[i], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
listView[i].setOnItemLongClickListener((view, position) -> {
if (view instanceof BlockRelatedArticlesCell) {
BlockRelatedArticlesCell cell = (BlockRelatedArticlesCell) view;
showCopyPopup(cell.currentBlock.parent.articles.get(cell.currentBlock.num).url);
return true;
}
return false;
});
listView[i].setOnItemClickListener((view, position, x, y) -> {
if (textSelectionHelper != null) {
if (textSelectionHelper.isSelectionMode()) {
textSelectionHelper.clear();
return;
}
textSelectionHelper.clear();
}
if (view instanceof ReportCell && webpageAdapter.currentPage != null) {
ReportCell cell = (ReportCell) view;
if (previewsReqId != 0 || cell.hasViews && x < view.getMeasuredWidth() / 2) {
return;
}
TLObject object = MessagesController.getInstance(currentAccount).getUserOrChat("previews");
if (object instanceof TLRPC.TL_user) {
openPreviewsChat((TLRPC.User) object, webpageAdapter.currentPage.id);
} else {
final int currentAccount = UserConfig.selectedAccount;
final long pageId = webpageAdapter.currentPage.id;
showProgressView(true, true);
TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
req.username = "previews";
previewsReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (previewsReqId == 0) {
return;
}
previewsReqId = 0;
showProgressView(true, false);
if (response != null) {
TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
MessagesController.getInstance(currentAccount).putUsers(res.users, false);
MessagesStorage.getInstance(currentAccount).putUsersAndChats(res.users, res.chats, false, true);
if (!res.users.isEmpty()) {
openPreviewsChat(res.users.get(0), pageId);
}
}
}));
}
} else if (position >= 0 && position < webpageAdapter.localBlocks.size()) {
TLRPC.PageBlock pageBlock = webpageAdapter.localBlocks.get(position);
TLRPC.PageBlock originalBlock = pageBlock;
pageBlock = getLastNonListPageBlock(pageBlock);
if (pageBlock instanceof TL_pageBlockDetailsChild) {
TL_pageBlockDetailsChild detailsChild = (TL_pageBlockDetailsChild) pageBlock;
pageBlock = detailsChild.block;
}
if (pageBlock instanceof TLRPC.TL_pageBlockChannel) {
TLRPC.TL_pageBlockChannel pageBlockChannel = (TLRPC.TL_pageBlockChannel) pageBlock;
MessagesController.getInstance(currentAccount).openByUserName(pageBlockChannel.channel.username, parentFragment, 2);
close(false, true);
} else if (pageBlock instanceof TL_pageBlockRelatedArticlesChild) {
TL_pageBlockRelatedArticlesChild pageBlockRelatedArticlesChild = (TL_pageBlockRelatedArticlesChild) pageBlock;
openWebpageUrl(pageBlockRelatedArticlesChild.parent.articles.get(pageBlockRelatedArticlesChild.num).url, null);
} else if (pageBlock instanceof TLRPC.TL_pageBlockDetails) {
view = getLastNonListCell(view);
if (!(view instanceof BlockDetailsCell)) {
return;
}
pressedLinkOwnerLayout = null;
pressedLinkOwnerView = null;
int index = webpageAdapter.blocks.indexOf(originalBlock);
if (index < 0) {
return;
}
TLRPC.TL_pageBlockDetails pageBlockDetails = (TLRPC.TL_pageBlockDetails) pageBlock;
pageBlockDetails.open = !pageBlockDetails.open;
int oldCount = webpageAdapter.getItemCount();
webpageAdapter.updateRows();
int newCount = webpageAdapter.getItemCount();
int changeCount = Math.abs(newCount - oldCount);
BlockDetailsCell cell = (BlockDetailsCell) view;
cell.arrow.setAnimationProgressAnimated(pageBlockDetails.open ? 0.0f : 1.0f);
cell.invalidate();
if (changeCount != 0) {
if (pageBlockDetails.open) {
webpageAdapter.notifyItemRangeInserted(position + 1, changeCount);
} else {
webpageAdapter.notifyItemRangeRemoved(position + 1, changeCount);
}
}
}
}
});
listView[i].setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
textSelectionHelper.stopScrolling();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (recyclerView.getChildCount() == 0) {
return;
}
textSelectionHelper.onParentScrolled();
headerView.invalidate();
checkScroll(dy);
}
});
}
headerPaint.setColor(0xff000000);
statusBarPaint.setColor(0xff000000);
headerProgressPaint.setColor(0xff242426);
headerView = new FrameLayout(activity) {
@Override
protected void onDraw(Canvas canvas) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
canvas.drawRect(0, 0, width, height, headerPaint);
if (layoutManager == null) {
return;
}
int first = layoutManager[0].findFirstVisibleItemPosition();
int last = layoutManager[0].findLastVisibleItemPosition();
int count = layoutManager[0].getItemCount();
View view;
if (last >= count - 2) {
view = layoutManager[0].findViewByPosition(count - 2);
} else {
view = layoutManager[0].findViewByPosition(first);
}
if (view == null) {
return;
}
float itemProgress = width / (float) (count - 1);
int childCount = layoutManager[0].getChildCount();
float viewHeight = view.getMeasuredHeight();
float viewProgress;
if (last >= count - 2) {
viewProgress = (count - 2 - first) * itemProgress * (listView[0].getMeasuredHeight() - view.getTop()) / viewHeight;
} else {
viewProgress = itemProgress * (1.0f - (Math.min(0, view.getTop() - listView[0].getPaddingTop()) + viewHeight) / viewHeight);
}
float progress = first * itemProgress + viewProgress;
canvas.drawRect(0, 0, progress, height, headerProgressPaint);
}
};
headerView.setWillNotDraw(false);
containerView.addView(headerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
headerView.setOnClickListener(v -> listView[0].smoothScrollToPosition(0));
titleTextView = new SimpleTextView(activity);
titleTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
titleTextView.setTextSize(20);
titleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleTextView.setTextColor(0xffb3b3b3);
titleTextView.setPivotX(0.0f);
titleTextView.setPivotY(AndroidUtilities.dp(28));
headerView.addView(titleTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56, Gravity.LEFT | Gravity.TOP, 72, 0, 48 * 2, 0));
lineProgressView = new LineProgressView(activity);
lineProgressView.setProgressColor(0xffffffff);
lineProgressView.setPivotX(0.0f);
lineProgressView.setPivotY(AndroidUtilities.dp(2));
headerView.addView(lineProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 2, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 1));
lineProgressTickRunnable = () -> {
float progressLeft = 0.7f - lineProgressView.getCurrentProgress();
if (progressLeft > 0.0f) {
float tick;
if (progressLeft < 0.25f) {
tick = 0.01f;
} else {
tick = 0.02f;
}
lineProgressView.setProgress(lineProgressView.getCurrentProgress() + tick, true);
AndroidUtilities.runOnUIThread(lineProgressTickRunnable, 100);
}
};
menuContainer = new FrameLayout(activity);
headerView.addView(menuContainer, LayoutHelper.createFrame(48, 56, Gravity.TOP | Gravity.RIGHT));
searchShadow = new View(activity);
searchShadow.setBackgroundResource(R.drawable.header_shadow);
searchShadow.setAlpha(0.0f);
containerView.addView(searchShadow, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.TOP, 0, 56, 0, 0));
searchContainer = new FrameLayout(parentActivity);
searchContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
searchContainer.setVisibility(View.INVISIBLE);
if (Build.VERSION.SDK_INT < 21) {
searchContainer.setAlpha(0.0f);
}
headerView.addView(searchContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 56));
searchField = new EditTextBoldCursor(parentActivity) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (!AndroidUtilities.showKeyboard(this)) {
clearFocus();
requestFocus();
}
}
return super.onTouchEvent(event);
}
};
searchField.setCursorWidth(1.5f);
searchField.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
searchField.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
searchField.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
searchField.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
searchField.setSingleLine(true);
searchField.setHint(LocaleController.getString("Search", R.string.Search));
searchField.setBackgroundResource(0);
searchField.setPadding(0, 0, 0, 0);
int inputType = searchField.getInputType() | EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
searchField.setInputType(inputType);
if (Build.VERSION.SDK_INT < 23) {
searchField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
}
searchField.setOnEditorActionListener((v, actionId, event) -> {
if (event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
AndroidUtilities.hideKeyboard(searchField);
}
return false;
});
searchField.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (ignoreOnTextChange) {
ignoreOnTextChange = false;
return;
}
processSearch(s.toString().toLowerCase());
if (clearButton != null) {
if (TextUtils.isEmpty(s)) {
if (clearButton.getTag() != null) {
clearButton.setTag(null);
clearButton.clearAnimation();
if (animateClear) {
clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(0.0f).setDuration(180).scaleY(0.0f).scaleX(0.0f).rotation(45).withEndAction(() -> clearButton.setVisibility(View.INVISIBLE)).start();
} else {
clearButton.setAlpha(0.0f);
clearButton.setRotation(45);
clearButton.setScaleX(0.0f);
clearButton.setScaleY(0.0f);
clearButton.setVisibility(View.INVISIBLE);
animateClear = true;
}
}
} else {
if (clearButton.getTag() == null) {
clearButton.setTag(1);
clearButton.clearAnimation();
clearButton.setVisibility(View.VISIBLE);
if (animateClear) {
clearButton.animate().setInterpolator(new DecelerateInterpolator()).alpha(1.0f).setDuration(180).scaleY(1.0f).scaleX(1.0f).rotation(0).start();
} else {
clearButton.setAlpha(1.0f);
clearButton.setRotation(0);
clearButton.setScaleX(1.0f);
clearButton.setScaleY(1.0f);
animateClear = true;
}
}
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
searchField.setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_SEARCH);
searchField.setTextIsSelectable(false);
searchContainer.addView(searchField, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 36, Gravity.CENTER_VERTICAL, 72, 0, 48, 0));
clearButton = new ImageView(parentActivity) {
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
clearAnimation();
if (getTag() == null) {
clearButton.setVisibility(INVISIBLE);
clearButton.setAlpha(0.0f);
clearButton.setRotation(45);
clearButton.setScaleX(0.0f);
clearButton.setScaleY(0.0f);
} else {
clearButton.setAlpha(1.0f);
clearButton.setRotation(0);
clearButton.setScaleX(1.0f);
clearButton.setScaleY(1.0f);
}
}
};
clearButton.setImageDrawable(new CloseProgressDrawable2());
clearButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
clearButton.setScaleType(ImageView.ScaleType.CENTER);
clearButton.setAlpha(0.0f);
clearButton.setRotation(45);
clearButton.setScaleX(0.0f);
clearButton.setScaleY(0.0f);
clearButton.setOnClickListener(v -> {
if (searchField.length() != 0) {
searchField.setText("");
}
searchField.requestFocus();
AndroidUtilities.showKeyboard(searchField);
});
clearButton.setContentDescription(LocaleController.getString("ClearButton", R.string.ClearButton));
searchContainer.addView(clearButton, LayoutHelper.createFrame(48, LayoutHelper.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT));
backButton = new ImageView(activity);
backButton.setScaleType(ImageView.ScaleType.CENTER);
backDrawable = new BackDrawable(false);
backDrawable.setAnimationTime(200.0f);
backDrawable.setColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
backDrawable.setRotatedColor(0xffb3b3b3);
backDrawable.setRotation(1.0f, false);
backButton.setImageDrawable(backDrawable);
backButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
headerView.addView(backButton, LayoutHelper.createFrame(54, 56));
backButton.setOnClickListener(v -> {
/*if (collapsed) {
uncollapse();
} else {
collapse();
}*/
if (searchContainer.getTag() != null) {
showSearch(false);
} else {
close(true, true);
}
});
backButton.setContentDescription(LocaleController.getString("AccDescrGoBack", R.string.AccDescrGoBack));
menuButton = new ActionBarMenuItem(parentActivity, null, Theme.ACTION_BAR_WHITE_SELECTOR_COLOR, 0xffb3b3b3) {
@Override
public void toggleSubMenu() {
super.toggleSubMenu();
listView[0].stopScroll();
checkScrollAnimated();
}
};
menuButton.setLayoutInScreen(true);
menuButton.setDuplicateParentStateEnabled(false);
menuButton.setClickable(true);
menuButton.setIcon(R.drawable.ic_ab_other);
menuButton.addSubItem(search_item, R.drawable.msg_search, LocaleController.getString("Search", R.string.Search));
menuButton.addSubItem(share_item, R.drawable.msg_share, LocaleController.getString("ShareFile", R.string.ShareFile));
menuButton.addSubItem(open_item, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
menuButton.addSubItem(settings_item, R.drawable.menu_settings, LocaleController.getString("Settings", R.string.Settings));
menuButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.ACTION_BAR_WHITE_SELECTOR_COLOR));
menuButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
menuContainer.addView(menuButton, LayoutHelper.createFrame(48, 56));
progressView = new ContextProgressView(activity, 2);
progressView.setVisibility(View.GONE);
menuContainer.addView(progressView, LayoutHelper.createFrame(48, 56));
menuButton.setOnClickListener(v -> menuButton.toggleSubMenu());
menuButton.setDelegate(id -> {
if (adapter[0].currentPage == null || parentActivity == null) {
return;
}
if (id == search_item) {
showSearch(true);
} else if (id == share_item) {
showDialog(new ShareAlert(parentActivity, null, adapter[0].currentPage.url, false, adapter[0].currentPage.url, false));
} else if (id == open_item) {
String webPageUrl;
if (!TextUtils.isEmpty(adapter[0].currentPage.cached_page.url)) {
webPageUrl = adapter[0].currentPage.cached_page.url;
} else {
webPageUrl = adapter[0].currentPage.url;
}
Browser.openUrl(parentActivity, webPageUrl, true, false);
} else if (id == settings_item) {
BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity);
builder.setApplyTopPadding(false);
LinearLayout settingsContainer = new LinearLayout(parentActivity);
settingsContainer.setPadding(0, 0, 0, AndroidUtilities.dp(4));
settingsContainer.setOrientation(LinearLayout.VERTICAL);
HeaderCell headerCell = new HeaderCell(parentActivity);
headerCell.setText(LocaleController.getString("FontSize", R.string.FontSize));
settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 1, 3, 0));
TextSizeCell sizeCell = new TextSizeCell(parentActivity);
settingsContainer.addView(sizeCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 0, 3, 0));
headerCell = new HeaderCell(parentActivity);
headerCell.setText(LocaleController.getString("FontType", R.string.FontType));
settingsContainer.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 3, 4, 3, 2));
for (int a = 0; a < 2; a++) {
fontCells[a] = new FontCell(parentActivity);
switch(a) {
case 0:
fontCells[a].setTextAndTypeface(LocaleController.getString("Default", R.string.Default), Typeface.DEFAULT);
break;
case 1:
fontCells[a].setTextAndTypeface("Serif", Typeface.SERIF);
break;
}
fontCells[a].select(a == selectedFont, false);
fontCells[a].setTag(a);
fontCells[a].setOnClickListener(v -> {
int num = (Integer) v.getTag();
selectedFont = num;
for (int a1 = 0; a1 < 2; a1++) {
fontCells[a1].select(a1 == num, true);
}
updatePaintFonts();
for (int i = 0; i < listView.length; i++) {
adapter[i].notifyDataSetChanged();
}
});
settingsContainer.addView(fontCells[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
}
builder.setCustomView(settingsContainer);
showDialog(linkSheet = builder.create());
}
});
searchPanel = new FrameLayout(parentActivity) {
@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(), Theme.chat_composeBackgroundPaint);
}
};
searchPanel.setOnTouchListener((v, event) -> true);
searchPanel.setWillNotDraw(false);
searchPanel.setVisibility(View.INVISIBLE);
searchPanel.setFocusable(true);
searchPanel.setFocusableInTouchMode(true);
searchPanel.setClickable(true);
searchPanel.setPadding(0, AndroidUtilities.dp(3), 0, 0);
containerView.addView(searchPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
searchUpButton = new ImageView(parentActivity);
searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
searchUpButton.setImageResource(R.drawable.msg_go_up);
searchUpButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
searchUpButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchPanel.addView(searchUpButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 48, 0));
searchUpButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex - 1));
searchUpButton.setContentDescription(LocaleController.getString("AccDescrSearchNext", R.string.AccDescrSearchNext));
searchDownButton = new ImageView(parentActivity);
searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
searchDownButton.setImageResource(R.drawable.msg_go_down);
searchDownButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText), PorterDuff.Mode.MULTIPLY));
searchDownButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_actionBarActionModeDefaultSelector), 1));
searchPanel.addView(searchDownButton, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP, 0, 0, 0, 0));
searchDownButton.setOnClickListener(view -> scrollToSearchIndex(currentSearchIndex + 1));
searchDownButton.setContentDescription(LocaleController.getString("AccDescrSearchPrev", R.string.AccDescrSearchPrev));
searchCountText = new SimpleTextView(parentActivity);
searchCountText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
searchCountText.setTextSize(15);
searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
searchCountText.setGravity(Gravity.LEFT);
searchPanel.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 18, 0, 108, 0));
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 - 1;
windowLayoutParams.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
if (Build.VERSION.SDK_INT >= 21) {
windowLayoutParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
if (Build.VERSION.SDK_INT >= 28) {
windowLayoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
}
}
textSelectionHelper = new TextSelectionHelper.ArticleTextSelectionHelper();
textSelectionHelper.setParentView(listView[0]);
if (MessagesController.getGlobalMainSettings().getBoolean("translate_button", false)) {
textSelectionHelper.setOnTranslate((text, fromLang, toLang, onAlertDismiss) -> {
TranslateAlert.showAlert(parentActivity, parentFragment, fromLang, toLang, text, false, null, onAlertDismiss);
});
}
textSelectionHelper.layoutManager = layoutManager[0];
textSelectionHelper.setCallback(new TextSelectionHelper.Callback() {
@Override
public void onStateChanged(boolean isSelected) {
if (isSelected) {
showSearch(false);
}
}
@Override
public void onTextCopied() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
BulletinFactory.of(containerView, null).createCopyBulletin(LocaleController.getString("TextCopied", R.string.TextCopied)).show();
}
}
});
containerView.addView(textSelectionHelper.getOverlayView(activity));
pinchToZoomHelper = new PinchToZoomHelper(containerView, windowView);
pinchToZoomHelper.setClipBoundsListener(new PinchToZoomHelper.ClipBoundsListener() {
@Override
public void getClipTopBottom(float[] topBottom) {
topBottom[0] = currentHeaderHeight;
topBottom[1] = listView[0].getMeasuredHeight();
}
});
pinchToZoomHelper.setCallback(new PinchToZoomHelper.Callback() {
@Override
public void onZoomStarted(MessageObject messageObject) {
if (listView[0] != null) {
listView[0].cancelClickRunnables(true);
}
}
});
updatePaintColors();
}
use of org.telegram.ui.ActionBar.ActionBarMenuItem 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.ui.ActionBar.ActionBarMenuItem in project Telegram-FOSS by Telegram-FOSS-Team.
the class ThemePreviewActivity method createView.
@SuppressLint("Recycle")
@Override
public View createView(Context context) {
hasOwnBackground = true;
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
page1 = new FrameLayout(context);
ActionBarMenu menu = actionBar.createMenu();
final ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
@Override
public void onSearchExpand() {
}
@Override
public boolean canCollapseSearch() {
return true;
}
@Override
public void onSearchCollapse() {
}
@Override
public void onTextChanged(EditText editText) {
}
});
item.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
actionBar.setBackButtonDrawable(new MenuDrawable());
actionBar.setAddToContainer(false);
actionBar.setTitle(LocaleController.getString("ThemePreview", R.string.ThemePreview));
page1 = new FrameLayout(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
int actionBarHeight = actionBar.getMeasuredHeight();
if (actionBar.getVisibility() == VISIBLE) {
heightSize -= actionBarHeight;
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
layoutParams.topMargin = actionBarHeight;
listView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
measureChildWithMargins(floatingButton, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == actionBar && parentLayout != null) {
parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() : 0);
}
return result;
}
};
page1.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
page1.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
listView = new RecyclerListView(context);
listView.setVerticalScrollBarEnabled(true);
listView.setItemAnimator(null);
listView.setLayoutAnimation(null);
listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
listView.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
listView.setPadding(0, 0, 0, AndroidUtilities.dp(screenType != SCREEN_TYPE_PREVIEW ? 12 : 0));
listView.setOnItemClickListener((view, position) -> {
});
page1.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
floatingButton = new ImageView(context);
floatingButton.setScaleType(ImageView.ScaleType.CENTER);
Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
drawable = combinedDrawable;
}
floatingButton.setBackgroundDrawable(drawable);
floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
floatingButton.setImageResource(R.drawable.floating_pencil);
if (Build.VERSION.SDK_INT >= 21) {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
floatingButton.setStateListAnimator(animator);
floatingButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
}
});
}
page1.addView(floatingButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 14));
dialogsAdapter = new DialogsAdapter(context);
listView.setAdapter(dialogsAdapter);
page2 = new FrameLayout(context) {
private boolean ignoreLayout;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
if (dropDownContainer != null) {
ignoreLayout = true;
if (!AndroidUtilities.isTablet()) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams();
layoutParams.topMargin = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
dropDownContainer.setLayoutParams(layoutParams);
}
if (!AndroidUtilities.isTablet() && ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
dropDown.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
} else {
dropDown.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
}
ignoreLayout = false;
}
measureChildWithMargins(actionBar2, widthMeasureSpec, 0, heightMeasureSpec, 0);
int actionBarHeight = actionBar2.getMeasuredHeight();
if (actionBar2.getVisibility() == VISIBLE) {
heightSize -= actionBarHeight;
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView2.getLayoutParams();
layoutParams.topMargin = actionBarHeight;
listView2.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - layoutParams.bottomMargin, MeasureSpec.EXACTLY));
layoutParams = (FrameLayout.LayoutParams) backgroundImage.getLayoutParams();
layoutParams.topMargin = actionBarHeight;
backgroundImage.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
if (bottomOverlayChat != null) {
measureChildWithMargins(bottomOverlayChat, widthMeasureSpec, 0, heightMeasureSpec, 0);
}
for (int a = 0; a < patternLayout.length; a++) {
if (patternLayout[a] != null) {
measureChildWithMargins(patternLayout[a], widthMeasureSpec, 0, heightMeasureSpec, 0);
}
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == actionBar2 && parentLayout != null) {
parentLayout.drawHeaderShadow(canvas, actionBar2.getVisibility() == VISIBLE ? (int) (actionBar2.getMeasuredHeight() + actionBar2.getTranslationY()) : 0);
}
return result;
}
@Override
public void requestLayout() {
if (ignoreLayout) {
return;
}
super.requestLayout();
}
};
messagesAdapter = new MessagesAdapter(context);
actionBar2 = createActionBar(context);
if (AndroidUtilities.isTablet()) {
actionBar2.setOccupyStatusBar(false);
}
actionBar2.setBackButtonDrawable(new BackDrawable(false));
actionBar2.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
if (checkDiscard()) {
cancelThemeApply(false);
}
} else if (id >= 1 && id <= 3) {
selectColorType(id);
} else if (id == 4) {
if (removeBackgroundOverride) {
Theme.resetCustomWallpaper(false);
}
File path = accent.getPathToWallpaper();
if (path != null) {
path.delete();
}
accent.patternSlug = selectedPattern != null ? selectedPattern.slug : "";
accent.patternIntensity = currentIntensity;
accent.patternMotion = isMotion;
if ((int) accent.backgroundOverrideColor == 0) {
accent.backgroundOverrideColor = 0x100000000L;
}
if ((int) accent.backgroundGradientOverrideColor1 == 0) {
accent.backgroundGradientOverrideColor1 = 0x100000000L;
}
if ((int) accent.backgroundGradientOverrideColor2 == 0) {
accent.backgroundGradientOverrideColor2 = 0x100000000L;
}
if ((int) accent.backgroundGradientOverrideColor3 == 0) {
accent.backgroundGradientOverrideColor3 = 0x100000000L;
}
saveAccentWallpaper();
NotificationCenter.getGlobalInstance().removeObserver(ThemePreviewActivity.this, NotificationCenter.wallpapersDidLoad);
Theme.saveThemeAccents(applyingTheme, true, false, false, true);
Theme.applyPreviousTheme();
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, applyingTheme, nightTheme, null, -1);
finishFragment();
} else if (id == 5) {
if (getParentActivity() == null) {
return;
}
String link;
StringBuilder modes = new StringBuilder();
if (isBlurred) {
modes.append("blur");
}
if (isMotion) {
if (modes.length() > 0) {
modes.append("+");
}
modes.append("motion");
}
if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
link = "https://" + MessagesController.getInstance(currentAccount).linkPrefix + "/bg/" + wallPaper.slug;
if (modes.length() > 0) {
link += "?mode=" + modes.toString();
}
} else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
WallpapersListActivity.ColorWallpaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(selectedPattern != null ? selectedPattern.slug : Theme.COLOR_BACKGROUND_SLUG, backgroundColor, backgroundGradientColor1, backgroundGradientColor2, backgroundGradientColor3, backgroundRotation, currentIntensity, isMotion, null);
colorWallpaper.pattern = selectedPattern;
link = colorWallpaper.getUrl();
} else {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
Theme.ThemeAccent accent = Theme.getActiveTheme().getAccent(false);
if (accent != null) {
WallpapersListActivity.ColorWallpaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(accent.patternSlug, (int) accent.backgroundOverrideColor, (int) accent.backgroundGradientOverrideColor1, (int) accent.backgroundGradientOverrideColor2, (int) accent.backgroundGradientOverrideColor3, accent.backgroundRotation, accent.patternIntensity, accent.patternMotion, null);
for (int a = 0, N = patterns.size(); a < N; a++) {
TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) patterns.get(a);
if (wallPaper.pattern) {
if (accent.patternSlug.equals(wallPaper.slug)) {
colorWallpaper.pattern = wallPaper;
break;
}
}
}
link = colorWallpaper.getUrl();
} else {
return;
}
} else {
return;
}
}
showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false) {
@Override
protected void onSend(LongSparseArray<TLRPC.Dialog> dids, int count) {
if (dids.size() == 1) {
undoView.showWithAction(dids.valueAt(0).id, UndoView.ACTION_SHARE_BACKGROUND, count);
} else {
undoView.showWithAction(0, UndoView.ACTION_SHARE_BACKGROUND, count, dids.size(), null, null);
}
}
});
}
}
});
backgroundImage = new BackupImageView(context) {
private Drawable background;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
parallaxScale = parallaxEffect.getScale(getMeasuredWidth(), getMeasuredHeight());
if (isMotion) {
setScaleX(parallaxScale);
setScaleY(parallaxScale);
}
if (radialProgress != null) {
int size = AndroidUtilities.dp(44);
int x = (getMeasuredWidth() - size) / 2;
int y = (getMeasuredHeight() - size) / 2;
radialProgress.setProgressRect(x, y, x + size, y + size);
}
progressVisible = screenType == SCREEN_TYPE_CHANGE_BACKGROUND && getMeasuredWidth() <= getMeasuredHeight();
}
@Override
protected void onDraw(Canvas canvas) {
if (background instanceof ColorDrawable || background instanceof GradientDrawable || background instanceof MotionBackgroundDrawable) {
background.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
background.draw(canvas);
} else if (background instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) background;
if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
canvas.save();
float scale = 2.0f / AndroidUtilities.density;
canvas.scale(scale, scale);
background.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
background.draw(canvas);
canvas.restore();
} else {
int viewHeight = getMeasuredHeight();
float scaleX = (float) getMeasuredWidth() / (float) background.getIntrinsicWidth();
float scaleY = (float) (viewHeight) / (float) background.getIntrinsicHeight();
float scale = Math.max(scaleX, scaleY);
int width = (int) Math.ceil(background.getIntrinsicWidth() * scale * parallaxScale);
int height = (int) Math.ceil(background.getIntrinsicHeight() * scale * parallaxScale);
int x = (getMeasuredWidth() - width) / 2;
int y = (viewHeight - height) / 2;
background.setBounds(x, y, x + width, y + height);
background.draw(canvas);
}
}
super.onDraw(canvas);
if (progressVisible && radialProgress != null) {
radialProgress.draw(canvas);
}
}
@Override
public Drawable getBackground() {
return background;
}
@Override
public void setBackground(Drawable drawable) {
background = drawable;
}
@Override
public void setAlpha(float alpha) {
if (radialProgress != null) {
radialProgress.setOverrideAlpha(alpha);
}
}
};
page2.addView(backgroundImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48));
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
backgroundImage.getImageReceiver().setDelegate((imageReceiver, set, thumb, memCache) -> {
if (!(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
Drawable dr = imageReceiver.getDrawable();
if (set && dr != null) {
if (!Theme.hasThemeKey(Theme.key_chat_serviceBackground) || backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
Theme.applyChatServiceMessageColor(AndroidUtilities.calcDrawableColor(dr), dr);
}
listView2.invalidateViews();
if (backgroundButtonsContainer != null) {
for (int a = 0, N = backgroundButtonsContainer.getChildCount(); a < N; a++) {
backgroundButtonsContainer.getChildAt(a).invalidate();
}
}
if (messagesButtonsContainer != null) {
for (int a = 0, N = messagesButtonsContainer.getChildCount(); a < N; a++) {
messagesButtonsContainer.getChildAt(a).invalidate();
}
}
if (radialProgress != null) {
radialProgress.setColors(Theme.key_chat_serviceBackground, Theme.key_chat_serviceBackground, Theme.key_chat_serviceText, Theme.key_chat_serviceText);
}
if (!thumb && isBlurred && blurredBitmap == null) {
backgroundImage.getImageReceiver().setCrossfadeWithOldImage(false);
updateBlurred();
backgroundImage.getImageReceiver().setCrossfadeWithOldImage(true);
}
}
}
});
}
if (messagesAdapter.showSecretMessages) {
actionBar2.setTitle("Telegram Beta Chat");
actionBar2.setSubtitle(LocaleController.formatPluralString("Members", 505));
} else {
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
actionBar2.setTitle(LocaleController.getString("BackgroundPreview", R.string.BackgroundPreview));
if (BuildVars.DEBUG_PRIVATE_VERSION && Theme.getActiveTheme().getAccent(false) != null || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && !Theme.DEFAULT_BACKGROUND_SLUG.equals(((WallpapersListActivity.ColorWallpaper) currentWallpaper).slug) || currentWallpaper instanceof TLRPC.TL_wallPaper) {
ActionBarMenu menu2 = actionBar2.createMenu();
menu2.addItem(5, R.drawable.msg_share_filled);
}
} else if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
ActionBarMenu menu2 = actionBar2.createMenu();
saveItem = menu2.addItem(4, LocaleController.getString("Save", R.string.Save).toUpperCase());
dropDownContainer = new ActionBarMenuItem(context, menu2, 0, 0) {
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setText(dropDown.getText());
}
};
dropDownContainer.setSubMenuOpenSide(1);
dropDownContainer.addSubItem(2, LocaleController.getString("ColorPickerBackground", R.string.ColorPickerBackground));
dropDownContainer.addSubItem(1, LocaleController.getString("ColorPickerMainColor", R.string.ColorPickerMainColor));
dropDownContainer.addSubItem(3, LocaleController.getString("ColorPickerMyMessages", R.string.ColorPickerMyMessages));
dropDownContainer.setAllowCloseAnimation(false);
dropDownContainer.setForceSmoothKeyboard(true);
actionBar2.addView(dropDownContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
dropDownContainer.setOnClickListener(view -> dropDownContainer.toggleSubMenu());
dropDown = new TextView(context);
dropDown.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
dropDown.setGravity(Gravity.LEFT);
dropDown.setSingleLine(true);
dropDown.setLines(1);
dropDown.setMaxLines(1);
dropDown.setEllipsize(TextUtils.TruncateAt.END);
dropDown.setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle));
dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
dropDown.setText(LocaleController.getString("ColorPickerMainColor", R.string.ColorPickerMainColor));
Drawable dropDownDrawable = context.getResources().getDrawable(R.drawable.ic_arrow_drop_down).mutate();
dropDownDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultTitle), PorterDuff.Mode.MULTIPLY));
dropDown.setCompoundDrawablesWithIntrinsicBounds(null, null, dropDownDrawable, null);
dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 1));
} else {
String name = applyingTheme.info != null ? applyingTheme.info.title : applyingTheme.getName();
int index = name.lastIndexOf(".attheme");
if (index >= 0) {
name = name.substring(0, index);
}
actionBar2.setTitle(name);
if (applyingTheme.info != null && applyingTheme.info.installs_count > 0) {
actionBar2.setSubtitle(LocaleController.formatPluralString("ThemeInstallCount", applyingTheme.info.installs_count));
} else {
actionBar2.setSubtitle(LocaleController.formatDateOnline(System.currentTimeMillis() / 1000 - 60 * 60));
}
}
}
listView2 = new RecyclerListView(context) {
@Override
public boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child instanceof ChatMessageCell) {
ChatMessageCell chatMessageCell = (ChatMessageCell) child;
MessageObject message = chatMessageCell.getMessageObject();
ImageReceiver imageReceiver = chatMessageCell.getAvatarImage();
if (imageReceiver != null) {
int top = child.getTop();
if (chatMessageCell.isPinnedBottom()) {
ViewHolder holder = listView2.getChildViewHolder(child);
if (holder != null) {
int p = holder.getAdapterPosition();
int nextPosition;
nextPosition = p - 1;
holder = listView2.findViewHolderForAdapterPosition(nextPosition);
if (holder != null) {
imageReceiver.setImageY(-AndroidUtilities.dp(1000));
imageReceiver.draw(canvas);
return result;
}
}
}
float tx = chatMessageCell.getTranslationX();
int y = child.getTop() + chatMessageCell.getLayoutHeight();
int maxY = listView2.getMeasuredHeight() - listView2.getPaddingBottom();
if (y > maxY) {
y = maxY;
}
if (chatMessageCell.isPinnedTop()) {
ViewHolder holder = listView2.getChildViewHolder(child);
if (holder != null) {
int tries = 0;
while (true) {
if (tries >= 20) {
break;
}
tries++;
int p = holder.getAdapterPosition();
int prevPosition = p + 1;
holder = listView2.findViewHolderForAdapterPosition(prevPosition);
if (holder != null) {
top = holder.itemView.getTop();
if (y - AndroidUtilities.dp(48) < holder.itemView.getBottom()) {
tx = Math.min(holder.itemView.getTranslationX(), tx);
}
if (holder.itemView instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) holder.itemView;
if (!cell.isPinnedTop()) {
break;
}
} else {
break;
}
} else {
break;
}
}
}
}
if (y - AndroidUtilities.dp(48) < top) {
y = top + AndroidUtilities.dp(48);
}
if (tx != 0) {
canvas.save();
canvas.translate(tx, 0);
}
imageReceiver.setImageY(y - AndroidUtilities.dp(44));
imageReceiver.draw(canvas);
if (tx != 0) {
canvas.restore();
}
}
}
return result;
}
@Override
public void setTranslationY(float translationY) {
super.setTranslationY(translationY);
if (backgroundCheckBoxView != null) {
for (int a = 0; a < backgroundCheckBoxView.length; a++) {
backgroundCheckBoxView[a].invalidate();
}
}
if (messagesCheckBoxView != null) {
for (int a = 0; a < messagesCheckBoxView.length; a++) {
messagesCheckBoxView[a].invalidate();
}
}
if (backgroundPlayAnimationView != null) {
backgroundPlayAnimationView.invalidate();
}
if (messagesPlayAnimationView != null) {
messagesPlayAnimationView.invalidate();
}
}
@Override
protected void onChildPressed(View child, float x, float y, boolean pressed) {
if (pressed && child instanceof ChatMessageCell) {
ChatMessageCell messageCell = (ChatMessageCell) child;
if (!messageCell.isInsideBackground(x, y)) {
return;
}
}
super.onChildPressed(child, x, y, pressed);
}
@Override
protected boolean allowSelectChildAtPosition(View child) {
RecyclerView.ViewHolder holder = listView2.findContainingViewHolder(child);
if (holder != null && holder.getItemViewType() == 2) {
return false;
}
return super.allowSelectChildAtPosition(child);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
checkMotionEvent(e);
return super.onTouchEvent(e);
}
private void checkMotionEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_UP) {
if (!wasScroll && currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && patternLayout[0].getVisibility() == View.VISIBLE) {
showPatternsView(0, false, true);
}
wasScroll = false;
}
}
};
DefaultItemAnimator itemAnimator = new DefaultItemAnimator() {
@Override
protected void onMoveAnimationUpdate(RecyclerView.ViewHolder holder) {
listView2.invalidateViews();
}
};
itemAnimator.setDelayAnimations(false);
listView2.setItemAnimator(itemAnimator);
listView2.setVerticalScrollBarEnabled(true);
listView2.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4 + 48));
} else if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(16));
} else {
listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4));
}
listView2.setClipToPadding(false);
listView2.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true));
listView2.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
page2.addView(listView2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 273));
listView2.setOnItemClickListener((view, position, x, y) -> {
if (view instanceof ChatMessageCell) {
ChatMessageCell cell = (ChatMessageCell) view;
if (cell.isInsideBackground(x, y)) {
if (cell.getMessageObject().isOutOwner()) {
selectColorType(3);
} else {
selectColorType(1);
}
} else {
selectColorType(2);
}
}
});
} else {
page2.addView(listView2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
}
listView2.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
listView2.invalidateViews();
wasScroll = true;
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
wasScroll = false;
}
}
});
page2.addView(actionBar2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
parallaxEffect = new WallpaperParallaxEffect(context);
parallaxEffect.setCallback((offsetX, offsetY, angle) -> {
if (!isMotion) {
return;
}
Drawable background = backgroundImage.getBackground();
float progress;
if (motionAnimation != null) {
progress = (backgroundImage.getScaleX() - 1.0f) / (parallaxScale - 1.0f);
} else {
progress = 1.0f;
}
backgroundImage.setTranslationX(offsetX * progress);
backgroundImage.setTranslationY(offsetY * progress);
});
if (screenType == SCREEN_TYPE_ACCENT_COLOR || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
radialProgress = new RadialProgress2(backgroundImage);
radialProgress.setColors(Theme.key_chat_serviceBackground, Theme.key_chat_serviceBackground, Theme.key_chat_serviceText, Theme.key_chat_serviceText);
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
bottomOverlayChat = 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(), Theme.chat_composeBackgroundPaint);
}
};
bottomOverlayChat.setWillNotDraw(false);
bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
page2.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
bottomOverlayChat.setOnClickListener(view -> {
boolean done;
boolean sameFile = false;
Theme.ThemeInfo theme = Theme.getActiveTheme();
String originalFileName = theme.generateWallpaperName(null, isBlurred);
String fileName = isBlurred ? theme.generateWallpaperName(null, false) : originalFileName;
File toFile = new File(ApplicationLoader.getFilesDirFixed(), originalFileName);
if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
if (originalBitmap != null) {
try {
FileOutputStream stream = new FileOutputStream(toFile);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
stream.close();
done = true;
} catch (Exception e) {
done = false;
FileLog.e(e);
}
} else {
ImageReceiver imageReceiver = backgroundImage.getImageReceiver();
if (imageReceiver.hasNotThumb() || imageReceiver.hasStaticThumb()) {
Bitmap bitmap = imageReceiver.getBitmap();
try {
FileOutputStream stream = new FileOutputStream(toFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
stream.close();
done = true;
} catch (Exception e) {
done = false;
FileLog.e(e);
}
} else {
done = false;
}
}
if (!done) {
TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
File f = FileLoader.getPathToAttach(wallPaper.document, true);
try {
done = AndroidUtilities.copyFile(f, toFile);
} catch (Exception e) {
done = false;
FileLog.e(e);
}
}
} else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
if (selectedPattern != null) {
try {
WallpapersListActivity.ColorWallpaper wallPaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
Bitmap bitmap = backgroundImage.getImageReceiver().getBitmap();
@SuppressLint("DrawAllocation") Bitmap dst = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dst);
if (backgroundGradientColor2 != 0) {
} else if (backgroundGradientColor1 != 0) {
GradientDrawable gradientDrawable = new GradientDrawable(BackgroundGradientDrawable.getGradientOrientation(backgroundRotation), new int[] { backgroundColor, backgroundGradientColor1 });
gradientDrawable.setBounds(0, 0, dst.getWidth(), dst.getHeight());
gradientDrawable.draw(canvas);
} else {
canvas.drawColor(backgroundColor);
}
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
paint.setColorFilter(new PorterDuffColorFilter(patternColor, blendMode));
paint.setAlpha((int) (255 * Math.abs(currentIntensity)));
canvas.drawBitmap(bitmap, 0, 0, paint);
FileOutputStream stream = new FileOutputStream(toFile);
if (backgroundGradientColor2 != 0) {
dst.compress(Bitmap.CompressFormat.PNG, 100, stream);
} else {
dst.compress(Bitmap.CompressFormat.JPEG, 87, stream);
}
stream.close();
done = true;
} catch (Throwable e) {
FileLog.e(e);
done = false;
}
} else {
done = true;
}
} else if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
WallpapersListActivity.FileWallpaper wallpaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
if (wallpaper.resId != 0 || Theme.THEME_BACKGROUND_SLUG.equals(wallpaper.slug)) {
done = true;
} else {
try {
File fromFile = wallpaper.originalPath != null ? wallpaper.originalPath : wallpaper.path;
if (sameFile = fromFile.equals(toFile)) {
done = true;
} else {
done = AndroidUtilities.copyFile(fromFile, toFile);
}
} catch (Exception e) {
done = false;
FileLog.e(e);
}
}
} else if (currentWallpaper instanceof MediaController.SearchImage) {
MediaController.SearchImage wallpaper = (MediaController.SearchImage) currentWallpaper;
File f;
if (wallpaper.photo != null) {
TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(wallpaper.photo.sizes, maxWallpaperSize, true);
f = FileLoader.getPathToAttach(image, true);
} else {
f = ImageLoader.getHttpFilePath(wallpaper.imageUrl, "jpg");
}
try {
done = AndroidUtilities.copyFile(f, toFile);
} catch (Exception e) {
done = false;
FileLog.e(e);
}
} else {
done = false;
}
if (isBlurred) {
try {
File blurredFile = new File(ApplicationLoader.getFilesDirFixed(), fileName);
FileOutputStream stream = new FileOutputStream(blurredFile);
blurredBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
stream.close();
done = true;
} catch (Throwable e) {
FileLog.e(e);
done = false;
}
}
String slug;
int rotation = 45;
int color = 0;
int gradientColor1 = 0;
int gradientColor2 = 0;
int gradientColor3 = 0;
File path = null;
if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
slug = wallPaper.slug;
} else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
WallpapersListActivity.ColorWallpaper wallPaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
if (Theme.DEFAULT_BACKGROUND_SLUG.equals(wallPaper.slug)) {
slug = Theme.DEFAULT_BACKGROUND_SLUG;
color = 0;
} else {
if (selectedPattern != null) {
slug = selectedPattern.slug;
} else {
slug = Theme.COLOR_BACKGROUND_SLUG;
}
color = backgroundColor;
gradientColor1 = backgroundGradientColor1;
gradientColor2 = backgroundGradientColor2;
gradientColor3 = backgroundGradientColor3;
rotation = backgroundRotation;
}
} else if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
WallpapersListActivity.FileWallpaper wallPaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
slug = wallPaper.slug;
path = wallPaper.path;
} else if (currentWallpaper instanceof MediaController.SearchImage) {
MediaController.SearchImage wallPaper = (MediaController.SearchImage) currentWallpaper;
if (wallPaper.photo != null) {
TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(wallPaper.photo.sizes, maxWallpaperSize, true);
path = FileLoader.getPathToAttach(image, true);
} else {
path = ImageLoader.getHttpFilePath(wallPaper.imageUrl, "jpg");
}
slug = "";
} else {
color = 0;
slug = Theme.DEFAULT_BACKGROUND_SLUG;
}
Theme.OverrideWallpaperInfo wallpaperInfo = new Theme.OverrideWallpaperInfo();
wallpaperInfo.fileName = fileName;
wallpaperInfo.originalFileName = originalFileName;
wallpaperInfo.slug = slug;
wallpaperInfo.isBlurred = isBlurred;
wallpaperInfo.isMotion = isMotion;
wallpaperInfo.color = color;
wallpaperInfo.gradientColor1 = gradientColor1;
wallpaperInfo.gradientColor2 = gradientColor2;
wallpaperInfo.gradientColor3 = gradientColor3;
wallpaperInfo.rotation = rotation;
wallpaperInfo.intensity = currentIntensity;
if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
WallpapersListActivity.ColorWallpaper colorWallpaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
String slugStr;
if (!Theme.COLOR_BACKGROUND_SLUG.equals(slug) && !Theme.THEME_BACKGROUND_SLUG.equals(slug) && !Theme.DEFAULT_BACKGROUND_SLUG.equals(slug)) {
slugStr = slug;
} else {
slugStr = null;
}
float intensity = colorWallpaper.intensity;
if (intensity < 0 && !Theme.getActiveTheme().isDark()) {
intensity *= -1;
}
if (colorWallpaper.parentWallpaper != null && colorWallpaper.color == color && colorWallpaper.gradientColor1 == gradientColor1 && colorWallpaper.gradientColor2 == gradientColor2 && colorWallpaper.gradientColor3 == gradientColor3 && TextUtils.equals(colorWallpaper.slug, slugStr) && colorWallpaper.gradientRotation == rotation && (selectedPattern == null || Math.abs(intensity - currentIntensity) < 0.001f)) {
wallpaperInfo.wallpaperId = colorWallpaper.parentWallpaper.id;
wallpaperInfo.accessHash = colorWallpaper.parentWallpaper.access_hash;
}
}
MessagesController.getInstance(currentAccount).saveWallpaperToServer(path, wallpaperInfo, slug != null, 0);
if (done) {
Theme.serviceMessageColorBackup = Theme.getColor(Theme.key_chat_serviceBackground);
if (Theme.THEME_BACKGROUND_SLUG.equals(wallpaperInfo.slug)) {
wallpaperInfo = null;
}
Theme.getActiveTheme().setOverrideWallpaper(wallpaperInfo);
Theme.reloadWallpaper();
if (!sameFile) {
ImageLoader.getInstance().removeImage(ImageLoader.getHttpFileName(toFile.getAbsolutePath()) + "@100_100");
}
}
if (delegate != null) {
delegate.didSetNewBackground();
}
finishFragment();
});
bottomOverlayChatText = new TextView(context);
bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
bottomOverlayChatText.setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
bottomOverlayChatText.setText(LocaleController.getString("SetBackground", R.string.SetBackground));
bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
}
Rect paddings = new Rect();
sheetDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
sheetDrawable.getPadding(paddings);
sheetDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhite), PorterDuff.Mode.MULTIPLY));
TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(AndroidUtilities.dp(14));
textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
{
int textsCount;
if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
textsCount = 3;
if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && Theme.DEFAULT_BACKGROUND_SLUG.equals(((WallpapersListActivity.ColorWallpaper) currentWallpaper).slug)) {
textsCount = 0;
}
} else {
textsCount = 2;
if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
WallpapersListActivity.FileWallpaper fileWallpaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
if (Theme.THEME_BACKGROUND_SLUG.equals(fileWallpaper.slug)) {
textsCount = 0;
}
}
}
String[] texts = new String[textsCount];
int[] textSizes = new int[textsCount];
backgroundCheckBoxView = new WallpaperCheckBoxView[textsCount];
int maxTextSize = 0;
if (textsCount != 0) {
backgroundButtonsContainer = new FrameLayout(context);
if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
texts[0] = LocaleController.getString("BackgroundColors", R.string.BackgroundColors);
texts[1] = LocaleController.getString("BackgroundPattern", R.string.BackgroundPattern);
texts[2] = LocaleController.getString("BackgroundMotion", R.string.BackgroundMotion);
} else {
texts[0] = LocaleController.getString("BackgroundBlurred", R.string.BackgroundBlurred);
texts[1] = LocaleController.getString("BackgroundMotion", R.string.BackgroundMotion);
}
for (int a = 0; a < texts.length; a++) {
textSizes[a] = (int) Math.ceil(textPaint.measureText(texts[a]));
maxTextSize = Math.max(maxTextSize, textSizes[a]);
}
backgroundPlayAnimationView = new FrameLayout(context) {
private RectF rect = new RectF();
@Override
protected void onDraw(Canvas canvas) {
rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
Theme.applyServiceShaderMatrixForView(backgroundPlayAnimationView, backgroundImage);
canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundPaint);
if (Theme.hasGradientService()) {
canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundGradientDarkenPaint);
}
}
};
backgroundPlayAnimationView.setWillNotDraw(false);
backgroundPlayAnimationView.setVisibility(backgroundGradientColor1 != 0 ? View.VISIBLE : View.INVISIBLE);
backgroundPlayAnimationView.setScaleX(backgroundGradientColor1 != 0 ? 1.0f : 0.1f);
backgroundPlayAnimationView.setScaleY(backgroundGradientColor1 != 0 ? 1.0f : 0.1f);
backgroundPlayAnimationView.setAlpha(backgroundGradientColor1 != 0 ? 1.0f : 0.0f);
backgroundPlayAnimationView.setTag(backgroundGradientColor1 != 0 ? 1 : null);
backgroundButtonsContainer.addView(backgroundPlayAnimationView, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
backgroundPlayAnimationView.setOnClickListener(new View.OnClickListener() {
int rotation = 0;
@Override
public void onClick(View v) {
Drawable background = backgroundImage.getBackground();
backgroundPlayAnimationImageView.setRotation(rotation);
rotation -= 45;
backgroundPlayAnimationImageView.animate().rotationBy(-45).setDuration(300).setInterpolator(CubicBezierInterpolator.EASE_OUT).start();
if (background instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) background;
motionBackgroundDrawable.switchToNextPosition();
} else {
onColorsRotate();
}
}
});
backgroundPlayAnimationImageView = new ImageView(context);
backgroundPlayAnimationImageView.setScaleType(ImageView.ScaleType.CENTER);
backgroundPlayAnimationImageView.setImageResource(R.drawable.bg_rotate_large);
backgroundPlayAnimationView.addView(backgroundPlayAnimationImageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
}
for (int a = 0; a < textsCount; a++) {
final int num = a;
backgroundCheckBoxView[a] = new WallpaperCheckBoxView(context, screenType != SCREEN_TYPE_ACCENT_COLOR && !(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) || a != 0, backgroundImage);
backgroundCheckBoxView[a].setBackgroundColor(backgroundColor);
backgroundCheckBoxView[a].setText(texts[a], textSizes[a], maxTextSize);
if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
if (a == 1) {
backgroundCheckBoxView[a].setChecked(selectedPattern != null || accent != null && !TextUtils.isEmpty(accent.patternSlug), false);
} else if (a == 2) {
backgroundCheckBoxView[a].setChecked(isMotion, false);
}
} else {
backgroundCheckBoxView[a].setChecked(a == 0 ? isBlurred : isMotion, false);
}
int width = maxTextSize + AndroidUtilities.dp(14 * 2 + 28);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
if (textsCount == 3) {
if (a == 0 || a == 2) {
layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
} else {
layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
}
} else {
if (a == 1) {
layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
} else {
layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
}
}
backgroundButtonsContainer.addView(backgroundCheckBoxView[a], layoutParams);
WallpaperCheckBoxView view = backgroundCheckBoxView[a];
backgroundCheckBoxView[a].setOnClickListener(v -> {
if (backgroundButtonsContainer.getAlpha() != 1.0f || patternViewAnimation != null) {
return;
}
if ((screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) && num == 2) {
view.setChecked(!view.isChecked(), true);
isMotion = view.isChecked();
parallaxEffect.setEnabled(isMotion);
animateMotionChange();
} else if (num == 1 && (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
if (backgroundCheckBoxView[1].isChecked()) {
lastSelectedPattern = selectedPattern;
backgroundImage.setImageDrawable(null);
selectedPattern = null;
isMotion = false;
updateButtonState(false, true);
animateMotionChange();
if (patternLayout[1].getVisibility() == View.VISIBLE) {
if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
showPatternsView(0, true, true);
} else {
showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
}
}
} else {
selectPattern(lastSelectedPattern != null ? -1 : 0);
if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
showPatternsView(1, true, true);
} else {
showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
}
}
backgroundCheckBoxView[1].setChecked(selectedPattern != null, true);
updateSelectedPattern(true);
patternsListView.invalidateViews();
updateMotionButton();
} else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
} else if (screenType != SCREEN_TYPE_ACCENT_COLOR) {
view.setChecked(!view.isChecked(), true);
if (num == 0) {
isBlurred = view.isChecked();
if (isBlurred) {
backgroundImage.getImageReceiver().setForceCrossfade(true);
}
updateBlurred();
} else {
isMotion = view.isChecked();
parallaxEffect.setEnabled(isMotion);
animateMotionChange();
}
}
});
if (a == 2) {
backgroundCheckBoxView[a].setAlpha(0.0f);
backgroundCheckBoxView[a].setVisibility(View.INVISIBLE);
}
}
}
if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
String[] texts = new String[2];
int[] textSizes = new int[2];
messagesCheckBoxView = new WallpaperCheckBoxView[2];
int maxTextSize = 0;
messagesButtonsContainer = new FrameLayout(context);
texts[0] = LocaleController.getString("BackgroundAnimate", R.string.BackgroundAnimate);
texts[1] = LocaleController.getString("BackgroundColors", R.string.BackgroundColors);
for (int a = 0; a < texts.length; a++) {
textSizes[a] = (int) Math.ceil(textPaint.measureText(texts[a]));
maxTextSize = Math.max(maxTextSize, textSizes[a]);
}
messagesPlayAnimationView = new FrameLayout(context) {
private RectF rect = new RectF();
@Override
protected void onDraw(Canvas canvas) {
rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
Theme.applyServiceShaderMatrixForView(messagesPlayAnimationView, backgroundImage);
canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundPaint);
if (Theme.hasGradientService()) {
canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundGradientDarkenPaint);
}
}
};
messagesPlayAnimationView.setWillNotDraw(false);
messagesPlayAnimationView.setVisibility(accent.myMessagesGradientAccentColor1 != 0 ? View.VISIBLE : View.INVISIBLE);
messagesPlayAnimationView.setScaleX(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.1f);
messagesPlayAnimationView.setScaleY(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.1f);
messagesPlayAnimationView.setAlpha(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.0f);
messagesButtonsContainer.addView(messagesPlayAnimationView, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
messagesPlayAnimationView.setOnClickListener(new View.OnClickListener() {
int rotation = 0;
@Override
public void onClick(View v) {
messagesPlayAnimationImageView.setRotation(rotation);
rotation -= 45;
messagesPlayAnimationImageView.animate().rotationBy(-45).setDuration(300).setInterpolator(CubicBezierInterpolator.EASE_OUT).start();
if (accent.myMessagesAnimated) {
if (msgOutDrawable.getMotionBackgroundDrawable() != null) {
msgOutDrawable.getMotionBackgroundDrawable().switchToNextPosition();
}
} else {
int temp;
if (accent.myMessagesGradientAccentColor3 != 0) {
temp = accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor;
accent.myMessagesAccentColor = accent.myMessagesGradientAccentColor1;
accent.myMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor2;
accent.myMessagesGradientAccentColor2 = accent.myMessagesGradientAccentColor3;
accent.myMessagesGradientAccentColor3 = temp;
} else {
temp = accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor;
accent.myMessagesAccentColor = accent.myMessagesGradientAccentColor1;
accent.myMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor2;
accent.myMessagesGradientAccentColor2 = temp;
}
colorPicker.setColor(accent.myMessagesGradientAccentColor3, 3);
colorPicker.setColor(accent.myMessagesGradientAccentColor2, 2);
colorPicker.setColor(accent.myMessagesGradientAccentColor1, 1);
colorPicker.setColor(accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor, 0);
messagesCheckBoxView[1].setColor(0, accent.myMessagesAccentColor);
messagesCheckBoxView[1].setColor(1, accent.myMessagesGradientAccentColor1);
messagesCheckBoxView[1].setColor(2, accent.myMessagesGradientAccentColor2);
messagesCheckBoxView[1].setColor(3, accent.myMessagesGradientAccentColor3);
Theme.refreshThemeColors(true, true);
listView2.invalidateViews();
}
}
});
messagesPlayAnimationImageView = new ImageView(context);
messagesPlayAnimationImageView.setScaleType(ImageView.ScaleType.CENTER);
messagesPlayAnimationImageView.setImageResource(R.drawable.bg_rotate_large);
messagesPlayAnimationView.addView(messagesPlayAnimationImageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
for (int a = 0; a < 2; a++) {
final int num = a;
messagesCheckBoxView[a] = new WallpaperCheckBoxView(context, a == 0, backgroundImage);
messagesCheckBoxView[a].setText(texts[a], textSizes[a], maxTextSize);
if (a == 0) {
messagesCheckBoxView[a].setChecked(accent.myMessagesAnimated, false);
}
int width = maxTextSize + AndroidUtilities.dp(14 * 2 + 28);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
if (a == 1) {
layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
} else {
layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
}
messagesButtonsContainer.addView(messagesCheckBoxView[a], layoutParams);
WallpaperCheckBoxView view = messagesCheckBoxView[a];
messagesCheckBoxView[a].setOnClickListener(v -> {
if (messagesButtonsContainer.getAlpha() != 1.0f) {
return;
}
if (num == 0) {
view.setChecked(!view.isChecked(), true);
accent.myMessagesAnimated = view.isChecked();
Theme.refreshThemeColors(true, true);
listView2.invalidateViews();
}
});
}
}
if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
isBlurred = false;
for (int a = 0; a < 2; a++) {
final int num = a;
patternLayout[a] = new FrameLayout(context) {
@Override
public void onDraw(Canvas canvas) {
if (num == 0) {
sheetDrawable.setBounds(colorPicker.getLeft() - paddings.left, 0, colorPicker.getRight() + paddings.right, getMeasuredHeight());
} else {
sheetDrawable.setBounds(-paddings.left, 0, getMeasuredWidth() + paddings.right, getMeasuredHeight());
}
sheetDrawable.draw(canvas);
}
};
if (a == 1 || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
patternLayout[a].setVisibility(View.INVISIBLE);
}
patternLayout[a].setWillNotDraw(false);
FrameLayout.LayoutParams layoutParams;
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
layoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, a == 0 ? 321 : 316, Gravity.LEFT | Gravity.BOTTOM);
} else {
layoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, a == 0 ? 273 : 316, Gravity.LEFT | Gravity.BOTTOM);
}
if (a == 0) {
layoutParams.height += AndroidUtilities.dp(12) + paddings.top;
patternLayout[a].setPadding(0, AndroidUtilities.dp(12) + paddings.top, 0, 0);
}
page2.addView(patternLayout[a], layoutParams);
if (a == 1 || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
patternsButtonsContainer[a] = 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(), Theme.chat_composeBackgroundPaint);
}
};
patternsButtonsContainer[a].setWillNotDraw(false);
patternsButtonsContainer[a].setPadding(0, AndroidUtilities.dp(3), 0, 0);
patternsButtonsContainer[a].setClickable(true);
patternLayout[a].addView(patternsButtonsContainer[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
patternsCancelButton[a] = new TextView(context);
patternsCancelButton[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
patternsCancelButton[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
patternsCancelButton[a].setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
patternsCancelButton[a].setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
patternsCancelButton[a].setGravity(Gravity.CENTER);
patternsCancelButton[a].setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
patternsCancelButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 0));
patternsButtonsContainer[a].addView(patternsCancelButton[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
patternsCancelButton[a].setOnClickListener(v -> {
if (patternViewAnimation != null) {
return;
}
if (num == 0) {
backgroundRotation = previousBackgroundRotation;
setBackgroundColor(previousBackgroundGradientColor3, 3, true, true);
setBackgroundColor(previousBackgroundGradientColor2, 2, true, true);
setBackgroundColor(previousBackgroundGradientColor1, 1, true, true);
setBackgroundColor(previousBackgroundColor, 0, true, true);
} else {
selectedPattern = previousSelectedPattern;
if (selectedPattern == null) {
backgroundImage.setImageDrawable(null);
} else {
backgroundImage.setImage(ImageLocation.getForDocument(selectedPattern.document), imageFilter, null, null, "jpg", selectedPattern.document.size, 1, selectedPattern);
}
backgroundCheckBoxView[1].setChecked(selectedPattern != null, false);
currentIntensity = previousIntensity;
intensitySeekBar.setProgress(currentIntensity);
backgroundImage.getImageReceiver().setAlpha(currentIntensity);
updateButtonState(false, true);
updateSelectedPattern(true);
}
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
showPatternsView(num, false, true);
} else {
if (selectedPattern == null) {
if (isMotion) {
isMotion = false;
backgroundCheckBoxView[0].setChecked(false, true);
animateMotionChange();
}
updateMotionButton();
}
showPatternsView(0, true, true);
}
});
patternsSaveButton[a] = new TextView(context);
patternsSaveButton[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
patternsSaveButton[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
patternsSaveButton[a].setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
patternsSaveButton[a].setText(LocaleController.getString("ApplyTheme", R.string.ApplyTheme).toUpperCase());
patternsSaveButton[a].setGravity(Gravity.CENTER);
patternsSaveButton[a].setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
patternsSaveButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 0));
patternsButtonsContainer[a].addView(patternsSaveButton[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP));
patternsSaveButton[a].setOnClickListener(v -> {
if (patternViewAnimation != null) {
return;
}
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
showPatternsView(num, false, true);
} else {
showPatternsView(0, true, true);
}
});
}
if (a == 1) {
TextView titleView = new TextView(context);
titleView.setLines(1);
titleView.setSingleLine(true);
titleView.setText(LocaleController.getString("BackgroundChoosePattern", R.string.BackgroundChoosePattern));
titleView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8));
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setGravity(Gravity.CENTER_VERTICAL);
patternLayout[a].addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP, 0, 21, 0, 0));
patternsListView = new RecyclerListView(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.onTouchEvent(event);
}
};
patternsListView.setLayoutManager(patternsLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
patternsListView.setAdapter(patternsAdapter = new PatternsAdapter(context));
patternsListView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
outRect.left = AndroidUtilities.dp(12);
outRect.bottom = outRect.top = 0;
if (position == state.getItemCount() - 1) {
outRect.right = AndroidUtilities.dp(12);
}
}
});
patternLayout[a].addView(patternsListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.TOP, 0, 76, 0, 0));
patternsListView.setOnItemClickListener((view, position) -> {
boolean previousMotion = selectedPattern != null;
selectPattern(position);
if (previousMotion == (selectedPattern == null)) {
animateMotionChange();
updateMotionButton();
}
updateSelectedPattern(true);
backgroundCheckBoxView[1].setChecked(selectedPattern != null, true);
patternsListView.invalidateViews();
int left = view.getLeft();
int right = view.getRight();
int extra = AndroidUtilities.dp(52);
if (left - extra < 0) {
patternsListView.smoothScrollBy(left - extra, 0);
} else if (right + extra > patternsListView.getMeasuredWidth()) {
patternsListView.smoothScrollBy(right + extra - patternsListView.getMeasuredWidth(), 0);
}
});
intensityCell = new HeaderCell(context);
intensityCell.setText(LocaleController.getString("BackgroundIntensity", R.string.BackgroundIntensity));
patternLayout[a].addView(intensityCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 175, 0, 0));
intensitySeekBar = new SeekBarView(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.onTouchEvent(event);
}
};
intensitySeekBar.setProgress(currentIntensity);
intensitySeekBar.setReportChanges(true);
intensitySeekBar.setDelegate(new SeekBarView.SeekBarViewDelegate() {
@Override
public void onSeekBarDrag(boolean stop, float progress) {
currentIntensity = progress;
backgroundImage.getImageReceiver().setAlpha(Math.abs(currentIntensity));
backgroundImage.invalidate();
patternsListView.invalidateViews();
if (currentIntensity >= 0) {
if (Build.VERSION.SDK_INT >= 29 && backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
backgroundImage.getImageReceiver().setBlendMode(BlendMode.SOFT_LIGHT);
}
backgroundImage.getImageReceiver().setGradientBitmap(null);
} else {
if (Build.VERSION.SDK_INT >= 29) {
backgroundImage.getImageReceiver().setBlendMode(null);
}
if (backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) backgroundImage.getBackground();
backgroundImage.getImageReceiver().setGradientBitmap(motionBackgroundDrawable.getBitmap());
}
}
}
@Override
public void onSeekBarPressed(boolean pressed) {
}
});
patternLayout[a].addView(intensitySeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 5, 211, 5, 0));
} else {
colorPicker = new ColorPicker(context, editingTheme, new ColorPicker.ColorPickerDelegate() {
@Override
public void setColor(int color, int num, boolean applyNow) {
if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
setBackgroundColor(color, num, applyNow, true);
} else {
scheduleApplyColor(color, num, applyNow);
}
}
@Override
public void openThemeCreate(boolean share) {
if (share) {
if (accent.info == null) {
finishFragment();
MessagesController.getInstance(currentAccount).saveThemeToServer(accent.parentTheme, accent);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needShareTheme, accent.parentTheme, accent);
} else {
String link = "https://" + MessagesController.getInstance(currentAccount).linkPrefix + "/addtheme/" + accent.info.slug;
showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false));
}
} else {
AlertsCreator.createThemeCreateDialog(ThemePreviewActivity.this, 1, null, null);
}
}
@Override
public void deleteTheme() {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
builder1.setTitle(LocaleController.getString("DeleteThemeTitle", R.string.DeleteThemeTitle));
builder1.setMessage(LocaleController.getString("DeleteThemeAlert", R.string.DeleteThemeAlert));
builder1.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
Theme.deleteThemeAccent(applyingTheme, accent, true);
Theme.applyPreviousTheme();
Theme.refreshThemeColors();
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, applyingTheme, nightTheme, null, -1);
finishFragment();
});
builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
AlertDialog alertDialog = builder1.create();
showDialog(alertDialog);
TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if (button != null) {
button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
}
}
@Override
public void rotateColors() {
onColorsRotate();
}
@Override
public int getDefaultColor(int num) {
if (colorType == 3 && applyingTheme.firstAccentIsDefault && num == 0) {
Theme.ThemeAccent accent = applyingTheme.themeAccentsMap.get(Theme.DEFALT_THEME_ACCENT_ID);
return accent != null ? accent.myMessagesAccentColor : 0;
}
return 0;
}
@Override
public boolean hasChanges() {
return ThemePreviewActivity.this.hasChanges(colorType);
}
});
if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
patternLayout[a].addView(colorPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL));
if (applyingTheme.isDark()) {
colorPicker.setMinBrightness(0.2f);
} else {
colorPicker.setMinBrightness(0.05f);
colorPicker.setMaxBrightness(0.8f);
}
int colorsCount = accent.accentColor2 != 0 ? 2 : 1;
colorPicker.setType(1, hasChanges(1), 2, colorsCount, false, 0, false);
colorPicker.setColor(accent.accentColor, 0);
if (accent.accentColor2 != 0) {
colorPicker.setColor(accent.accentColor2, 1);
}
} else {
patternLayout[a].addView(colorPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL, 0, 0, 0, 48));
}
}
}
}
updateButtonState(false, false);
if (!backgroundImage.getImageReceiver().hasBitmapImage()) {
page2.setBackgroundColor(0xff000000);
}
if (screenType != SCREEN_TYPE_ACCENT_COLOR && !(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
backgroundImage.getImageReceiver().setCrossfadeWithOldImage(true);
}
}
listView2.setAdapter(messagesAdapter);
frameLayout = new FrameLayout(context) {
private int[] loc = new int[2];
@Override
public void invalidate() {
super.invalidate();
if (page2 != null) {
page2.invalidate();
}
}
@Override
protected void onDraw(Canvas canvas) {
if (!AndroidUtilities.usingHardwareInput) {
getLocationInWindow(loc);
if (Build.VERSION.SDK_INT < 21 && !AndroidUtilities.isTablet()) {
loc[1] -= AndroidUtilities.statusBarHeight;
}
if (actionBar2.getTranslationY() != loc[1]) {
actionBar2.setTranslationY(-loc[1]);
page2.invalidate();
}
if (SystemClock.elapsedRealtime() < watchForKeyboardEndTime) {
invalidate();
}
}
}
};
frameLayout.setWillNotDraw(false);
fragmentView = frameLayout;
frameLayout.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = () -> {
watchForKeyboardEndTime = SystemClock.elapsedRealtime() + 1500;
frameLayout.invalidate();
});
viewPager = new ViewPager(context);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
dotsContainer.invalidate();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return screenType != SCREEN_TYPE_PREVIEW ? 1 : 2;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return object == view;
}
@Override
public int getItemPosition(Object object) {
return POSITION_UNCHANGED;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = position == 0 ? page2 : page1;
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
});
AndroidUtilities.setViewPagerEdgeEffectColor(viewPager, Theme.getColor(Theme.key_actionBarDefault));
frameLayout.addView(viewPager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, screenType == SCREEN_TYPE_PREVIEW ? 48 : 0));
undoView = new UndoView(context, this);
undoView.setAdditionalTranslationY(AndroidUtilities.dp(51));
frameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
if (screenType == SCREEN_TYPE_PREVIEW) {
View shadow = new View(context);
shadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine));
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, Gravity.LEFT | Gravity.BOTTOM);
layoutParams.bottomMargin = AndroidUtilities.dp(48);
frameLayout.addView(shadow, layoutParams);
saveButtonsContainer = new FrameLayout(context);
saveButtonsContainer.setBackgroundColor(getButtonsColor(Theme.key_windowBackgroundWhite));
frameLayout.addView(saveButtonsContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
dotsContainer = new View(context) {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
@Override
protected void onDraw(Canvas canvas) {
int selected = viewPager.getCurrentItem();
paint.setColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
for (int a = 0; a < 2; a++) {
paint.setAlpha(a == selected ? 255 : 127);
canvas.drawCircle(AndroidUtilities.dp(3 + 15 * a), AndroidUtilities.dp(4), AndroidUtilities.dp(3), paint);
}
}
};
saveButtonsContainer.addView(dotsContainer, LayoutHelper.createFrame(22, 8, Gravity.CENTER));
cancelButton = new TextView(context);
cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
cancelButton.setTextColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
cancelButton.setGravity(Gravity.CENTER);
cancelButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x0f000000, 0));
cancelButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
cancelButton.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
cancelButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
saveButtonsContainer.addView(cancelButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
cancelButton.setOnClickListener(v -> cancelThemeApply(false));
doneButton = new TextView(context);
doneButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
doneButton.setTextColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
doneButton.setGravity(Gravity.CENTER);
doneButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x0f000000, 0));
doneButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
doneButton.setText(LocaleController.getString("ApplyTheme", R.string.ApplyTheme).toUpperCase());
doneButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
saveButtonsContainer.addView(doneButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
doneButton.setOnClickListener(v -> {
Theme.ThemeInfo previousTheme = Theme.getPreviousTheme();
if (previousTheme == null) {
return;
}
Theme.ThemeAccent previousAccent;
if (previousTheme != null && previousTheme.prevAccentId >= 0) {
previousAccent = previousTheme.themeAccentsMap.get(previousTheme.prevAccentId);
} else {
previousAccent = previousTheme.getAccent(false);
}
if (accent != null) {
saveAccentWallpaper();
Theme.saveThemeAccents(applyingTheme, true, false, false, false);
Theme.clearPreviousTheme();
Theme.applyTheme(applyingTheme, nightTheme);
parentLayout.rebuildAllFragmentViews(false, false);
} else {
parentLayout.rebuildAllFragmentViews(false, false);
Theme.applyThemeFile(new File(applyingTheme.pathToFile), applyingTheme.name, applyingTheme.info, false);
MessagesController.getInstance(applyingTheme.account).saveTheme(applyingTheme, null, false, false);
SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE).edit();
editor.putString("lastDayTheme", applyingTheme.getKey());
editor.commit();
}
finishFragment();
if (screenType == SCREEN_TYPE_PREVIEW) {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didApplyNewTheme, previousTheme, previousAccent, deleteOnCancel);
}
});
}
if (screenType == SCREEN_TYPE_ACCENT_COLOR && !Theme.hasCustomWallpaper() && accent.backgroundOverrideColor != 0x100000000L) {
selectColorType(2);
}
themeDescriptions = getThemeDescriptionsInternal();
setCurrentImage(true);
updatePlayAnimationView(false);
if (showColor) {
showPatternsView(0, true, false);
}
return fragmentView;
}
use of org.telegram.ui.ActionBar.ActionBarMenuItem in project Telegram-FOSS by Telegram-FOSS-Team.
the class WebviewActivity method createView.
@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
@Override
public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == share) {
if (currentMessageObject != null) {
currentMessageObject.messageOwner.with_my_score = false;
showDialog(ShareAlert.createShareAlert(getParentActivity(), currentMessageObject, null, false, linkToCopy, false));
}
} else if (id == open_in) {
openGameInBrowser(currentUrl, currentMessageObject, getParentActivity(), short_param, currentBot);
}
}
});
ActionBarMenu menu = actionBar.createMenu();
progressItem = menu.addItemWithWidth(share, R.drawable.share, AndroidUtilities.dp(54));
if (type == TYPE_GAME) {
ActionBarMenuItem menuItem = menu.addItem(0, R.drawable.ic_ab_other);
menuItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
actionBar.setTitle(currentGame);
actionBar.setSubtitle("@" + currentBot);
progressView = new ContextProgressView(context, 1);
progressItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
progressView.setAlpha(0.0f);
progressView.setScaleX(0.1f);
progressView.setScaleY(0.1f);
progressView.setVisibility(View.INVISIBLE);
} else if (type == TYPE_STAT) {
actionBar.setBackgroundColor(Theme.getColor(Theme.key_player_actionBar));
actionBar.setItemsColor(Theme.getColor(Theme.key_player_actionBarItems), false);
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_player_actionBarSelector), false);
actionBar.setTitleColor(Theme.getColor(Theme.key_player_actionBarTitle));
actionBar.setSubtitleColor(Theme.getColor(Theme.key_player_actionBarSubtitle));
actionBar.setTitle(LocaleController.getString("Statistics", R.string.Statistics));
progressView = new ContextProgressView(context, 3);
progressItem.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
progressView.setAlpha(1.0f);
progressView.setScaleX(1.0f);
progressView.setScaleY(1.0f);
progressView.setVisibility(View.VISIBLE);
progressItem.getContentView().setVisibility(View.GONE);
progressItem.setEnabled(false);
}
webView = new WebView(context);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
fragmentView = new FrameLayout(context);
FrameLayout frameLayout = (FrameLayout) fragmentView;
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
if (Build.VERSION.SDK_INT >= 21) {
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
if (type == TYPE_GAME) {
webView.addJavascriptInterface(new TelegramWebviewProxy(), "TelegramWebviewProxy");
}
}
webView.setWebViewClient(new WebViewClient() {
private boolean isInternalUrl(String url) {
if (TextUtils.isEmpty(url)) {
return false;
}
Uri uri = Uri.parse(url);
if ("tg".equals(uri.getScheme())) {
if (type == TYPE_STAT) {
try {
uri = Uri.parse(url.replace("tg:statsrefresh", "tg://telegram.org"));
reloadStats(uri.getQueryParameter("params"));
} catch (Throwable e) {
FileLog.e(e);
}
} else {
finishFragment(false);
try {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
ComponentName componentName = new ComponentName(ApplicationLoader.applicationContext.getPackageName(), LaunchActivity.class.getName());
intent.setComponent(componentName);
intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, ApplicationLoader.applicationContext.getPackageName());
ApplicationLoader.applicationContext.startActivity(intent);
} catch (Exception e) {
FileLog.e(e);
}
}
return true;
}
return false;
}
@Override
public void onLoadResource(WebView view, String url) {
if (isInternalUrl(url)) {
return;
}
super.onLoadResource(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return isInternalUrl(url) || super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressView != null && progressView.getVisibility() == View.VISIBLE) {
AnimatorSet animatorSet = new AnimatorSet();
if (type == TYPE_GAME) {
progressItem.getContentView().setVisibility(View.VISIBLE);
progressItem.setEnabled(true);
animatorSet.playTogether(ObjectAnimator.ofFloat(progressView, "scaleX", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "scaleY", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "alpha", 1.0f, 0.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "scaleX", 0.0f, 1.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "scaleY", 0.0f, 1.0f), ObjectAnimator.ofFloat(progressItem.getContentView(), "alpha", 0.0f, 1.0f));
} else {
animatorSet.playTogether(ObjectAnimator.ofFloat(progressView, "scaleX", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "scaleY", 1.0f, 0.1f), ObjectAnimator.ofFloat(progressView, "alpha", 1.0f, 0.0f));
}
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
if (type == TYPE_STAT) {
progressItem.setVisibility(View.GONE);
} else {
progressView.setVisibility(View.INVISIBLE);
}
}
});
animatorSet.setDuration(150);
animatorSet.start();
}
}
});
frameLayout.addView(webView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
return fragmentView;
}
use of org.telegram.ui.ActionBar.ActionBarMenuItem in project Telegram-FOSS by Telegram-FOSS-Team.
the class LocationActivity method createView.
@Override
public View createView(Context context) {
searchWas = false;
searching = false;
searchInProgress = false;
if (adapter != null) {
adapter.destroy();
}
if (searchAdapter != null) {
searchAdapter.destroy();
}
if (chatLocation != null) {
userLocation = new Location("network");
userLocation.setLatitude(chatLocation.geo_point.lat);
userLocation.setLongitude(chatLocation.geo_point._long);
} else if (messageObject != null) {
userLocation = new Location("network");
userLocation.setLatitude(messageObject.messageOwner.media.geo.lat);
userLocation.setLongitude(messageObject.messageOwner.media.geo._long);
}
locationDenied = Build.VERSION.SDK_INT >= 23 && getParentActivity() != null && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack));
actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false);
actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
actionBar.setAddToContainer(false);
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == open_in) {
try {
double lat = messageObject.messageOwner.media.geo.lat;
double lon = messageObject.messageOwner.media.geo._long;
getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon)));
} catch (Exception e) {
FileLog.e(e);
}
} else if (id == share_live_location) {
openShareLiveLocation(0);
}
}
});
ActionBarMenu menu = actionBar.createMenu();
if (chatLocation != null) {
actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
} else if (messageObject != null) {
if (messageObject.isLiveLocation()) {
actionBar.setTitle(LocaleController.getString("AttachLiveLocation", R.string.AttachLiveLocation));
} else {
if (messageObject.messageOwner.media.title != null && messageObject.messageOwner.media.title.length() > 0) {
actionBar.setTitle(LocaleController.getString("SharedPlace", R.string.SharedPlace));
} else {
actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
}
otherItem = menu.addItem(0, R.drawable.ic_ab_other);
otherItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
if (!getLocationController().isSharingLocation(dialogId)) {
otherItem.addSubItem(share_live_location, R.drawable.menu_location, LocaleController.getString("SendLiveLocationMenu", R.string.SendLiveLocationMenu));
}
otherItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
}
} else {
actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation));
if (locationType != LOCATION_TYPE_GROUP) {
overlayView = new MapOverlayView(context);
searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
@Override
public void onSearchExpand() {
searching = true;
}
@Override
public void onSearchCollapse() {
searching = false;
searchWas = false;
searchAdapter.searchDelayed(null, null);
updateEmptyView();
}
@Override
public void onTextChanged(EditText editText) {
if (searchAdapter == null) {
return;
}
String text = editText.getText().toString();
if (text.length() != 0) {
searchWas = true;
searchItem.setShowSearchProgress(true);
if (otherItem != null) {
otherItem.setVisibility(View.GONE);
}
listView.setVisibility(View.GONE);
mapViewClip.setVisibility(View.GONE);
if (searchListView.getAdapter() != searchAdapter) {
searchListView.setAdapter(searchAdapter);
}
searchListView.setVisibility(View.VISIBLE);
searchInProgress = searchAdapter.getItemCount() == 0;
} else {
if (otherItem != null) {
otherItem.setVisibility(View.VISIBLE);
}
listView.setVisibility(View.VISIBLE);
mapViewClip.setVisibility(View.VISIBLE);
searchListView.setAdapter(null);
searchListView.setVisibility(View.GONE);
}
updateEmptyView();
searchAdapter.searchDelayed(text, userLocation);
}
});
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
EditTextBoldCursor editText = searchItem.getSearchField();
editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
editText.setCursorColor(Theme.getColor(Theme.key_dialogTextBlack));
editText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint));
}
}
fragmentView = new FrameLayout(context) {
private boolean first = true;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
fixLayoutInternal(first);
first = false;
} else {
updateClipView(true);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == actionBar && parentLayout != null) {
parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
}
return result;
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
fragmentView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY));
Rect padding = new Rect();
shadowDrawable.getPadding(padding);
FrameLayout.LayoutParams layoutParams;
if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(21) + padding.top);
} else {
layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(6) + padding.top);
}
layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
mapViewClip = new FrameLayout(context) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (overlayView != null) {
overlayView.updatePositions();
}
}
};
mapViewClip.setBackgroundDrawable(new MapPlaceholderDrawable());
if (messageObject == null && (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE)) {
searchAreaButton = new SearchButton(context);
searchAreaButton.setTranslationX(-AndroidUtilities.dp(80));
Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.places_btn).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, AndroidUtilities.dp(2), AndroidUtilities.dp(2));
combinedDrawable.setFullsize(true);
drawable = combinedDrawable;
} else {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[] {}, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
searchAreaButton.setStateListAnimator(animator);
searchAreaButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), view.getMeasuredHeight() / 2);
}
});
}
searchAreaButton.setBackgroundDrawable(drawable);
searchAreaButton.setTextColor(Theme.getColor(Theme.key_location_actionActiveIcon));
searchAreaButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
searchAreaButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
searchAreaButton.setText(LocaleController.getString("PlacesInThisArea", R.string.PlacesInThisArea));
searchAreaButton.setGravity(Gravity.CENTER);
searchAreaButton.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
mapViewClip.addView(searchAreaButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 80, 12, 80, 0));
searchAreaButton.setOnClickListener(v -> {
showSearchPlacesButton(false);
adapter.searchPlacesWithQuery(null, userLocation, true, true);
searchedForCustomLocations = true;
showResults();
});
}
mapTypeButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_location_actionIcon));
mapTypeButton.setClickable(true);
mapTypeButton.setSubMenuOpenSide(2);
mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10));
mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10));
mapTypeButton.addSubItem(map_list_menu_osm, R.drawable.msg_map, "Standard OSM");
mapTypeButton.addSubItem(map_list_menu_wiki, R.drawable.msg_map, "Wikimedia");
mapTypeButton.addSubItem(map_list_menu_cartodark, R.drawable.msg_map, "Carto Dark");
mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
drawable = combinedDrawable;
} else {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[] {}, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
mapTypeButton.setStateListAnimator(animator);
mapTypeButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
}
});
}
mapTypeButton.setBackgroundDrawable(drawable);
mapTypeButton.setIcon(R.drawable.location_type);
mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0));
mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu());
mapTypeButton.setDelegate(id -> {
if (mapView == null) {
return;
}
if (id == map_list_menu_osm) {
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
mapView.setTileSource(TileSourceFactory.MAPNIK);
} else if (id == map_list_menu_wiki) {
// Create a custom tile source
ITileSource tileSource = new XYTileSource("Wikimedia", 0, 19, 256, ".png", new String[] { "https://maps.wikimedia.org/osm-intl/" }, "© OpenStreetMap contributors");
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
mapView.setTileSource(tileSource);
} else if (id == map_list_menu_cartodark) {
// Create a custom tile source
ITileSource tileSource = new XYTileSource("Carto Dark", 0, 20, 256, ".png", new String[] { "https://cartodb-basemaps-a.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-b.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-d.global.ssl.fastly.net/dark_all/" }, "© OpenStreetMap contributors, © CARTO");
attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, © <a href=\"https://carto.com/attributions\">CARTO</a>"));
mapView.setTileSource(tileSource);
}
});
mapViewClip.addView(getAttributionOverlay(context), LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM, LocaleController.isRTL ? 0 : 4, 0, LocaleController.isRTL ? 4 : 0, 20));
locationButton = new ImageView(context);
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
drawable = combinedDrawable;
} else {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[] {}, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
locationButton.setStateListAnimator(animator);
locationButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
}
});
}
locationButton.setBackgroundDrawable(drawable);
locationButton.setImageResource(R.drawable.location_current);
locationButton.setScaleType(ImageView.ScaleType.CENTER);
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionActiveIcon);
locationButton.setContentDescription(LocaleController.getString("AccDescrMyLocation", R.string.AccDescrMyLocation));
FrameLayout.LayoutParams layoutParams1 = LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 12);
layoutParams1.bottomMargin += layoutParams.height - padding.top;
mapViewClip.addView(locationButton, layoutParams1);
locationButton.setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= 23) {
Activity activity = getParentActivity();
if (activity != null) {
if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
showPermissionAlert(false);
return;
}
}
}
if (!checkGpsEnabled()) {
return;
}
if (messageObject != null || chatLocation != null) {
if (myLocation != null && mapView != null) {
final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()), mapView.getMaxZoomLevel() - 2, null);
}
} else {
if (myLocation != null && mapView != null) {
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionActiveIcon);
adapter.setCustomLocation(null);
userLocationMoved = false;
showSearchPlacesButton(false);
final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()));
if (searchedForCustomLocations) {
if (myLocation != null) {
adapter.searchPlacesWithQuery(null, myLocation, true, true);
}
searchedForCustomLocations = false;
showResults();
}
}
}
removeInfoView();
});
proximityButton = new ImageView(context);
drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
if (Build.VERSION.SDK_INT < 21) {
Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
drawable = combinedDrawable;
} else {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[] {}, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
proximityButton.setStateListAnimator(animator);
proximityButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
}
});
}
proximityButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
proximityButton.setBackgroundDrawable(drawable);
proximityButton.setScaleType(ImageView.ScaleType.CENTER);
proximityButton.setContentDescription(LocaleController.getString("AccDescrLocationNotify", R.string.AccDescrLocationNotify));
mapViewClip.addView(proximityButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12 + 50, 12, 0));
proximityButton.setOnClickListener(v -> {
if (getParentActivity() == null || myLocation == null || !checkGpsEnabled() || mapView == null) {
return;
}
if (hintView != null) {
hintView.hide();
}
SharedPreferences preferences = MessagesController.getGlobalMainSettings();
preferences.edit().putInt("proximityhint", 3).commit();
LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId);
if (canUndo) {
undoView[0].hide(true, 1);
}
if (info != null && info.proximityMeters > 0) {
proximityButton.setImageResource(R.drawable.msg_location_alert);
if (proximityCircle != null) {
mapView.getOverlayManager().remove(proximityCircle);
proximityCircle = null;
}
canUndo = true;
getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_REMOVED, 0, null, () -> {
getLocationController().setProximityLocation(dialogId, 0, true);
canUndo = false;
}, () -> {
proximityButton.setImageResource(R.drawable.msg_location_alert2);
createCircle(info.proximityMeters);
canUndo = false;
});
return;
}
openProximityAlert();
});
TLRPC.Chat chat = null;
if (DialogObject.isChatDialog(dialogId)) {
chat = getMessagesController().getChat(-dialogId);
}
if (messageObject == null || !messageObject.isLiveLocation() || messageObject.isExpiredLiveLocation(getConnectionsManager().getCurrentTime()) || ChatObject.isChannel(chat) && !chat.megagroup) {
proximityButton.setVisibility(View.GONE);
proximityButton.setImageResource(R.drawable.msg_location_alert);
} else {
LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId);
if (myInfo != null && myInfo.proximityMeters > 0) {
proximityButton.setImageResource(R.drawable.msg_location_alert2);
} else {
if (DialogObject.isUserDialog(dialogId) && messageObject.getFromChatId() == getUserConfig().getClientUserId()) {
proximityButton.setVisibility(View.INVISIBLE);
proximityButton.setAlpha(0.0f);
proximityButton.setScaleX(0.4f);
proximityButton.setScaleY(0.4f);
}
proximityButton.setImageResource(R.drawable.msg_location_alert);
}
}
hintView = new HintView(context, 6, true);
hintView.setVisibility(View.INVISIBLE);
hintView.setShowingDuration(4000);
mapViewClip.addView(hintView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0));
emptyView = new LinearLayout(context);
emptyView.setOrientation(LinearLayout.VERTICAL);
emptyView.setGravity(Gravity.CENTER_HORIZONTAL);
emptyView.setPadding(0, AndroidUtilities.dp(60 + 100), 0, 0);
emptyView.setVisibility(View.GONE);
frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
emptyView.setOnTouchListener((v, event) -> true);
emptyImageView = new ImageView(context);
emptyImageView.setImageResource(R.drawable.location_empty);
emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY));
emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
emptyTitleTextView = new TextView(context);
emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
emptyTitleTextView.setGravity(Gravity.CENTER);
emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
emptyTitleTextView.setText(LocaleController.getString("NoPlacesFound", R.string.NoPlacesFound));
emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0));
emptySubtitleTextView = new TextView(context);
emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
emptySubtitleTextView.setGravity(Gravity.CENTER);
emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0));
listView = new RecyclerListView(context);
listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false, null) {
@Override
protected void onDirectionClick() {
if (Build.VERSION.SDK_INT >= 23) {
Activity activity = getParentActivity();
if (activity != null) {
if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
showPermissionAlert(true);
return;
}
}
}
if (myLocation != null) {
try {
Intent intent;
if (messageObject != null) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long)));
} else {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), chatLocation.geo_point.lat, chatLocation.geo_point._long)));
}
getParentActivity().startActivity(intent);
} catch (Exception e) {
FileLog.e(e);
}
}
}
});
adapter.setMyLocationDenied(locationDenied);
adapter.setUpdateRunnable(() -> updateClipView(false));
listView.setVerticalScrollBarEnabled(false);
listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
scrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
if (!scrolling && forceUpdate != null) {
forceUpdate = null;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
updateClipView(false);
if (forceUpdate != null) {
yOffset += dy;
}
}
});
((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false);
listView.setOnItemClickListener((view, position) -> {
if (locationType == LOCATION_TYPE_GROUP) {
if (position == 1) {
TLRPC.TL_messageMediaVenue venue = (TLRPC.TL_messageMediaVenue) adapter.getItem(position);
if (venue == null) {
return;
}
if (dialogId == 0) {
delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
finishFragment();
} else {
final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(getParentActivity(), 3) };
TLRPC.TL_channels_editLocation req = new TLRPC.TL_channels_editLocation();
req.address = venue.address;
req.channel = getMessagesController().getInputChannel(-dialogId);
req.geo_point = new TLRPC.TL_inputGeoPoint();
req.geo_point.lat = venue.geo.lat;
req.geo_point._long = venue.geo._long;
int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog[0].dismiss();
} catch (Throwable ignore) {
}
progressDialog[0] = null;
delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
finishFragment();
}));
progressDialog[0].setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(requestId, true));
showDialog(progressDialog[0]);
}
}
} else if (locationType == LOCATION_TYPE_GROUP_VIEW) {
if (mapView != null) {
final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(chatLocation.geo_point.lat, chatLocation.geo_point._long), mapView.getMaxZoomLevel() - 2, null);
}
} else if (position == 1 && messageObject != null && (!messageObject.isLiveLocation() || locationType == LOCATION_TYPE_LIVE_VIEW)) {
if (mapView != null) {
final IMapController controller = mapView.getController();
controller.animateTo(new GeoPoint(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long), mapView.getMaxZoomLevel() - 2, null);
}
} else if (position == 1 && locationType != 2) {
if (delegate != null && userLocation != null) {
if (lastPressedMarkerView != null) {
lastPressedMarkerView.callOnClick();
} else {
TLRPC.TL_messageMediaGeo location = new TLRPC.TL_messageMediaGeo();
location.geo = new TLRPC.TL_geoPoint();
location.geo.lat = AndroidUtilities.fixLocationCoord(userLocation.getLatitude());
location.geo._long = AndroidUtilities.fixLocationCoord(userLocation.getLongitude());
if (parentFragment != null && parentFragment.isInScheduleMode()) {
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
delegate.didSelectLocation(location, locationType, notify, scheduleDate);
finishFragment();
});
} else {
delegate.didSelectLocation(location, locationType, true, 0);
finishFragment();
}
}
}
} else if (position == 2 && locationType == 1 || position == 1 && locationType == 2 || position == 3 && locationType == 3) {
if (getLocationController().isSharingLocation(dialogId)) {
getLocationController().removeSharingLocation(dialogId);
finishFragment();
} else {
openShareLiveLocation(0);
}
} else {
Object object = adapter.getItem(position);
if (object instanceof TLRPC.TL_messageMediaVenue) {
if (parentFragment != null && parentFragment.isInScheduleMode()) {
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, notify, scheduleDate);
finishFragment();
});
} else {
delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, true, 0);
finishFragment();
}
} else if (object instanceof LiveLocation) {
LiveLocation liveLocation = (LiveLocation) object;
final IMapController controller = mapView.getController();
controller.animateTo(liveLocation.marker.getPosition(), mapView.getMaxZoomLevel() - 2, null);
}
}
});
adapter.setDelegate(dialogId, this::updatePlacesMarkers);
adapter.setOverScrollHeight(overScrollHeight);
frameLayout.addView(mapViewClip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
mapView = new MapView(context) {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
MotionEvent eventToRecycle = null;
if (yOffset != 0) {
ev = eventToRecycle = MotionEvent.obtain(ev);
eventToRecycle.offsetLocation(0, -yOffset / 2);
}
boolean result = super.dispatchTouchEvent(ev);
if (eventToRecycle != null) {
eventToRecycle.recycle();
}
return result;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (messageObject == null && chatLocation == null) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (animatorSet != null) {
animatorSet.cancel();
}
animatorSet = new AnimatorSet();
animatorSet.setDuration(200);
animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop - AndroidUtilities.dp(10)));
animatorSet.start();
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
if (animatorSet != null) {
animatorSet.cancel();
}
yOffset = 0;
animatorSet = new AnimatorSet();
animatorSet.setDuration(200);
animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop));
animatorSet.start();
adapter.fetchLocationAddress();
}
if (ev.getAction() == MotionEvent.ACTION_MOVE) {
if (!userLocationMoved) {
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionIcon);
userLocationMoved = true;
}
if (mapView != null) {
if (userLocation != null) {
userLocation.setLatitude(mapView.getMapCenter().getLatitude());
userLocation.setLongitude(mapView.getMapCenter().getLongitude());
}
}
adapter.setCustomLocation(userLocation);
}
}
return super.onTouchEvent(ev);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
AndroidUtilities.runOnUIThread(() -> {
if (moveToBounds != null) {
mapView.zoomToBoundingBox(moveToBounds, false, AndroidUtilities.dp(80 + 33));
moveToBounds = null;
}
});
}
};
AndroidUtilities.runOnUIThread(() -> {
if (mapView != null && getParentActivity() != null) {
mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
onMapInit();
mapsInitialized = true;
if (isActiveThemeDark()) {
/*currentMapStyleDark = true;
MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night);
googleMap.setMapStyle(style);
*/
// TODO Dark?
}
if (onResumeCalled) {
mapView.onResume();
}
}
});
if (messageObject == null && chatLocation == null) {
if (chat != null && locationType == LOCATION_TYPE_GROUP && dialogId != 0) {
FrameLayout frameLayout1 = new FrameLayout(context);
frameLayout1.setBackgroundResource(R.drawable.livepin);
mapViewClip.addView(frameLayout1, LayoutHelper.createFrame(62, 76, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
BackupImageView backupImageView = new BackupImageView(context);
backupImageView.setRoundRadius(AndroidUtilities.dp(26));
backupImageView.setForUserOrChat(chat, new AvatarDrawable(chat));
frameLayout1.addView(backupImageView, LayoutHelper.createFrame(52, 52, Gravity.LEFT | Gravity.TOP, 5, 5, 0, 0));
markerImageView = frameLayout1;
markerImageView.setTag(1);
}
if (markerImageView == null) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(R.drawable.map_pin2);
mapViewClip.addView(imageView, LayoutHelper.createFrame(28, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
markerImageView = imageView;
}
searchListView = new RecyclerListView(context);
searchListView.setVisibility(View.GONE);
searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
searchAdapter = new LocationActivitySearchAdapter(context) {
@Override
public void notifyDataSetChanged() {
if (searchItem != null) {
searchItem.setShowSearchProgress(searchAdapter.isSearching());
}
if (emptySubtitleTextView != null) {
emptySubtitleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("NoPlacesFoundInfo", R.string.NoPlacesFoundInfo, searchAdapter.getLastSearchString())));
}
super.notifyDataSetChanged();
}
};
searchAdapter.setDelegate(0, places -> {
searchInProgress = false;
updateEmptyView();
});
frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_DRAGGING && searching && searchWas) {
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}
});
searchListView.setOnItemClickListener((view, position) -> {
TLRPC.TL_messageMediaVenue object = searchAdapter.getItem(position);
if (object != null && delegate != null) {
if (parentFragment != null && parentFragment.isInScheduleMode()) {
AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
delegate.didSelectLocation(object, locationType, notify, scheduleDate);
finishFragment();
});
} else {
delegate.didSelectLocation(object, locationType, true, 0);
finishFragment();
}
}
});
} else if (messageObject != null && !messageObject.isLiveLocation() || chatLocation != null) {
if (chatLocation != null) {
adapter.setChatLocation(chatLocation);
} else if (messageObject != null) {
adapter.setMessageObject(messageObject);
}
}
if (messageObject != null && locationType == LOCATION_TYPE_LIVE_VIEW) {
adapter.setMessageObject(messageObject);
}
for (int a = 0; a < 2; a++) {
undoView[a] = new UndoView(context);
undoView[a].setAdditionalTranslationY(AndroidUtilities.dp(10));
if (Build.VERSION.SDK_INT >= 21) {
undoView[a].setTranslationZ(AndroidUtilities.dp(5));
}
mapViewClip.addView(undoView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
}
shadow = new View(context) {
private RectF rect = new RectF();
@Override
protected void onDraw(Canvas canvas) {
shadowDrawable.setBounds(-padding.left, 0, getMeasuredWidth() + padding.right, getMeasuredHeight());
shadowDrawable.draw(canvas);
if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
int w = AndroidUtilities.dp(36);
int y = padding.top + AndroidUtilities.dp(10);
rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4));
int color = Theme.getColor(Theme.key_sheet_scrollUp);
int alpha = Color.alpha(color);
Theme.dialogs_onlineCirclePaint.setColor(color);
canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
}
}
};
if (Build.VERSION.SDK_INT >= 21) {
shadow.setTranslationZ(AndroidUtilities.dp(6));
}
mapViewClip.addView(shadow, layoutParams);
if (messageObject == null && chatLocation == null && initialLocation != null) {
userLocationMoved = true;
locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
locationButton.setTag(Theme.key_location_actionIcon);
}
frameLayout.addView(actionBar);
updateEmptyView();
return fragmentView;
}
Aggregations