use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class MessagesController method didReceivedNotification.
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.fileUploaded) {
String location = (String) args[0];
TLRPC.InputFile file = (TLRPC.InputFile) args[1];
if (uploadingAvatar != null && uploadingAvatar.equals(location)) {
TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
req.file = file;
req.flags |= 1;
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error == null) {
TLRPC.User user = getUser(getUserConfig().getClientUserId());
if (user == null) {
user = getUserConfig().getCurrentUser();
putUser(user, true);
} else {
getUserConfig().setCurrentUser(user);
}
if (user == null) {
return;
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
}
getMessagesStorage().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
getMessagesStorage().putUsersAndChats(users, null, false, true);
AndroidUtilities.runOnUIThread(() -> {
getNotificationCenter().postNotificationName(NotificationCenter.mainUserInfoChanged);
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_AVATAR);
getUserConfig().saveConfig(true);
});
}
});
} else if (uploadingWallpaper != null && uploadingWallpaper.equals(location)) {
TLRPC.TL_account_uploadWallPaper req = new TLRPC.TL_account_uploadWallPaper();
req.file = file;
req.mime_type = "image/jpeg";
Theme.OverrideWallpaperInfo overrideWallpaperInfo = uploadingWallpaperInfo;
TLRPC.TL_wallPaperSettings settings = new TLRPC.TL_wallPaperSettings();
settings.blur = overrideWallpaperInfo.isBlurred;
settings.motion = overrideWallpaperInfo.isMotion;
req.settings = settings;
getConnectionsManager().sendRequest(req, (response, error) -> {
TLRPC.WallPaper wallPaper = (TLRPC.WallPaper) response;
File path = new File(ApplicationLoader.getFilesDirFixed(), overrideWallpaperInfo.originalFileName);
if (wallPaper != null) {
try {
AndroidUtilities.copyFile(path, FileLoader.getPathToAttach(wallPaper.document, true));
} catch (Exception ignore) {
}
}
AndroidUtilities.runOnUIThread(() -> {
if (uploadingWallpaper != null && wallPaper != null) {
wallPaper.settings = settings;
wallPaper.flags |= 4;
overrideWallpaperInfo.slug = wallPaper.slug;
overrideWallpaperInfo.saveOverrideWallpaper();
ArrayList<TLRPC.WallPaper> wallpapers = new ArrayList<>();
wallpapers.add(wallPaper);
getMessagesStorage().putWallpapers(wallpapers, 2);
TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(wallPaper.document.thumbs, 320);
if (image != null) {
String newKey = image.location.volume_id + "_" + image.location.local_id + "@100_100";
String oldKey = Utilities.MD5(path.getAbsolutePath()) + "@100_100";
ImageLoader.getInstance().replaceImageInCache(oldKey, newKey, ImageLocation.getForDocument(image, wallPaper.document), false);
}
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.wallpapersNeedReload, wallPaper.slug);
}
});
});
} else {
Object object = uploadingThemes.get(location);
Theme.ThemeInfo themeInfo;
Theme.ThemeAccent accent;
TLRPC.InputFile uploadedThumb;
TLRPC.InputFile uploadedFile;
if (object instanceof Theme.ThemeInfo) {
themeInfo = (Theme.ThemeInfo) object;
accent = null;
if (location.equals(themeInfo.uploadingThumb)) {
themeInfo.uploadedThumb = file;
themeInfo.uploadingThumb = null;
} else if (location.equals(themeInfo.uploadingFile)) {
themeInfo.uploadedFile = file;
themeInfo.uploadingFile = null;
}
uploadedThumb = themeInfo.uploadedThumb;
uploadedFile = themeInfo.uploadedFile;
} else if (object instanceof Theme.ThemeAccent) {
accent = (Theme.ThemeAccent) object;
if (location.equals(accent.uploadingThumb)) {
accent.uploadedThumb = file;
accent.uploadingThumb = null;
} else if (location.equals(accent.uploadingFile)) {
accent.uploadedFile = file;
accent.uploadingFile = null;
}
themeInfo = accent.parentTheme;
uploadedThumb = accent.uploadedThumb;
uploadedFile = accent.uploadedFile;
} else {
themeInfo = null;
accent = null;
uploadedThumb = null;
uploadedFile = null;
}
uploadingThemes.remove(location);
if (uploadedFile != null && uploadedThumb != null) {
File f = new File(location);
TLRPC.TL_account_uploadTheme req = new TLRPC.TL_account_uploadTheme();
req.mime_type = "application/x-tgtheme-android";
req.file_name = "theme.attheme";
req.file = uploadedFile;
req.file.name = "theme.attheme";
req.thumb = uploadedThumb;
req.thumb.name = "theme-preview.jpg";
req.flags |= 1;
TLRPC.TL_theme info;
TLRPC.TL_inputThemeSettings settings;
if (accent != null) {
accent.uploadedFile = null;
accent.uploadedThumb = null;
info = accent.info;
settings = new TLRPC.TL_inputThemeSettings();
settings.base_theme = Theme.getBaseThemeByKey(themeInfo.name);
settings.accent_color = accent.accentColor;
if (accent.accentColor2 != 0) {
settings.flags |= 8;
settings.outbox_accent_color = accent.accentColor2;
}
if (accent.myMessagesAccentColor != 0) {
settings.message_colors.add(accent.myMessagesAccentColor);
settings.flags |= 1;
if (accent.myMessagesGradientAccentColor1 != 0) {
settings.message_colors.add(accent.myMessagesGradientAccentColor1);
if (accent.myMessagesGradientAccentColor2 != 0) {
settings.message_colors.add(accent.myMessagesGradientAccentColor2);
if (accent.myMessagesGradientAccentColor3 != 0) {
settings.message_colors.add(accent.myMessagesGradientAccentColor3);
}
}
}
settings.message_colors_animated = accent.myMessagesAnimated;
}
settings.flags |= 2;
settings.wallpaper_settings = new TLRPC.TL_wallPaperSettings();
if (!TextUtils.isEmpty(accent.patternSlug)) {
TLRPC.TL_inputWallPaperSlug inputWallPaperSlug = new TLRPC.TL_inputWallPaperSlug();
inputWallPaperSlug.slug = accent.patternSlug;
settings.wallpaper = inputWallPaperSlug;
settings.wallpaper_settings.intensity = (int) (accent.patternIntensity * 100);
settings.wallpaper_settings.flags |= 8;
} else {
TLRPC.TL_inputWallPaperNoFile inputWallPaperNoFile = new TLRPC.TL_inputWallPaperNoFile();
inputWallPaperNoFile.id = 0;
settings.wallpaper = inputWallPaperNoFile;
}
settings.wallpaper_settings.motion = accent.patternMotion;
if (accent.backgroundOverrideColor != 0) {
settings.wallpaper_settings.background_color = (int) accent.backgroundOverrideColor;
settings.wallpaper_settings.flags |= 1;
}
if (accent.backgroundGradientOverrideColor1 != 0) {
settings.wallpaper_settings.second_background_color = (int) accent.backgroundGradientOverrideColor1;
settings.wallpaper_settings.flags |= 16;
settings.wallpaper_settings.rotation = AndroidUtilities.getWallpaperRotation(accent.backgroundRotation, true);
}
if (accent.backgroundGradientOverrideColor2 != 0) {
settings.wallpaper_settings.third_background_color = (int) accent.backgroundGradientOverrideColor2;
settings.wallpaper_settings.flags |= 32;
}
if (accent.backgroundGradientOverrideColor3 != 0) {
settings.wallpaper_settings.fourth_background_color = (int) accent.backgroundGradientOverrideColor3;
settings.wallpaper_settings.flags |= 64;
}
} else {
themeInfo.uploadedFile = null;
themeInfo.uploadedThumb = null;
info = themeInfo.info;
settings = null;
}
getConnectionsManager().sendRequest(req, (response, error) -> {
String title = info != null ? info.title : themeInfo.getName();
int index = title.lastIndexOf(".attheme");
String n = index > 0 ? title.substring(0, index) : title;
if (response != null) {
TLRPC.Document document = (TLRPC.Document) response;
TLRPC.TL_inputDocument inputDocument = new TLRPC.TL_inputDocument();
inputDocument.access_hash = document.access_hash;
inputDocument.id = document.id;
inputDocument.file_reference = document.file_reference;
if (info == null || !info.creator) {
TLRPC.TL_account_createTheme req2 = new TLRPC.TL_account_createTheme();
req2.document = inputDocument;
req2.flags |= 4;
req2.slug = info != null && !TextUtils.isEmpty(info.slug) ? info.slug : "";
req2.title = n;
if (settings != null) {
req2.settings = settings;
req2.flags |= 8;
}
getConnectionsManager().sendRequest(req2, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
if (response1 instanceof TLRPC.TL_theme) {
Theme.setThemeUploadInfo(themeInfo, accent, (TLRPC.TL_theme) response1, currentAccount, false);
installTheme(themeInfo, accent, themeInfo == Theme.getCurrentNightTheme());
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadedToServer, themeInfo, accent);
} else {
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadError, themeInfo, accent);
}
}));
} else {
TLRPC.TL_account_updateTheme req2 = new TLRPC.TL_account_updateTheme();
TLRPC.TL_inputTheme inputTheme = new TLRPC.TL_inputTheme();
inputTheme.id = info.id;
inputTheme.access_hash = info.access_hash;
req2.theme = inputTheme;
req2.slug = info.slug;
req2.flags |= 1;
req2.title = n;
req2.flags |= 2;
req2.document = inputDocument;
req2.flags |= 4;
if (settings != null) {
req2.settings = settings;
req2.flags |= 8;
}
req2.format = "android";
getConnectionsManager().sendRequest(req2, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> {
if (response1 instanceof TLRPC.TL_theme) {
Theme.setThemeUploadInfo(themeInfo, accent, (TLRPC.TL_theme) response1, currentAccount, false);
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadedToServer, themeInfo, accent);
} else {
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadError, themeInfo, accent);
}
}));
}
} else {
AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.themeUploadError, themeInfo, accent));
}
});
}
}
} else if (id == NotificationCenter.fileUploadFailed) {
String location = (String) args[0];
if (uploadingAvatar != null && uploadingAvatar.equals(location)) {
uploadingAvatar = null;
} else if (uploadingWallpaper != null && uploadingWallpaper.equals(location)) {
uploadingWallpaper = null;
uploadingWallpaperInfo = null;
} else {
Object object = uploadingThemes.remove(location);
if (object instanceof Theme.ThemeInfo) {
Theme.ThemeInfo themeInfo = (Theme.ThemeInfo) object;
themeInfo.uploadedFile = null;
themeInfo.uploadedThumb = null;
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadError, themeInfo, null);
} else if (object instanceof Theme.ThemeAccent) {
Theme.ThemeAccent accent = (Theme.ThemeAccent) object;
accent.uploadingThumb = null;
getNotificationCenter().postNotificationName(NotificationCenter.themeUploadError, accent.parentTheme, accent);
}
}
} else if (id == NotificationCenter.messageReceivedByServer) {
Boolean scheduled = (Boolean) args[6];
if (scheduled) {
return;
}
Integer msgId = (Integer) args[0];
Integer newMsgId = (Integer) args[1];
Long did = (Long) args[3];
MessageObject obj = dialogMessage.get(did);
if (obj != null && (obj.getId() == msgId || obj.messageOwner.local_id == msgId)) {
obj.messageOwner.id = newMsgId;
obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
}
TLRPC.Dialog dialog = dialogs_dict.get(did);
if (dialog != null && dialog.top_message == msgId) {
dialog.top_message = newMsgId;
getNotificationCenter().postNotificationName(NotificationCenter.dialogsNeedReload);
}
obj = dialogMessagesByIds.get(msgId);
if (obj != null) {
dialogMessagesByIds.remove(msgId);
dialogMessagesByIds.put(newMsgId, obj);
}
if (DialogObject.isChatDialog(did)) {
TLRPC.ChatFull chatFull = fullChats.get(-did);
TLRPC.Chat chat = getChat(-did);
if (chat != null && !ChatObject.hasAdminRights(chat) && chatFull != null && chatFull.slowmode_seconds != 0) {
chatFull.slowmode_next_send_date = getConnectionsManager().getCurrentTime() + chatFull.slowmode_seconds;
chatFull.flags |= 262144;
getMessagesStorage().updateChatInfo(chatFull, false);
}
}
} else if (id == NotificationCenter.updateMessageMedia) {
TLRPC.Message message = (TLRPC.Message) args[0];
if (message.peer_id.channel_id == 0) {
MessageObject existMessageObject = dialogMessagesByIds.get(message.id);
if (existMessageObject != null) {
existMessageObject.messageOwner.media = message.media;
if (message.media.ttl_seconds != 0 && (message.media.photo instanceof TLRPC.TL_photoEmpty || message.media.document instanceof TLRPC.TL_documentEmpty)) {
existMessageObject.setType();
getNotificationCenter().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
}
}
}
}
}
use of org.telegram.ui.ActionBar.Theme 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.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class ThemeSetUrlActivity method checkUrl.
private boolean checkUrl(final String url, boolean alert) {
if (checkRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(checkRunnable);
checkRunnable = null;
lastCheckName = null;
if (checkReqId != 0) {
ConnectionsManager.getInstance(currentAccount).cancelRequest(checkReqId, true);
}
}
lastNameAvailable = false;
if (url != null) {
if (url.startsWith("_") || url.endsWith("_")) {
setCheckText(LocaleController.getString("SetUrlInvalid", R.string.SetUrlInvalid), Theme.key_windowBackgroundWhiteRedText4);
return false;
}
for (int a = 0; a < url.length(); a++) {
char ch = url.charAt(a);
if (a == 0 && ch >= '0' && ch <= '9') {
if (alert) {
AlertsCreator.showSimpleAlert(this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("SetUrlInvalidStartNumber", R.string.SetUrlInvalidStartNumber));
} else {
setCheckText(LocaleController.getString("SetUrlInvalidStartNumber", R.string.SetUrlInvalidStartNumber), Theme.key_windowBackgroundWhiteRedText4);
}
return false;
}
if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
if (alert) {
AlertsCreator.showSimpleAlert(this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("SetUrlInvalid", R.string.SetUrlInvalid));
} else {
setCheckText(LocaleController.getString("SetUrlInvalid", R.string.SetUrlInvalid), Theme.key_windowBackgroundWhiteRedText4);
}
return false;
}
}
}
if (url == null || url.length() < 5) {
if (alert) {
AlertsCreator.showSimpleAlert(this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("SetUrlInvalidShort", R.string.SetUrlInvalidShort));
} else {
setCheckText(LocaleController.getString("SetUrlInvalidShort", R.string.SetUrlInvalidShort), Theme.key_windowBackgroundWhiteRedText4);
}
return false;
}
if (url.length() > 64) {
if (alert) {
AlertsCreator.showSimpleAlert(this, LocaleController.getString("Theme", R.string.Theme), LocaleController.getString("SetUrlInvalidLong", R.string.SetUrlInvalidLong));
} else {
setCheckText(LocaleController.getString("SetUrlInvalidLong", R.string.SetUrlInvalidLong), Theme.key_windowBackgroundWhiteRedText4);
}
return false;
}
if (!alert) {
String currentUrl = info != null && info.slug != null ? info.slug : "";
if (url.equals(currentUrl)) {
setCheckText(LocaleController.formatString("SetUrlAvailable", R.string.SetUrlAvailable, url), Theme.key_windowBackgroundWhiteGreenText);
return true;
}
setCheckText(LocaleController.getString("SetUrlChecking", R.string.SetUrlChecking), Theme.key_windowBackgroundWhiteGrayText8);
lastCheckName = url;
checkRunnable = () -> {
TLRPC.TL_account_createTheme req = new TLRPC.TL_account_createTheme();
req.slug = url;
req.title = "";
req.document = new TLRPC.TL_inputDocumentEmpty();
checkReqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
checkReqId = 0;
if (lastCheckName != null && lastCheckName.equals(url)) {
if (error == null || !"THEME_SLUG_INVALID".equals(error.text) && !"THEME_SLUG_OCCUPIED".equals(error.text)) {
setCheckText(LocaleController.formatString("SetUrlAvailable", R.string.SetUrlAvailable, url), Theme.key_windowBackgroundWhiteGreenText);
lastNameAvailable = true;
} else {
setCheckText(LocaleController.getString("SetUrlInUse", R.string.SetUrlInUse), Theme.key_windowBackgroundWhiteRedText4);
lastNameAvailable = false;
}
}
}), ConnectionsManager.RequestFlagFailOnServerErrors);
};
AndroidUtilities.runOnUIThread(checkRunnable, 300);
}
return true;
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class LaunchActivity method handleIntent.
private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) {
if (AndroidUtilities.handleProxyIntent(this, intent)) {
actionBarLayout.showLastFragment();
if (AndroidUtilities.isTablet()) {
layersActionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
}
return true;
}
if (PhotoViewer.hasInstance() && PhotoViewer.getInstance().isVisible()) {
if (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) {
PhotoViewer.getInstance().closePhoto(false, true);
}
}
int flags = intent.getFlags();
String action = intent.getAction();
final int[] intentAccount = new int[] { intent.getIntExtra("currentAccount", UserConfig.selectedAccount) };
switchToAccount(intentAccount[0], true);
boolean isVoipIntent = action != null && action.equals("voip");
if (!fromPassword && (AndroidUtilities.needShowPasscode(true) || SharedConfig.isWaitingForPasscodeEnter)) {
showPasscodeActivity(true, false, -1, -1, null, null);
UserConfig.getInstance(currentAccount).saveConfig(false);
if (!isVoipIntent) {
passcodeSaveIntent = intent;
passcodeSaveIntentIsNew = isNew;
passcodeSaveIntentIsRestore = restore;
return false;
}
}
boolean pushOpened = false;
long push_user_id = 0;
long push_chat_id = 0;
int push_enc_id = 0;
int push_msg_id = 0;
int open_settings = 0;
int open_widget_edit = -1;
int open_widget_edit_type = -1;
int open_new_dialog = 0;
long dialogId = 0;
boolean showDialogsList = false;
boolean showPlayer = false;
boolean showLocations = false;
boolean showGroupVoip = false;
boolean showCallLog = false;
boolean audioCallUser = false;
boolean videoCallUser = false;
boolean needCallAlert = false;
boolean newContact = false;
boolean newContactAlert = false;
boolean scanQr = false;
String searchQuery = null;
String callSearchQuery = null;
String newContactName = null;
String newContactPhone = null;
photoPathsArray = null;
videoPath = null;
sendingText = null;
sendingLocation = null;
documentsPathsArray = null;
documentsOriginalPathsArray = null;
documentsMimeType = null;
documentsUrisArray = null;
exportingChatUri = null;
contactsToSend = null;
contactsToSendUri = null;
importingStickers = null;
importingStickersEmoji = null;
importingStickersSoftware = null;
if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (intent != null && intent.getAction() != null && !restore) {
if (Intent.ACTION_SEND.equals(intent.getAction())) {
if (SharedConfig.directShare && intent != null && intent.getExtras() != null) {
dialogId = intent.getExtras().getLong("dialogId", 0);
String hash = null;
if (dialogId == 0) {
try {
String id = intent.getExtras().getString(ShortcutManagerCompat.EXTRA_SHORTCUT_ID);
if (id != null) {
List<ShortcutInfoCompat> list = ShortcutManagerCompat.getDynamicShortcuts(ApplicationLoader.applicationContext);
for (int a = 0, N = list.size(); a < N; a++) {
ShortcutInfoCompat info = list.get(a);
if (id.equals(info.getId())) {
Bundle extras = info.getIntent().getExtras();
dialogId = extras.getLong("dialogId", 0);
hash = extras.getString("hash", null);
break;
}
}
}
} catch (Throwable e) {
FileLog.e(e);
}
} else {
hash = intent.getExtras().getString("hash", null);
}
if (SharedConfig.directShareHash == null || !SharedConfig.directShareHash.equals(hash)) {
dialogId = 0;
}
}
boolean error = false;
String type = intent.getType();
if (type != null && type.equals(ContactsContract.Contacts.CONTENT_VCARD_TYPE)) {
try {
Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
if (uri != null) {
contactsToSend = AndroidUtilities.loadVCardFromStream(uri, currentAccount, false, null, null);
if (contactsToSend.size() > 5) {
contactsToSend = null;
documentsUrisArray = new ArrayList<>();
documentsUrisArray.add(uri);
documentsMimeType = type;
} else {
contactsToSendUri = uri;
}
} else {
error = true;
}
} catch (Exception e) {
FileLog.e(e);
error = true;
}
} else {
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text == null) {
CharSequence textSequence = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
if (textSequence != null) {
text = textSequence.toString();
}
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (!TextUtils.isEmpty(text)) {
Matcher m = locationRegex.matcher(text);
if (m.find()) {
String[] lines = text.split("\\n");
String venueTitle = null;
String venueAddress = null;
if (lines[0].equals("My Position")) {
// Use normal GeoPoint message (user position)
} else if (!lines[0].contains("geo:")) {
venueTitle = lines[0];
if (!lines[1].contains("geo:")) {
venueAddress = lines[1];
}
}
sendingLocation = new Location("");
sendingLocation.setLatitude(Double.parseDouble(m.group(1)));
sendingLocation.setLongitude(Double.parseDouble(m.group(2)));
Bundle bundle = new Bundle();
bundle.putCharSequence("venueTitle", venueTitle);
bundle.putCharSequence("venueAddress", venueAddress);
sendingLocation.setExtras(bundle);
} else if ((text.startsWith("http://") || text.startsWith("https://")) && !TextUtils.isEmpty(subject)) {
text = subject + "\n" + text;
}
sendingText = text;
} else if (!TextUtils.isEmpty(subject)) {
sendingText = subject;
}
Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (parcelable != null) {
String path;
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
if (uri != null) {
if (AndroidUtilities.isInternalUri(uri)) {
error = true;
}
}
if (!error && uri != null) {
if (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg")) {
if (photoPathsArray == null) {
photoPathsArray = new ArrayList<>();
}
SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
info.uri = uri;
photoPathsArray.add(info);
} else {
String originalPath = uri.toString();
if (dialogId == 0 && originalPath != null) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("export path = " + originalPath);
}
Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
for (String u : exportUris) {
try {
Pattern pattern = Pattern.compile(u);
if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
exportingChatUri = uri;
break;
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (exportingChatUri == null) {
if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
exportingChatUri = uri;
}
}
}
if (exportingChatUri == null) {
path = AndroidUtilities.getPath(uri);
if (!BuildVars.NO_SCOPED_STORAGE) {
path = MediaController.copyFileToCache(uri, "file");
}
if (path != null) {
if (path.startsWith("file:")) {
path = path.replace("file://", "");
}
if (type != null && type.startsWith("video/")) {
videoPath = path;
} else {
if (documentsPathsArray == null) {
documentsPathsArray = new ArrayList<>();
documentsOriginalPathsArray = new ArrayList<>();
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(uri.toString());
}
} else {
if (documentsUrisArray == null) {
documentsUrisArray = new ArrayList<>();
}
documentsUrisArray.add(uri);
documentsMimeType = type;
}
}
}
}
} else if (sendingText == null && sendingLocation == null) {
error = true;
}
}
if (error) {
Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
}
} else if ("org.telegram.messenger.CREATE_STICKER_PACK".equals(intent.getAction())) {
try {
importingStickers = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
importingStickersEmoji = intent.getStringArrayListExtra("STICKER_EMOJIS");
importingStickersSoftware = intent.getStringExtra("IMPORTER");
} catch (Throwable e) {
FileLog.e(e);
importingStickers = null;
importingStickersEmoji = null;
importingStickersSoftware = null;
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) {
boolean error = false;
try {
ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
String type = intent.getType();
if (uris != null) {
for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
if (uri != null) {
if (AndroidUtilities.isInternalUri(uri)) {
uris.remove(a);
a--;
}
}
}
if (uris.isEmpty()) {
uris = null;
}
}
if (uris != null) {
if (type != null && type.startsWith("image/")) {
for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
if (photoPathsArray == null) {
photoPathsArray = new ArrayList<>();
}
SendMessagesHelper.SendingMediaInfo info = new SendMessagesHelper.SendingMediaInfo();
info.uri = uri;
photoPathsArray.add(info);
}
} else {
Set<String> exportUris = MessagesController.getInstance(intentAccount[0]).exportUri;
for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
String path = AndroidUtilities.getPath(uri);
String originalPath = parcelable.toString();
if (originalPath == null) {
originalPath = path;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("export path = " + originalPath);
}
if (dialogId == 0 && originalPath != null && exportingChatUri == null) {
boolean ok = false;
String fileName = FileLoader.fixFileName(MediaController.getFileName(uri));
for (String u : exportUris) {
try {
Pattern pattern = Pattern.compile(u);
if (pattern.matcher(originalPath).find() || pattern.matcher(fileName).find()) {
exportingChatUri = uri;
ok = true;
break;
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (ok) {
continue;
} else if (originalPath.startsWith("content://com.kakao.talk") && originalPath.endsWith("KakaoTalkChats.txt")) {
exportingChatUri = uri;
continue;
}
}
if (path != null) {
if (path.startsWith("file:")) {
path = path.replace("file://", "");
}
if (documentsPathsArray == null) {
documentsPathsArray = new ArrayList<>();
documentsOriginalPathsArray = new ArrayList<>();
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(originalPath);
} else {
if (documentsUrisArray == null) {
documentsUrisArray = new ArrayList<>();
}
documentsUrisArray.add(uri);
documentsMimeType = type;
}
}
}
} else {
error = true;
}
} catch (Exception e) {
FileLog.e(e);
error = true;
}
if (error) {
Toast.makeText(this, "Unsupported content", Toast.LENGTH_SHORT).show();
}
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri data = intent.getData();
if (data != null) {
String username = null;
String login = null;
String group = null;
String sticker = null;
HashMap<String, String> auth = null;
String unsupportedUrl = null;
String botUser = null;
String botChat = null;
String message = null;
String phone = null;
String game = null;
String voicechat = null;
String livestream = null;
String phoneHash = null;
String lang = null;
String theme = null;
String code = null;
TLRPC.TL_wallPaper wallPaper = null;
Integer messageId = null;
Long channelId = null;
Integer threadId = null;
Integer commentId = null;
int videoTimestamp = -1;
boolean hasUrl = false;
final String scheme = data.getScheme();
if (scheme != null) {
switch(scheme) {
case "http":
case "https":
{
String host = data.getHost().toLowerCase();
if (host.equals("telegram.me") || host.equals("t.me") || host.equals("telegram.dog")) {
String path = data.getPath();
if (path != null && path.length() > 1) {
path = path.substring(1);
if (path.startsWith("bg/")) {
wallPaper = new TLRPC.TL_wallPaper();
wallPaper.settings = new TLRPC.TL_wallPaperSettings();
wallPaper.slug = path.replace("bg/", "");
boolean ok = false;
if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
try {
wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
wallPaper.slug = null;
ok = true;
} catch (Exception ignore) {
}
} else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
try {
wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
}
if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
}
try {
String rotation = data.getQueryParameter("rotation");
if (!TextUtils.isEmpty(rotation)) {
wallPaper.settings.rotation = Utilities.parseInt(rotation);
}
} catch (Exception ignore) {
}
wallPaper.slug = null;
ok = true;
} catch (Exception ignore) {
}
}
if (!ok) {
String mode = data.getQueryParameter("mode");
if (mode != null) {
mode = mode.toLowerCase();
String[] modes = mode.split(" ");
if (modes != null && modes.length > 0) {
for (int a = 0; a < modes.length; a++) {
if ("blur".equals(modes[a])) {
wallPaper.settings.blur = true;
} else if ("motion".equals(modes[a])) {
wallPaper.settings.motion = true;
}
}
}
}
String intensity = data.getQueryParameter("intensity");
if (!TextUtils.isEmpty(intensity)) {
wallPaper.settings.intensity = Utilities.parseInt(intensity);
} else {
wallPaper.settings.intensity = 50;
}
try {
String bgColor = data.getQueryParameter("bg_color");
if (!TextUtils.isEmpty(bgColor)) {
wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
if (bgColor.length() >= 13) {
wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(7, 13), 16) | 0xff000000;
if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
}
if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
}
}
} else {
wallPaper.settings.background_color = 0xffffffff;
}
} catch (Exception ignore) {
}
try {
String rotation = data.getQueryParameter("rotation");
if (!TextUtils.isEmpty(rotation)) {
wallPaper.settings.rotation = Utilities.parseInt(rotation);
}
} catch (Exception ignore) {
}
}
} else if (path.startsWith("login/")) {
int intCode = Utilities.parseInt(path.replace("login/", ""));
if (intCode != 0) {
code = "" + intCode;
}
} else if (path.startsWith("joinchat/")) {
group = path.replace("joinchat/", "");
} else if (path.startsWith("+")) {
group = path.replace("+", "");
} else if (path.startsWith("addstickers/")) {
sticker = path.replace("addstickers/", "");
} else if (path.startsWith("msg/") || path.startsWith("share/")) {
message = data.getQueryParameter("url");
if (message == null) {
message = "";
}
if (data.getQueryParameter("text") != null) {
if (message.length() > 0) {
hasUrl = true;
message += "\n";
}
message += data.getQueryParameter("text");
}
if (message.length() > 4096 * 4) {
message = message.substring(0, 4096 * 4);
}
while (message.endsWith("\n")) {
message = message.substring(0, message.length() - 1);
}
} else if (path.startsWith("confirmphone")) {
phone = data.getQueryParameter("phone");
phoneHash = data.getQueryParameter("hash");
} else if (path.startsWith("setlanguage/")) {
lang = path.substring(12);
} else if (path.startsWith("addtheme/")) {
theme = path.substring(9);
} else if (path.startsWith("c/")) {
List<String> segments = data.getPathSegments();
if (segments.size() == 3) {
channelId = Utilities.parseLong(segments.get(1));
messageId = Utilities.parseInt(segments.get(2));
if (messageId == 0 || channelId == 0) {
messageId = null;
channelId = null;
}
threadId = Utilities.parseInt(data.getQueryParameter("thread"));
if (threadId == 0) {
threadId = null;
}
}
} else if (path.length() >= 1) {
ArrayList<String> segments = new ArrayList<>(data.getPathSegments());
if (segments.size() > 0 && segments.get(0).equals("s")) {
segments.remove(0);
}
if (segments.size() > 0) {
username = segments.get(0);
if (segments.size() > 1) {
messageId = Utilities.parseInt(segments.get(1));
if (messageId == 0) {
messageId = null;
}
}
}
if (messageId != null) {
videoTimestamp = getTimestampFromLink(data);
}
botUser = data.getQueryParameter("start");
botChat = data.getQueryParameter("startgroup");
game = data.getQueryParameter("game");
voicechat = data.getQueryParameter("voicechat");
livestream = data.getQueryParameter("livestream");
threadId = Utilities.parseInt(data.getQueryParameter("thread"));
if (threadId == 0) {
threadId = null;
}
commentId = Utilities.parseInt(data.getQueryParameter("comment"));
if (commentId == 0) {
commentId = null;
}
}
}
}
break;
}
case "tg":
{
String url = data.toString();
if (url.startsWith("tg:resolve") || url.startsWith("tg://resolve")) {
url = url.replace("tg:resolve", "tg://telegram.org").replace("tg://resolve", "tg://telegram.org");
data = Uri.parse(url);
username = data.getQueryParameter("domain");
if ("telegrampassport".equals(username)) {
username = null;
auth = new HashMap<>();
String scope = data.getQueryParameter("scope");
if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
auth.put("nonce", data.getQueryParameter("nonce"));
} else {
auth.put("payload", data.getQueryParameter("payload"));
}
auth.put("bot_id", data.getQueryParameter("bot_id"));
auth.put("scope", scope);
auth.put("public_key", data.getQueryParameter("public_key"));
auth.put("callback_url", data.getQueryParameter("callback_url"));
} else {
botUser = data.getQueryParameter("start");
botChat = data.getQueryParameter("startgroup");
game = data.getQueryParameter("game");
voicechat = data.getQueryParameter("voicechat");
livestream = data.getQueryParameter("livestream");
messageId = Utilities.parseInt(data.getQueryParameter("post"));
if (messageId == 0) {
messageId = null;
}
threadId = Utilities.parseInt(data.getQueryParameter("thread"));
if (threadId == 0) {
threadId = null;
}
commentId = Utilities.parseInt(data.getQueryParameter("comment"));
if (commentId == 0) {
commentId = null;
}
}
} else if (url.startsWith("tg:privatepost") || url.startsWith("tg://privatepost")) {
url = url.replace("tg:privatepost", "tg://telegram.org").replace("tg://privatepost", "tg://telegram.org");
data = Uri.parse(url);
messageId = Utilities.parseInt(data.getQueryParameter("post"));
channelId = Utilities.parseLong(data.getQueryParameter("channel"));
if (messageId == 0 || channelId == 0) {
messageId = null;
channelId = null;
}
threadId = Utilities.parseInt(data.getQueryParameter("thread"));
if (threadId == 0) {
threadId = null;
}
commentId = Utilities.parseInt(data.getQueryParameter("comment"));
if (commentId == 0) {
commentId = null;
}
} else if (url.startsWith("tg:bg") || url.startsWith("tg://bg")) {
url = url.replace("tg:bg", "tg://telegram.org").replace("tg://bg", "tg://telegram.org");
data = Uri.parse(url);
wallPaper = new TLRPC.TL_wallPaper();
wallPaper.settings = new TLRPC.TL_wallPaperSettings();
wallPaper.slug = data.getQueryParameter("slug");
if (wallPaper.slug == null) {
wallPaper.slug = data.getQueryParameter("color");
}
boolean ok = false;
if (wallPaper.slug != null && wallPaper.slug.length() == 6) {
try {
wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug, 16) | 0xff000000;
wallPaper.slug = null;
ok = true;
} catch (Exception ignore) {
}
} else if (wallPaper.slug != null && wallPaper.slug.length() >= 13 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(6))) {
try {
wallPaper.settings.background_color = Integer.parseInt(wallPaper.slug.substring(0, 6), 16) | 0xff000000;
wallPaper.settings.second_background_color = Integer.parseInt(wallPaper.slug.substring(7, 13), 16) | 0xff000000;
if (wallPaper.slug.length() >= 20 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(13))) {
wallPaper.settings.third_background_color = Integer.parseInt(wallPaper.slug.substring(14, 20), 16) | 0xff000000;
}
if (wallPaper.slug.length() == 27 && AndroidUtilities.isValidWallChar(wallPaper.slug.charAt(20))) {
wallPaper.settings.fourth_background_color = Integer.parseInt(wallPaper.slug.substring(21), 16) | 0xff000000;
}
try {
String rotation = data.getQueryParameter("rotation");
if (!TextUtils.isEmpty(rotation)) {
wallPaper.settings.rotation = Utilities.parseInt(rotation);
}
} catch (Exception ignore) {
}
wallPaper.slug = null;
ok = true;
} catch (Exception ignore) {
}
}
if (!ok) {
String mode = data.getQueryParameter("mode");
if (mode != null) {
mode = mode.toLowerCase();
String[] modes = mode.split(" ");
if (modes != null && modes.length > 0) {
for (int a = 0; a < modes.length; a++) {
if ("blur".equals(modes[a])) {
wallPaper.settings.blur = true;
} else if ("motion".equals(modes[a])) {
wallPaper.settings.motion = true;
}
}
}
}
wallPaper.settings.intensity = Utilities.parseInt(data.getQueryParameter("intensity"));
try {
String bgColor = data.getQueryParameter("bg_color");
if (!TextUtils.isEmpty(bgColor)) {
wallPaper.settings.background_color = Integer.parseInt(bgColor.substring(0, 6), 16) | 0xff000000;
if (bgColor.length() >= 13) {
wallPaper.settings.second_background_color = Integer.parseInt(bgColor.substring(8, 13), 16) | 0xff000000;
if (bgColor.length() >= 20 && AndroidUtilities.isValidWallChar(bgColor.charAt(13))) {
wallPaper.settings.third_background_color = Integer.parseInt(bgColor.substring(14, 20), 16) | 0xff000000;
}
if (bgColor.length() == 27 && AndroidUtilities.isValidWallChar(bgColor.charAt(20))) {
wallPaper.settings.fourth_background_color = Integer.parseInt(bgColor.substring(21), 16) | 0xff000000;
}
}
}
} catch (Exception ignore) {
}
try {
String rotation = data.getQueryParameter("rotation");
if (!TextUtils.isEmpty(rotation)) {
wallPaper.settings.rotation = Utilities.parseInt(rotation);
}
} catch (Exception ignore) {
}
}
} else if (url.startsWith("tg:join") || url.startsWith("tg://join")) {
url = url.replace("tg:join", "tg://telegram.org").replace("tg://join", "tg://telegram.org");
data = Uri.parse(url);
group = data.getQueryParameter("invite");
} else if (url.startsWith("tg:addstickers") || url.startsWith("tg://addstickers")) {
url = url.replace("tg:addstickers", "tg://telegram.org").replace("tg://addstickers", "tg://telegram.org");
data = Uri.parse(url);
sticker = data.getQueryParameter("set");
} else if (url.startsWith("tg:msg") || url.startsWith("tg://msg") || url.startsWith("tg://share") || url.startsWith("tg:share")) {
url = url.replace("tg:msg", "tg://telegram.org").replace("tg://msg", "tg://telegram.org").replace("tg://share", "tg://telegram.org").replace("tg:share", "tg://telegram.org");
data = Uri.parse(url);
message = data.getQueryParameter("url");
if (message == null) {
message = "";
}
if (data.getQueryParameter("text") != null) {
if (message.length() > 0) {
hasUrl = true;
message += "\n";
}
message += data.getQueryParameter("text");
}
if (message.length() > 4096 * 4) {
message = message.substring(0, 4096 * 4);
}
while (message.endsWith("\n")) {
message = message.substring(0, message.length() - 1);
}
} else if (url.startsWith("tg:confirmphone") || url.startsWith("tg://confirmphone")) {
url = url.replace("tg:confirmphone", "tg://telegram.org").replace("tg://confirmphone", "tg://telegram.org");
data = Uri.parse(url);
phone = data.getQueryParameter("phone");
phoneHash = data.getQueryParameter("hash");
} else if (url.startsWith("tg:login") || url.startsWith("tg://login")) {
url = url.replace("tg:login", "tg://telegram.org").replace("tg://login", "tg://telegram.org");
data = Uri.parse(url);
login = data.getQueryParameter("token");
int intCode = Utilities.parseInt(data.getQueryParameter("code"));
if (intCode != 0) {
code = "" + intCode;
}
} else if (url.startsWith("tg:openmessage") || url.startsWith("tg://openmessage")) {
url = url.replace("tg:openmessage", "tg://telegram.org").replace("tg://openmessage", "tg://telegram.org");
data = Uri.parse(url);
String userID = data.getQueryParameter("user_id");
String chatID = data.getQueryParameter("chat_id");
String msgID = data.getQueryParameter("message_id");
if (userID != null) {
try {
push_user_id = Long.parseLong(userID);
} catch (NumberFormatException ignore) {
}
} else if (chatID != null) {
try {
push_chat_id = Long.parseLong(chatID);
} catch (NumberFormatException ignore) {
}
}
if (msgID != null) {
try {
push_msg_id = Integer.parseInt(msgID);
} catch (NumberFormatException ignore) {
}
}
} else if (url.startsWith("tg:passport") || url.startsWith("tg://passport") || url.startsWith("tg:secureid")) {
url = url.replace("tg:passport", "tg://telegram.org").replace("tg://passport", "tg://telegram.org").replace("tg:secureid", "tg://telegram.org");
data = Uri.parse(url);
auth = new HashMap<>();
String scope = data.getQueryParameter("scope");
if (!TextUtils.isEmpty(scope) && scope.startsWith("{") && scope.endsWith("}")) {
auth.put("nonce", data.getQueryParameter("nonce"));
} else {
auth.put("payload", data.getQueryParameter("payload"));
}
auth.put("bot_id", data.getQueryParameter("bot_id"));
auth.put("scope", scope);
auth.put("public_key", data.getQueryParameter("public_key"));
auth.put("callback_url", data.getQueryParameter("callback_url"));
} else if (url.startsWith("tg:setlanguage") || url.startsWith("tg://setlanguage")) {
url = url.replace("tg:setlanguage", "tg://telegram.org").replace("tg://setlanguage", "tg://telegram.org");
data = Uri.parse(url);
lang = data.getQueryParameter("lang");
} else if (url.startsWith("tg:addtheme") || url.startsWith("tg://addtheme")) {
url = url.replace("tg:addtheme", "tg://telegram.org").replace("tg://addtheme", "tg://telegram.org");
data = Uri.parse(url);
theme = data.getQueryParameter("slug");
} else if (url.startsWith("tg:settings") || url.startsWith("tg://settings")) {
if (url.contains("themes")) {
open_settings = 2;
} else if (url.contains("devices")) {
open_settings = 3;
} else if (url.contains("folders")) {
open_settings = 4;
} else if (url.contains("change_number")) {
open_settings = 5;
} else {
open_settings = 1;
}
} else if ((url.startsWith("tg:search") || url.startsWith("tg://search"))) {
url = url.replace("tg:search", "tg://telegram.org").replace("tg://search", "tg://telegram.org");
data = Uri.parse(url);
searchQuery = data.getQueryParameter("query");
if (searchQuery != null) {
searchQuery = searchQuery.trim();
} else {
searchQuery = "";
}
} else if ((url.startsWith("tg:calllog") || url.startsWith("tg://calllog"))) {
showCallLog = true;
} else if ((url.startsWith("tg:call") || url.startsWith("tg://call"))) {
if (UserConfig.getInstance(currentAccount).isClientActivated()) {
final String extraForceCall = "extra_force_call";
if (ContactsController.getInstance(currentAccount).contactsLoaded || intent.hasExtra(extraForceCall)) {
final String callFormat = data.getQueryParameter("format");
final String callUserName = data.getQueryParameter("name");
final String callPhone = data.getQueryParameter("phone");
final List<TLRPC.TL_contact> contacts = findContacts(callUserName, callPhone, false);
if (contacts.isEmpty() && callPhone != null) {
newContactName = callUserName;
newContactPhone = callPhone;
newContactAlert = true;
} else {
if (contacts.size() == 1) {
push_user_id = contacts.get(0).user_id;
}
if (push_user_id == 0) {
callSearchQuery = callUserName != null ? callUserName : "";
}
if ("video".equalsIgnoreCase(callFormat)) {
videoCallUser = true;
} else {
audioCallUser = true;
}
needCallAlert = true;
}
} else {
final Intent copyIntent = new Intent(intent);
copyIntent.removeExtra(EXTRA_ACTION_TOKEN);
copyIntent.putExtra(extraForceCall, true);
ContactsLoadingObserver.observe((contactsLoaded) -> handleIntent(copyIntent, true, false, false), 1000);
}
}
} else if ((url.startsWith("tg:scanqr") || url.startsWith("tg://scanqr"))) {
scanQr = true;
} else if ((url.startsWith("tg:addcontact") || url.startsWith("tg://addcontact"))) {
url = url.replace("tg:addcontact", "tg://telegram.org").replace("tg://addcontact", "tg://telegram.org");
data = Uri.parse(url);
newContactName = data.getQueryParameter("name");
newContactPhone = data.getQueryParameter("phone");
newContact = true;
} else {
unsupportedUrl = url.replace("tg://", "").replace("tg:", "");
int index;
if ((index = unsupportedUrl.indexOf('?')) >= 0) {
unsupportedUrl = unsupportedUrl.substring(0, index);
}
}
break;
}
}
}
if (intent.hasExtra(EXTRA_ACTION_TOKEN)) {
final boolean success = UserConfig.getInstance(currentAccount).isClientActivated() && "tg".equals(scheme) && unsupportedUrl == null;
intent.removeExtra(EXTRA_ACTION_TOKEN);
}
if (code != null || UserConfig.getInstance(currentAccount).isClientActivated()) {
if (phone != null || phoneHash != null) {
final Bundle args = new Bundle();
args.putString("phone", phone);
args.putString("hash", phoneHash);
AndroidUtilities.runOnUIThread(() -> presentFragment(new CancelAccountDeletionActivity(args)));
} else if (username != null || group != null || sticker != null || message != null || game != null || voicechat != null || auth != null || unsupportedUrl != null || lang != null || code != null || wallPaper != null || channelId != null || theme != null || login != null) {
if (message != null && message.startsWith("@")) {
message = " " + message;
}
runLinkRequest(intentAccount[0], username, group, sticker, botUser, botChat, message, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, login, wallPaper, theme, voicechat, livestream, 0, videoTimestamp);
} else {
try (Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null)) {
if (cursor != null) {
if (cursor.moveToFirst()) {
int accountId = Utilities.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (UserConfig.getInstance(a).getClientUserId() == accountId) {
intentAccount[0] = a;
switchToAccount(intentAccount[0], true);
break;
}
}
long userId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.DATA4));
NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
push_user_id = userId;
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call")) {
audioCallUser = true;
} else if (TextUtils.equals(mimeType, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.call.video")) {
videoCallUser = true;
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
}
} else if (intent.getAction().equals("org.telegram.messenger.OPEN_ACCOUNT")) {
open_settings = 1;
} else if (intent.getAction().equals("new_dialog")) {
open_new_dialog = 1;
} else if (intent.getAction().startsWith("com.tmessages.openchat")) {
long chatId = intent.getLongExtra("chatId", intent.getIntExtra("chatId", 0));
long userId = intent.getLongExtra("userId", intent.getIntExtra("userId", 0));
int encId = intent.getIntExtra("encId", 0);
int widgetId = intent.getIntExtra("appWidgetId", 0);
if (widgetId != 0) {
open_settings = 6;
open_widget_edit = widgetId;
open_widget_edit_type = intent.getIntExtra("appWidgetType", 0);
} else {
if (push_msg_id == 0) {
push_msg_id = intent.getIntExtra("message_id", 0);
}
if (chatId != 0) {
NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
push_chat_id = chatId;
} else if (userId != 0) {
NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
push_user_id = userId;
} else if (encId != 0) {
NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
push_enc_id = encId;
} else {
showDialogsList = true;
}
}
} else if (intent.getAction().equals("com.tmessages.openplayer")) {
showPlayer = true;
} else if (intent.getAction().equals("org.tmessages.openlocations")) {
showLocations = true;
} else if (action.equals("voip_chat")) {
showGroupVoip = true;
}
}
}
if (UserConfig.getInstance(currentAccount).isClientActivated()) {
if (searchQuery != null) {
final BaseFragment lastFragment = actionBarLayout.getLastFragment();
if (lastFragment instanceof DialogsActivity) {
final DialogsActivity dialogsActivity = (DialogsActivity) lastFragment;
if (dialogsActivity.isMainDialogList()) {
if (dialogsActivity.getFragmentView() != null) {
dialogsActivity.search(searchQuery, true);
} else {
dialogsActivity.setInitialSearchString(searchQuery);
}
}
} else {
showDialogsList = true;
}
}
if (push_user_id != 0) {
if (audioCallUser || videoCallUser) {
if (needCallAlert) {
final BaseFragment lastFragment = actionBarLayout.getLastFragment();
if (lastFragment != null) {
AlertsCreator.createCallDialogAlert(lastFragment, lastFragment.getMessagesController().getUser(push_user_id), videoCallUser);
}
} else {
VoIPPendingCall.startOrSchedule(this, push_user_id, videoCallUser, AccountInstance.getInstance(intentAccount[0]));
}
} else {
Bundle args = new Bundle();
args.putLong("user_id", push_user_id);
if (push_msg_id != 0) {
args.putInt("message_id", push_msg_id);
}
if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
ChatActivity fragment = new ChatActivity(args);
if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
pushOpened = true;
drawerLayoutContainer.closeDrawer();
}
}
}
} else if (push_chat_id != 0) {
Bundle args = new Bundle();
args.putLong("chat_id", push_chat_id);
if (push_msg_id != 0) {
args.putInt("message_id", push_msg_id);
}
if (mainFragmentsStack.isEmpty() || MessagesController.getInstance(intentAccount[0]).checkCanOpenChat(args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
ChatActivity fragment = new ChatActivity(args);
if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
pushOpened = true;
drawerLayoutContainer.closeDrawer();
}
}
} else if (push_enc_id != 0) {
Bundle args = new Bundle();
args.putInt("enc_id", push_enc_id);
ChatActivity fragment = new ChatActivity(args);
if (actionBarLayout.presentFragment(fragment, false, true, true, false)) {
pushOpened = true;
drawerLayoutContainer.closeDrawer();
}
} else if (showDialogsList) {
if (!AndroidUtilities.isTablet()) {
actionBarLayout.removeAllFragments();
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(false);
}
}
pushOpened = false;
isNew = false;
} else if (showPlayer) {
if (!actionBarLayout.fragmentsStack.isEmpty()) {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
fragment.showDialog(new AudioPlayerAlert(this, null));
}
pushOpened = false;
} else if (showLocations) {
if (!actionBarLayout.fragmentsStack.isEmpty()) {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
fragment.showDialog(new SharingLocationsAlert(this, info -> {
intentAccount[0] = info.messageObject.currentAccount;
switchToAccount(intentAccount[0], true);
LocationActivity locationActivity = new LocationActivity(2);
locationActivity.setMessageObject(info.messageObject);
final long dialog_id = info.messageObject.getDialogId();
locationActivity.setDelegate((location, live, notify, scheduleDate) -> SendMessagesHelper.getInstance(intentAccount[0]).sendMessage(location, dialog_id, null, null, null, null, notify, scheduleDate));
presentFragment(locationActivity);
}, null));
}
pushOpened = false;
} else if (exportingChatUri != null) {
runImportRequest(exportingChatUri, documentsUrisArray);
} else if (importingStickers != null) {
AndroidUtilities.runOnUIThread(() -> {
if (!actionBarLayout.fragmentsStack.isEmpty()) {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
fragment.showDialog(new StickersAlert(this, importingStickersSoftware, importingStickers, importingStickersEmoji, null));
}
});
pushOpened = false;
} else if (videoPath != null || photoPathsArray != null || sendingText != null || sendingLocation != null || documentsPathsArray != null || contactsToSend != null || documentsUrisArray != null) {
if (!AndroidUtilities.isTablet()) {
NotificationCenter.getInstance(intentAccount[0]).postNotificationName(NotificationCenter.closeChats);
}
if (dialogId == 0) {
openDialogsToSend(false);
pushOpened = true;
} else {
ArrayList<Long> dids = new ArrayList<>();
dids.add(dialogId);
didSelectDialogs(null, dids, null, false);
}
} else if (open_settings != 0) {
BaseFragment fragment;
boolean closePrevious = false;
if (open_settings == 1) {
Bundle args = new Bundle();
args.putLong("user_id", UserConfig.getInstance(currentAccount).clientUserId);
fragment = new ProfileActivity(args);
} else if (open_settings == 2) {
fragment = new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC);
} else if (open_settings == 3) {
fragment = new SessionsActivity(0);
} else if (open_settings == 4) {
fragment = new FiltersSetupActivity();
} else if (open_settings == 5) {
fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_CHANGE_PHONE_NUMBER);
closePrevious = true;
} else if (open_settings == 6) {
fragment = new EditWidgetActivity(open_widget_edit_type, open_widget_edit);
} else {
fragment = null;
}
boolean closePreviousFinal = closePrevious;
if (open_settings == 6) {
actionBarLayout.presentFragment(fragment, false, true, true, false);
} else {
AndroidUtilities.runOnUIThread(() -> presentFragment(fragment, closePreviousFinal, false));
}
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
} else if (open_new_dialog != 0) {
Bundle args = new Bundle();
args.putBoolean("destroyAfterSelect", true);
actionBarLayout.presentFragment(new ContactsActivity(args), false, true, true, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
} else if (callSearchQuery != null) {
final Bundle args = new Bundle();
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("returnAsResult", true);
args.putBoolean("onlyUsers", true);
args.putBoolean("allowSelf", false);
final ContactsActivity contactsFragment = new ContactsActivity(args);
contactsFragment.setInitialSearchString(callSearchQuery);
final boolean videoCall = videoCallUser;
contactsFragment.setDelegate((user, param, activity) -> {
final TLRPC.UserFull userFull = MessagesController.getInstance(currentAccount).getUserFull(user.id);
VoIPHelper.startCall(user, videoCall, userFull != null && userFull.video_calls_available, LaunchActivity.this, userFull, AccountInstance.getInstance(intentAccount[0]));
});
actionBarLayout.presentFragment(contactsFragment, actionBarLayout.getLastFragment() instanceof ContactsActivity, true, true, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
} else if (scanQr) {
ActionIntroActivity fragment = new ActionIntroActivity(ActionIntroActivity.ACTION_TYPE_QR_LOGIN);
fragment.setQrLoginDelegate(code -> {
AlertDialog progressDialog = new AlertDialog(LaunchActivity.this, 3);
progressDialog.setCanCacnel(false);
progressDialog.show();
byte[] token = Base64.decode(code.substring("tg://login?token=".length()), Base64.URL_SAFE);
TLRPC.TL_auth_acceptLoginToken req = new TLRPC.TL_auth_acceptLoginToken();
req.token = token;
ConnectionsManager.getInstance(currentAccount).sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
try {
progressDialog.dismiss();
} catch (Exception ignore) {
}
if (!(response instanceof TLRPC.TL_authorization)) {
AndroidUtilities.runOnUIThread(() -> AlertsCreator.showSimpleAlert(fragment, LocaleController.getString("AuthAnotherClient", R.string.AuthAnotherClient), LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred) + "\n" + error.text));
}
}));
});
actionBarLayout.presentFragment(fragment, false, true, true, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
} else if (newContact) {
final NewContactActivity fragment = new NewContactActivity();
if (newContactName != null) {
final String[] names = newContactName.split(" ", 2);
fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
}
if (newContactPhone != null) {
fragment.setInitialPhoneNumber(PhoneFormat.stripExceptNumbers(newContactPhone, true), false);
}
actionBarLayout.presentFragment(fragment, false, true, true, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
} else if (showGroupVoip) {
GroupCallActivity.create(this, AccountInstance.getInstance(currentAccount), null, null, false, null);
if (GroupCallActivity.groupCallInstance != null) {
GroupCallActivity.groupCallUiVisible = true;
}
} else if (newContactAlert) {
final BaseFragment lastFragment = actionBarLayout.getLastFragment();
if (lastFragment != null && lastFragment.getParentActivity() != null) {
final String finalNewContactName = newContactName;
final String finalNewContactPhone = NewContactActivity.getPhoneNumber(this, UserConfig.getInstance(currentAccount).getCurrentUser(), newContactPhone, false);
final AlertDialog newContactAlertDialog = new AlertDialog.Builder(lastFragment.getParentActivity()).setTitle(LocaleController.getString("NewContactAlertTitle", R.string.NewContactAlertTitle)).setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("NewContactAlertMessage", R.string.NewContactAlertMessage, PhoneFormat.getInstance().format(finalNewContactPhone)))).setPositiveButton(LocaleController.getString("NewContactAlertButton", R.string.NewContactAlertButton), (d, i) -> {
final NewContactActivity fragment = new NewContactActivity();
fragment.setInitialPhoneNumber(finalNewContactPhone, false);
if (finalNewContactName != null) {
final String[] names = finalNewContactName.split(" ", 2);
fragment.setInitialName(names[0], names.length > 1 ? names[1] : null);
}
lastFragment.presentFragment(fragment);
}).setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null).create();
lastFragment.showDialog(newContactAlertDialog);
pushOpened = true;
}
} else if (showCallLog) {
actionBarLayout.presentFragment(new CallLogActivity(), false, true, true, false);
if (AndroidUtilities.isTablet()) {
actionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
pushOpened = true;
}
}
if (!pushOpened && !isNew) {
if (AndroidUtilities.isTablet()) {
if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
if (layersActionBarLayout.fragmentsStack.isEmpty()) {
layersActionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
}
} else {
if (actionBarLayout.fragmentsStack.isEmpty()) {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
if (searchQuery != null) {
dialogsActivity.setInitialSearchString(searchQuery);
}
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
}
} else {
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.getInstance(currentAccount).isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
if (searchQuery != null) {
dialogsActivity.setInitialSearchString(searchQuery);
}
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
}
}
actionBarLayout.showLastFragment();
if (AndroidUtilities.isTablet()) {
layersActionBarLayout.showLastFragment();
rightActionBarLayout.showLastFragment();
}
}
if (isVoipIntent) {
VoIPFragment.show(this, intentAccount[0]);
}
if (!showGroupVoip && (intent == null || !Intent.ACTION_MAIN.equals(intent.getAction())) && GroupCallActivity.groupCallInstance != null) {
GroupCallActivity.groupCallInstance.dismiss();
}
intent.setAction(null);
return pushOpened;
}
use of org.telegram.ui.ActionBar.Theme in project Telegram-FOSS by Telegram-FOSS-Team.
the class ThemeEditorView method show.
public void show(Activity activity, final Theme.ThemeInfo theme) {
if (Instance != null) {
Instance.destroy();
}
hidden = false;
themeInfo = theme;
windowView = new FrameLayout(activity) {
private float startX;
private float startY;
private boolean dragging;
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getRawX();
float y = event.getRawY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startX = x;
startY = y;
} else if (event.getAction() == MotionEvent.ACTION_MOVE && !dragging) {
if (Math.abs(startX - x) >= AndroidUtilities.getPixelsInCM(0.3f, true) || Math.abs(startY - y) >= AndroidUtilities.getPixelsInCM(0.3f, false)) {
dragging = true;
startX = x;
startY = y;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (!dragging) {
if (editorAlert == null) {
LaunchActivity launchActivity = (LaunchActivity) parentActivity;
ActionBarLayout actionBarLayout = null;
if (AndroidUtilities.isTablet()) {
actionBarLayout = launchActivity.getLayersActionBarLayout();
if (actionBarLayout != null && actionBarLayout.fragmentsStack.isEmpty()) {
actionBarLayout = null;
}
if (actionBarLayout == null) {
actionBarLayout = launchActivity.getRightActionBarLayout();
if (actionBarLayout != null && actionBarLayout.fragmentsStack.isEmpty()) {
actionBarLayout = null;
}
}
}
if (actionBarLayout == null) {
actionBarLayout = launchActivity.getActionBarLayout();
}
if (actionBarLayout != null) {
BaseFragment fragment;
if (!actionBarLayout.fragmentsStack.isEmpty()) {
fragment = actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1);
} else {
fragment = null;
}
if (fragment != null) {
ArrayList<ThemeDescription> items = fragment.getThemeDescriptions();
if (items != null) {
editorAlert = new EditorAlert(parentActivity, items);
editorAlert.setOnDismissListener(dialog -> {
});
editorAlert.setOnDismissListener(dialog -> {
editorAlert = null;
show();
});
editorAlert.show();
hide();
}
}
}
}
}
}
if (dragging) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float dx = (x - startX);
float dy = (y - startY);
windowLayoutParams.x += dx;
windowLayoutParams.y += dy;
int maxDiff = editorWidth / 2;
if (windowLayoutParams.x < -maxDiff) {
windowLayoutParams.x = -maxDiff;
} else if (windowLayoutParams.x > AndroidUtilities.displaySize.x - windowLayoutParams.width + maxDiff) {
windowLayoutParams.x = AndroidUtilities.displaySize.x - windowLayoutParams.width + maxDiff;
}
float alpha = 1.0f;
if (windowLayoutParams.x < 0) {
alpha = 1.0f + windowLayoutParams.x / (float) maxDiff * 0.5f;
} else if (windowLayoutParams.x > AndroidUtilities.displaySize.x - windowLayoutParams.width) {
alpha = 1.0f - (windowLayoutParams.x - AndroidUtilities.displaySize.x + windowLayoutParams.width) / (float) maxDiff * 0.5f;
}
if (windowView.getAlpha() != alpha) {
windowView.setAlpha(alpha);
}
maxDiff = 0;
if (windowLayoutParams.y < -maxDiff) {
windowLayoutParams.y = -maxDiff;
} else if (windowLayoutParams.y > AndroidUtilities.displaySize.y - windowLayoutParams.height + maxDiff) {
windowLayoutParams.y = AndroidUtilities.displaySize.y - windowLayoutParams.height + maxDiff;
}
windowManager.updateViewLayout(windowView, windowLayoutParams);
startX = x;
startY = y;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
dragging = false;
animateToBoundsMaybe();
}
}
return true;
}
};
windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Context.MODE_PRIVATE);
int sidex = preferences.getInt("sidex", 1);
int sidey = preferences.getInt("sidey", 0);
float px = preferences.getFloat("px", 0);
float py = preferences.getFloat("py", 0);
try {
windowLayoutParams = new WindowManager.LayoutParams();
windowLayoutParams.width = editorWidth;
windowLayoutParams.height = editorHeight;
windowLayoutParams.x = getSideCoord(true, sidex, px, editorWidth);
windowLayoutParams.y = getSideCoord(false, sidey, py, editorHeight);
windowLayoutParams.format = PixelFormat.TRANSLUCENT;
windowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
windowManager.addView(windowView, windowLayoutParams);
} catch (Exception e) {
FileLog.e(e);
return;
}
wallpaperUpdater = new WallpaperUpdater(activity, null, new WallpaperUpdater.WallpaperUpdaterDelegate() {
@Override
public void didSelectWallpaper(File file, Bitmap bitmap, boolean gallery) {
Theme.setThemeWallpaper(themeInfo, bitmap, file);
}
@Override
public void needOpenColorPicker() {
for (int a = 0; a < currentThemeDesription.size(); a++) {
ThemeDescription description = currentThemeDesription.get(a);
description.startEditing();
if (a == 0) {
editorAlert.colorPicker.setColor(description.getCurrentColor());
}
}
editorAlert.setColorPickerVisible(true);
}
});
Instance = this;
parentActivity = activity;
showWithAnimation();
}
Aggregations