diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle index 6919524a6a..7ee1990f72 100644 --- a/TMessagesProj/build.gradle +++ b/TMessagesProj/build.gradle @@ -15,11 +15,11 @@ repositories { } def verName = "10.14.2" -def verCode = 1183 +def verCode = 1184 -def officialVer = "10.14.2" -def officialCode = 4911 +def officialVer = "10.14.3" +def officialCode = 4927 def serviceAccountCredentialsFile = rootProject.file("service_account_credentials.json") diff --git a/TMessagesProj/jni/gifvideo.cpp b/TMessagesProj/jni/gifvideo.cpp index b651482904..c3bc4ff658 100644 --- a/TMessagesProj/jni/gifvideo.cpp +++ b/TMessagesProj/jni/gifvideo.cpp @@ -840,7 +840,7 @@ enum PARAM_NUM { PARAM_NUM_COUNT = 11, }; -extern "C" JNIEXPORT void JNICALL Java_org_telegram_ui_Components_AnimatedFileDrawable_getVideoInfo(JNIEnv *env, jclass clazz,jint sdkVersion, jstring src, jintArray data) { +extern "C" JNIEXPORT void JNICALL Java_org_telegram_ui_Components_AnimatedFileDrawable_getVideoInfo(JNIEnv *env, jclass clazz, jint sdkVersion, jstring src, jintArray data) { VideoInfo *info = new VideoInfo(); char const *srcString = env->GetStringUTFChars(src, 0); diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml index 366bcf23d6..2e2f686c7b 100644 --- a/TMessagesProj/src/main/AndroidManifest.xml +++ b/TMessagesProj/src/main/AndroidManifest.xml @@ -121,6 +121,19 @@ + + + + + + + + + + + + + segments = new ArrayList<>(uri.getPathSegments()); - if (segments.size() > 0 && segments.get(0).equals("s")) { - segments.remove(0); - } - if (segments.size() > 0) { - if (segments.size() >= 3 && "s".equals(segments.get(1))) { - return false; - } else if (segments.size() > 1) { - return !TextUtils.isEmpty(segments.get(1)); - } else if (segments.size() == 1) { - return !TextUtils.isEmpty(uri.getQueryParameter("startapp")); + String host = uri.getHost().toLowerCase(); + Matcher prefixMatcher = LaunchActivity.PREFIX_T_ME_PATTERN.matcher(host); + boolean isPrefix = prefixMatcher.find(); + if (host.equals("telegram.me") || host.equals("t.me") || host.equals("telegram.dog") || isPrefix) { + ArrayList segments = new ArrayList<>(uri.getPathSegments()); + if (segments.size() > 0 && segments.get(0).equals("s")) { + segments.remove(0); + } + if (segments.size() > 0) { + if (segments.size() >= 3 && "s".equals(segments.get(1))) { + return false; + } else if (segments.size() > 1) { + final String segment = segments.get(1); + if (TextUtils.isEmpty(segment)) return false; + switch (segment) { + case "joinchat": + case "login": + case "addstickers": + case "addemoji": + case "msg": + case "share": + case "confirmphone": + case "setlanguage": + case "addtheme": + case "boost": + case "c": + case "contact": + case "folder": + case "addlist": + return false; + } + return true; + } else if (segments.size() == 1) { + return !TextUtils.isEmpty(uri.getQueryParameter("startapp")); + } } } break; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java index 9021f002f0..49bbc310f5 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java @@ -389,19 +389,22 @@ public String getInviteText(int contacts) { } public void checkAppAccount() { - AccountManager am = AccountManager.get(ApplicationLoader.applicationContext); - if (getUserConfig().isClientActivated()) { - readContacts(); - if (systemAccount == null && !NekoConfig.disableSystemAccount.Bool()) { - try { - TLRPC.User user = getUserConfig().getCurrentUser(); - systemAccount = new Account(formatName(user.first_name, user.last_name), BuildConfig.APPLICATION_ID); - am.addAccountExplicitly(systemAccount, "", null); - } catch (Exception e) { - FileLog.e(e); + systemAccount = null; + Utilities.globalQueue.postRunnable(() -> { + AccountManager am = AccountManager.get(ApplicationLoader.applicationContext); + if (getUserConfig().isClientActivated()) { + readContacts(); + if (systemAccount == null && !NekoConfig.disableSystemAccount.Bool()) { + try { + TLRPC.User user = getUserConfig().getCurrentUser(); + systemAccount = new Account(formatName(user.first_name, user.last_name), BuildConfig.APPLICATION_ID); + am.addAccountExplicitly(systemAccount, "", null); + } catch (Exception e) { + FileLog.e(e); + } } } - } + }); } public void deleteUnknownAppAccounts() { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java index 1b83da29a2..0052b9aafd 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ImageLoader.java @@ -1105,7 +1105,11 @@ public void run() { if ((isAnimatedAvatar(cacheImage.filter) || AUTOPLAY_FILTER.equals(cacheImage.filter)) && !(cacheImage.imageLocation.document instanceof TLRPC.TL_documentEncrypted) && !precache) { TLRPC.Document document = cacheImage.imageLocation.document instanceof TLRPC.Document ? cacheImage.imageLocation.document : null; long size = document != null ? cacheImage.size : cacheImage.imageLocation.currentSize; - fileDrawable = new AnimatedFileDrawable(cacheImage.finalFilePath, fistFrame, notCreateStream ? 0 : size, cacheImage.priority, notCreateStream ? null : document, document == null && !notCreateStream ? cacheImage.imageLocation : null, cacheImage.parentObject, seekTo, cacheImage.currentAccount, false, cacheOptions); + int cacheType = document != null ? 1 : 0; + if (cacheImage.cacheType > 1) { + cacheType = cacheImage.cacheType; + } + fileDrawable = new AnimatedFileDrawable(cacheImage.finalFilePath, fistFrame, notCreateStream ? 0 : size, cacheImage.priority, notCreateStream ? null : document, document == null && !notCreateStream ? cacheImage.imageLocation : null, cacheImage.parentObject, seekTo, cacheImage.currentAccount, false, 0, 0, cacheOptions, cacheType); fileDrawable.setIsWebmSticker(MessageObject.isWebM(document) || MessageObject.isVideoSticker(document) || isAnimatedAvatar(cacheImage.filter)); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java b/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java index 296340bba1..e636895097 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/LocaleController.java @@ -21,6 +21,7 @@ import android.telephony.TelephonyManager; import android.text.TextUtils; import android.text.format.DateFormat; +import android.util.Log; import android.util.Xml; import android.view.Gravity; @@ -29,22 +30,20 @@ import org.telegram.messenger.time.FastDateFormat; import org.telegram.ui.Stars.StarsController; -import org.telegram.ui.Stars.StarsIntroActivity; import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.RestrictedLanguagesSelectActivity; import org.xmlpull.v1.XmlPullParser; +import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; +import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.NumberFormat; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.TextStyle; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; @@ -79,26 +78,291 @@ public static int generateFlagStart() { } public static boolean is24HourFormat = false; - public FastDateFormat formatterDay; - public FastDateFormat formatterConstDay; - public FastDateFormat formatterWeek; - public FastDateFormat formatterWeekLong; - public FastDateFormat formatterDayMonth; - public FastDateFormat formatterYear; - public FastDateFormat formatterYearMax; - public FastDateFormat formatterStats; - public FastDateFormat formatterBannedUntil; - public FastDateFormat formatterBannedUntilThisYear; - public FastDateFormat chatDate; - public FastDateFormat chatFullDate; - public FastDateFormat formatterScheduleDay; - public FastDateFormat formatterScheduleYear; - public FastDateFormat formatterMonthYear; - public FastDateFormat formatterGiveawayCard; - public FastDateFormat formatterBoostExpired; - public FastDateFormat formatterGiveawayMonthDay; - public FastDateFormat formatterGiveawayMonthDayYear; - public FastDateFormat[] formatterScheduleSend = new FastDateFormat[15]; + + private volatile FastDateFormat formatterDay; + public FastDateFormat getFormatterDay() { + if (formatterDay == null) { + synchronized (this) { + if (formatterDay == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + String lang = locale.getLanguage(); + if (lang == null) { + lang = "en"; + } + lang = lang.toLowerCase(); + formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, (is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H)).replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm"), (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm")); + } + } + } + return formatterDay; + } + + private volatile FastDateFormat formatterConstDay; + public FastDateFormat getFormatterConstDay() { + if (formatterConstDay == null) { + synchronized (this) { + if (formatterConstDay == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + String lang = locale.getLanguage(); + if (lang == null) { + lang = "en"; + } + lang = lang.toLowerCase(); + formatterConstDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm"), (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm")); + } + } + } + return formatterConstDay; + } + + private volatile FastDateFormat formatterWeek; + public FastDateFormat getFormatterWeek() { + if (formatterWeek == null) { + synchronized (this) { + if (formatterWeek == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE"); + } + } + } + return formatterWeek; + } + + private volatile FastDateFormat formatterWeekLong; + public FastDateFormat getFormatterWeekLong() { + if (formatterWeekLong == null) { + synchronized (this) { + if (formatterWeekLong == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterWeekLong = createFormatter(locale, getStringInternal("formatterWeekLong", R.string.formatterWeekLong), "EEEE"); + } + } + } + return formatterWeekLong; + } + + private volatile FastDateFormat formatterDayMonth; + public FastDateFormat getFormatterDayMonth() { + if (formatterDayMonth == null) { + synchronized (this) { + if (formatterDayMonth == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterDayMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM"); + } + } + } + return formatterDayMonth; + } + + private volatile FastDateFormat formatterYear; + public FastDateFormat getFormatterYear() { + if (formatterYear == null) { + synchronized (this) { + if (formatterYear == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy"); + } + } + } + return formatterYear; + } + + private volatile FastDateFormat formatterYearMax; + public FastDateFormat getFormatterYearMax() { + if (formatterYearMax == null) { + synchronized (this) { + if (formatterYearMax == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy"); + } + } + } + return formatterYearMax; + } + + private volatile FastDateFormat formatterStats; + public FastDateFormat getFormatterStats() { + if (formatterStats == null) { + synchronized (this) { + if (formatterStats == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterStats = createFormatter(locale, is24HourFormat ? getStringInternal("formatterStats24H", R.string.formatterStats24H) : getStringInternal("formatterStats12H", R.string.formatterStats12H), is24HourFormat ? "MMM dd yyyy, HH:mm" : "MMM dd yyyy, h:mm a"); + } + } + } + return formatterStats; + } + + private volatile FastDateFormat formatterBannedUntil; + public FastDateFormat getFormatterBannedUntil() { + if (formatterBannedUntil == null) { + synchronized (this) { + if (formatterBannedUntil == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterBannedUntil = createFormatter(locale, is24HourFormat ? getStringInternal("formatterBannedUntil24H", R.string.formatterBannedUntil24H) : getStringInternal("formatterBannedUntil12H", R.string.formatterBannedUntil12H), is24HourFormat ? "MMM dd yyyy, HH:mm" : "MMM dd yyyy, h:mm a"); + } + } + } + return formatterBannedUntil; + } + + private volatile FastDateFormat formatterBannedUntilThisYear; + public FastDateFormat getFormatterBannedUntilThisYear() { + if (formatterBannedUntilThisYear == null) { + synchronized (this) { + if (formatterBannedUntilThisYear == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterBannedUntilThisYear = createFormatter(locale, is24HourFormat ? getStringInternal("formatterBannedUntilThisYear24H", R.string.formatterBannedUntilThisYear24H) : getStringInternal("formatterBannedUntilThisYear12H", R.string.formatterBannedUntilThisYear12H), is24HourFormat ? "MMM dd, HH:mm" : "MMM dd, h:mm a"); + } + } + } + return formatterBannedUntilThisYear; + } + + private volatile FastDateFormat chatDate; + public FastDateFormat getChatDate() { + if (chatDate == null) { + synchronized (this) { + if (chatDate == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM"); + } + } + } + return chatDate; + } + + private volatile FastDateFormat chatFullDate; + public FastDateFormat getChatFullDate() { + if (chatFullDate == null) { + synchronized (this) { + if (chatFullDate == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy"); + } + } + } + return chatFullDate; + } + + private volatile FastDateFormat formatterScheduleDay; + public FastDateFormat getFormatterScheduleDay() { + if (formatterScheduleDay == null) { + synchronized (this) { + if (formatterScheduleDay == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterScheduleDay = createFormatter(locale, getStringInternal("formatDateSchedule", R.string.formatDateSchedule), "MMM d"); + } + } + } + return formatterScheduleDay; + } + + private volatile FastDateFormat formatterScheduleYear; + public FastDateFormat getFormatterScheduleYear() { + if (formatterScheduleYear == null) { + synchronized (this) { + if (formatterScheduleYear == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterScheduleYear = createFormatter(locale, getStringInternal("formatDateScheduleYear", R.string.formatDateScheduleYear), "MMM d yyyy"); + } + } + } + return formatterScheduleYear; + } + + private volatile FastDateFormat formatterMonthYear; + public FastDateFormat getFormatterMonthYear() { + if (formatterMonthYear == null) { + synchronized (this) { + if (formatterMonthYear == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMM yyyy"); + } + } + } + return formatterMonthYear; + } + + private volatile FastDateFormat formatterGiveawayCard; + public FastDateFormat getFormatterGiveawayCard() { + if (formatterGiveawayCard == null) { + synchronized (this) { + if (formatterGiveawayCard == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterGiveawayCard = createFormatter(locale, getStringInternal("formatterGiveawayCard", R.string.formatterGiveawayCard), "dd MMM yyyy"); + } + } + } + return formatterGiveawayCard; + } + + private volatile FastDateFormat formatterBoostExpired; + public FastDateFormat getFormatterBoostExpired() { + if (formatterBoostExpired == null) { + synchronized (this) { + if (formatterBoostExpired == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterBoostExpired = createFormatter(locale, getStringInternal("formatterBoostExpired", R.string.formatterBoostExpired), "MMM dd, yyyy"); + } + } + } + return formatterBoostExpired; + } + + private volatile FastDateFormat formatterGiveawayMonthDay; + public FastDateFormat getFormatterGiveawayMonthDay() { + if (formatterGiveawayMonthDay == null) { + synchronized (this) { + if (formatterGiveawayMonthDay == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterGiveawayMonthDay = createFormatter(locale, getStringInternal("formatterGiveawayMonthDay", R.string.formatterGiveawayMonthDay), "MMMM dd"); + } + } + } + return formatterGiveawayMonthDay; + } + + private volatile FastDateFormat formatterGiveawayMonthDayYear; + public FastDateFormat getFormatterGiveawayMonthDayYear() { + if (formatterGiveawayMonthDayYear == null) { + synchronized (this) { + if (formatterGiveawayMonthDayYear == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + formatterGiveawayMonthDayYear = createFormatter(locale, getStringInternal("formatterGiveawayMonthDayYear", R.string.formatterGiveawayMonthDayYear), "MMMM dd, yyyy"); + } + } + } + return formatterGiveawayMonthDayYear; + } + + private final FastDateFormat[] formatterScheduleSend = new FastDateFormat[15]; + public FastDateFormat getFormatterScheduleSend(int n) { + if (n < 0 || n >= formatterScheduleSend.length) + return null; + if (formatterScheduleSend[n] == null) { + final Locale locale = currentLocale == null ? Locale.getDefault() : currentLocale; + switch (n) { + case 0: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("SendTodayAt", R.string.SendTodayAt), "'Send today at' HH:mm"); break; + case 1: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("SendDayAt", R.string.SendDayAt), "'Send on' MMM d 'at' HH:mm"); break; + case 2: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("SendDayYearAt", R.string.SendDayYearAt), "'Send on' MMM d yyyy 'at' HH:mm"); break; + case 3: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("RemindTodayAt", R.string.RemindTodayAt), "'Remind today at' HH:mm"); break; + case 4: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("RemindDayAt", R.string.RemindDayAt), "'Remind on' MMM d 'at' HH:mm"); break; + case 5: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("RemindDayYearAt", R.string.RemindDayYearAt), "'Remind on' MMM d yyyy 'at' HH:mm"); break; + case 6: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartTodayAt", R.string.StartTodayAt), "'Start today at' HH:mm"); break; + case 7: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartDayAt", R.string.StartDayAt), "'Start on' MMM d 'at' HH:mm"); break; + case 8: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartDayYearAt", R.string.StartDayYearAt), "'Start on' MMM d yyyy 'at' HH:mm"); break; + case 9: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartShortTodayAt", R.string.StartShortTodayAt), "'Today,' HH:mm"); break; + case 10: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartShortDayAt", R.string.StartShortDayAt), "MMM d',' HH:mm"); break; + case 11: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartShortDayYearAt", R.string.StartShortDayYearAt), "MMM d yyyy, HH:mm"); break; + case 12: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartsTodayAt", R.string.StartsTodayAt), "'Starts today at' HH:mm"); break; + case 13: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartsDayAt", R.string.StartsDayAt), "'Starts on' MMM d 'at' HH:mm"); break; + case 14: formatterScheduleSend[n] = createFormatter(locale, getStringInternal("StartsDayYearAt", R.string.StartsDayYearAt), "'Starts on' MMM d yyyy 'at' HH:mm"); break; + } + } + return formatterScheduleSend[n]; + } + private static HashMap resourcesCacheMap = new HashMap<>(); @@ -125,7 +389,7 @@ private class TimeZoneChangedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ApplicationLoader.applicationHandler.post(() -> { - if (!formatterDayMonth.getTimeZone().equals(TimeZone.getDefault())) { + if (!getFormatterDayMonth().getTimeZone().equals(TimeZone.getDefault())) { LocaleController.getInstance().recreateFormatters(); } }); @@ -955,7 +1219,7 @@ private HashMap getLocaleFileStrings(File file, boolean preserve if (!file.exists()) { return new HashMap<>(); } - HashMap stringMap = new HashMap<>(); + HashMap stringMap = new HashMap<>(10_000); XmlPullParser parser = Xml.newPullParser(); //AndroidUtilities.copyFile(file, new File(ApplicationLoader.applicationContext.getExternalFilesDir(null), "locale10.xml")); stream = new FileInputStream(file); @@ -1770,13 +2034,13 @@ public static String formatDateChat(long date, boolean checkYear) { if (usePersianCalendar) { return persianDate.getPersianMonthDay(); } else { - return getInstance().chatDate.format(date); + return getInstance().getChatDate().format(date); } } else { if (usePersianCalendar) { return persianDate.getPersianNormalDate(); } else { - return getInstance().chatFullDate.format(date); + return getInstance().getChatFullDate().format(date); } } } catch (Exception e) { @@ -1797,9 +2061,9 @@ public static String formatSmallDateChat(long date, boolean full) { calendar.setTimeInMillis(date); if (!full && currentYear == calendar.get(Calendar.YEAR)) { - return getInstance().formatterDayMonth.format(date); + return getInstance().getFormatterDayMonth().format(date); } - return getInstance().formatterDayMonth.format(date) + ", " + calendar.get(Calendar.YEAR); + return getInstance().getFormatterDayMonth().format(date) + ", " + calendar.get(Calendar.YEAR); } catch (Exception e) { FileLog.e(e); } @@ -1817,13 +2081,13 @@ public static String formatDate(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (dateDay == day && year == dateYear) { - return getInstance().formatterDay.format(new Date(date)); + return getInstance().getFormatterDay().format(new Date(date)); } else if (dateDay + 1 == day && year == dateYear) { return getString("Yesterday", R.string.Yesterday); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return getInstance().formatterDayMonth.format(new Date(date)); + return getInstance().getFormatterDayMonth().format(new Date(date)); } else { - return getInstance().formatterYear.format(new Date(date)); + return getInstance().getFormatterYear().format(new Date(date)); } } catch (Exception e) { FileLog.e(e); @@ -1843,16 +2107,16 @@ public static String formatDateAudio(long date, boolean shortFormat) { if (dateDay == day && year == dateYear) { if (shortFormat) { - return LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().getFormatterDay().format(new Date(date))); } } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -1871,13 +2135,13 @@ public static String formatSeenDate(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (dateDay == day && year == dateYear) { - return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().getFormatterDay().format(new Date(date))); } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -1896,13 +2160,13 @@ public static String formatPmSeenDate(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (dateDay == day && year == dateYear) { - return LocaleController.formatString(R.string.PmReadTodayAt, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString(R.string.PmReadTodayAt, getInstance().getFormatterDay().format(new Date(date))); } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString(R.string.PmReadYesterdayAt, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString(R.string.PmReadYesterdayAt, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return LocaleController.formatString(R.string.PmReadDateTimeAt, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString(R.string.PmReadDateTimeAt, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString(R.string.PmReadDateTimeAt, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString(R.string.PmReadDateTimeAt, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -1936,9 +2200,9 @@ public static String formatShortDate(long date) { } else if (dateDay + 1 == day && year == dateYear) { return LocaleController.getString(R.string.ShortYesterday); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return getInstance().formatterDayMonth.format(new Date(date)); + return getInstance().getFormatterDayMonth().format(new Date(date)); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -1963,13 +2227,13 @@ public static String formatStoryDate(long date) { int minutesAgo = (int) ((timeInMillis - date) / (1000 * 60)); return LocaleController.formatPluralString("MinutesAgo", minutesAgo, minutesAgo); } else if (dateDay == day && year == dateYear) { - return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().getFormatterDay().format(new Date(date))); } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -1991,20 +2255,20 @@ public static String formatDateCallLog(long date) { persianDate = new PersianDate(date); if (dateDay == day && year == dateYear) { - return getInstance().formatterDay.format(new Date(date)); + return getInstance().getFormatterDay().format(new Date(date)); } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { if (usePersianCalendar) { return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianMonthDay(), getInstance().formatterDay.format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().chatDate.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getChatDate().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } else { if (usePersianCalendar) { return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianNormalDate(), getInstance().formatterDay.format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().chatFullDate.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getChatFullDate().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } } catch (Exception e) { @@ -2024,11 +2288,11 @@ public static String formatStatusExpireDateTime(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (dateDay == day && year == dateYear) { - return LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return getInstance().formatterScheduleDay.format(new Date(date)); + return getInstance().getFormatterScheduleDay().format(new Date(date)); } else { - return getInstance().chatFullDate.format(new Date(date)); + return getInstance().getChatFullDate().format(new Date(date)); } } catch (Exception e) { FileLog.e(e); @@ -2047,13 +2311,13 @@ public static String formatDateTime(long date, boolean useToday) { int dateYear = rightNow.get(Calendar.YEAR); if (dateDay == day && year == dateYear && useToday) { - return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("TodayAtFormattedWithToday", R.string.TodayAtFormattedWithToday, getInstance().getFormatterDay().format(new Date(date))); } else if (dateDay + 1 == day && year == dateYear && useToday) { - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().chatDate.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getChatDate().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().chatFullDate.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getChatFullDate().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } } catch (Exception e) { FileLog.e(e); @@ -2065,9 +2329,9 @@ public static String formatShortDateTime(long date) { try { date *= 1000; if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - return getInstance().formatterScheduleDay.format(new Date(date)) + ", " + getInstance().formatterDay.format(new Date(date)); + return getInstance().getFormatterScheduleDay().format(new Date(date)) + ", " + getInstance().getFormatterDay().format(new Date(date)); } else { - return getInstance().formatterScheduleYear.format(new Date(date)) + ", " + getInstance().formatterDay.format(new Date(date)); + return getInstance().getFormatterScheduleYear().format(new Date(date)) + ", " + getInstance().getFormatterDay().format(new Date(date)); } } catch (Exception e) { FileLog.e(e); @@ -2092,14 +2356,14 @@ public static String formatLocationUpdateDate(long date) { } else if (diff < 60) { return LocaleController.formatPluralString("UpdatedMinutes", diff); } - return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().formatterDay.format(new Date(date)))); + return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().getFormatterDay().format(new Date(date)))); } else if (dateDay + 1 == day && year == dateYear) { - return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date)))); + return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date)))); } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, format); } else { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LocationUpdatedFormatted", R.string.LocationUpdatedFormatted, format); } } catch (Exception e) { @@ -2141,7 +2405,7 @@ public static String formatDateOnline(long date, boolean[] madeShorter) { } if (dateDay == day && year == dateYear) { - return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().formatterDay.format(new Date(date)))); + return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, LocaleController.formatString("TodayAtFormatted", R.string.TodayAtFormatted, getInstance().getFormatterDay().format(new Date(date)))); /*int diff = (int) (ConnectionsManager.getInstance().getCurrentTime() - date) / 60; if (diff < 1) { return LocaleController.getString("LastSeenNow", R.string.LastSeenNow); @@ -2154,26 +2418,26 @@ public static String formatDateOnline(long date, boolean[] madeShorter) { if (madeShorter != null) { madeShorter[0] = true; if (hour <= 6 && dateHour > 18 && is24HourFormat) { - return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, getInstance().getFormatterDay().format(new Date(date))); } - return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date))); + return LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date))); } else { - return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().formatterDay.format(new Date(date)))); + return LocaleController.formatString("LastSeenFormatted", R.string.LastSeenFormatted, LocaleController.formatString("YesterdayAtFormatted", R.string.YesterdayAtFormatted, getInstance().getFormatterDay().format(new Date(date)))); } } else if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { if (usePersianCalendar) { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianMonthDay(), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianMonthDay(), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LastSeenDateFormatted", R.string.LastSeenDateFormatted, format); } else { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LastSeenDateFormatted", R.string.LastSeenDateFormatted, format); } } else { if (usePersianCalendar) { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianNormalDate(), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, persianDate.getPersianNormalDate(), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LastSeenDateFormatted", R.string.LastSeenDateFormatted, format); } else { - String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + String format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); return LocaleController.formatString("LastSeenDateFormatted", R.string.LastSeenDateFormatted, format); } } @@ -2211,40 +2475,28 @@ public void recreateFormatters() { lang.startsWith("ar_") || lang.startsWith("fa_") || lang.startsWith("he_") || lang.startsWith("iw_") || currentLocaleInfo != null && currentLocaleInfo.isRtl; - formatterBoostExpired = createFormatter(locale, getStringInternal("formatterBoostExpired", R.string.formatterBoostExpired), "MMM dd, yyyy"); - formatterGiveawayCard = createFormatter(locale, getStringInternal("formatterGiveawayCard", R.string.formatterGiveawayCard), "dd MMM yyyy"); - formatterGiveawayMonthDay = createFormatter(locale, getStringInternal("formatterGiveawayMonthDay", R.string.formatterGiveawayMonthDay), "MMMM dd"); - formatterGiveawayMonthDayYear = createFormatter(locale, getStringInternal("formatterGiveawayMonthDayYear", R.string.formatterGiveawayMonthDayYear), "MMMM dd, yyyy"); - formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMM yyyy"); - formatterDayMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM"); - formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy"); - formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy"); - chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM"); - chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy"); - formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE"); - formatterWeekLong = createFormatter(locale, getStringInternal("formatterWeekLong", R.string.formatterWeekLong), "EEEE"); - formatterScheduleDay = createFormatter(locale, getStringInternal("formatDateSchedule", R.string.formatDateSchedule), "MMM d"); - formatterScheduleYear = createFormatter(locale, getStringInternal("formatDateScheduleYear", R.string.formatDateScheduleYear), "MMM d yyyy"); - formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, (is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H)).replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm"), (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm")); - formatterConstDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm"), (is24HourFormat ? "HH:mm" : "h:mm a").replace(":mm", NekoConfig.showSeconds.Bool() ? ":mm:ss" : ":mm")); - formatterStats = createFormatter(locale, is24HourFormat ? getStringInternal("formatterStats24H", R.string.formatterStats24H) : getStringInternal("formatterStats12H", R.string.formatterStats12H), is24HourFormat ? "MMM dd yyyy, HH:mm" : "MMM dd yyyy, h:mm a"); - formatterBannedUntil = createFormatter(locale, is24HourFormat ? getStringInternal("formatterBannedUntil24H", R.string.formatterBannedUntil24H) : getStringInternal("formatterBannedUntil12H", R.string.formatterBannedUntil12H), is24HourFormat ? "MMM dd yyyy, HH:mm" : "MMM dd yyyy, h:mm a"); - formatterBannedUntilThisYear = createFormatter(locale, is24HourFormat ? getStringInternal("formatterBannedUntilThisYear24H", R.string.formatterBannedUntilThisYear24H) : getStringInternal("formatterBannedUntilThisYear12H", R.string.formatterBannedUntilThisYear12H), is24HourFormat ? "MMM dd, HH:mm" : "MMM dd, h:mm a"); - formatterScheduleSend[0] = createFormatter(locale, getStringInternal("SendTodayAt", R.string.SendTodayAt), "'Send today at' HH:mm"); - formatterScheduleSend[1] = createFormatter(locale, getStringInternal("SendDayAt", R.string.SendDayAt), "'Send on' MMM d 'at' HH:mm"); - formatterScheduleSend[2] = createFormatter(locale, getStringInternal("SendDayYearAt", R.string.SendDayYearAt), "'Send on' MMM d yyyy 'at' HH:mm"); - formatterScheduleSend[3] = createFormatter(locale, getStringInternal("RemindTodayAt", R.string.RemindTodayAt), "'Remind today at' HH:mm"); - formatterScheduleSend[4] = createFormatter(locale, getStringInternal("RemindDayAt", R.string.RemindDayAt), "'Remind on' MMM d 'at' HH:mm"); - formatterScheduleSend[5] = createFormatter(locale, getStringInternal("RemindDayYearAt", R.string.RemindDayYearAt), "'Remind on' MMM d yyyy 'at' HH:mm"); - formatterScheduleSend[6] = createFormatter(locale, getStringInternal("StartTodayAt", R.string.StartTodayAt), "'Start today at' HH:mm"); - formatterScheduleSend[7] = createFormatter(locale, getStringInternal("StartDayAt", R.string.StartDayAt), "'Start on' MMM d 'at' HH:mm"); - formatterScheduleSend[8] = createFormatter(locale, getStringInternal("StartDayYearAt", R.string.StartDayYearAt), "'Start on' MMM d yyyy 'at' HH:mm"); - formatterScheduleSend[9] = createFormatter(locale, getStringInternal("StartShortTodayAt", R.string.StartShortTodayAt), "'Today,' HH:mm"); - formatterScheduleSend[10] = createFormatter(locale, getStringInternal("StartShortDayAt", R.string.StartShortDayAt), "MMM d',' HH:mm"); - formatterScheduleSend[11] = createFormatter(locale, getStringInternal("StartShortDayYearAt", R.string.StartShortDayYearAt), "MMM d yyyy, HH:mm"); - formatterScheduleSend[12] = createFormatter(locale, getStringInternal("StartsTodayAt", R.string.StartsTodayAt), "'Starts today at' HH:mm"); - formatterScheduleSend[13] = createFormatter(locale, getStringInternal("StartsDayAt", R.string.StartsDayAt), "'Starts on' MMM d 'at' HH:mm"); - formatterScheduleSend[14] = createFormatter(locale, getStringInternal("StartsDayYearAt", R.string.StartsDayYearAt), "'Starts on' MMM d yyyy 'at' HH:mm"); + formatterBoostExpired = null; + formatterGiveawayCard = null; + formatterGiveawayMonthDay = null; + formatterGiveawayMonthDayYear = null; + formatterMonthYear = null; + formatterDayMonth = null; + formatterYear = null; + formatterYearMax = null; + chatDate = null; + chatFullDate = null; + formatterWeek = null; + formatterWeekLong = null; + formatterScheduleDay = null; + formatterScheduleYear = null; + formatterDay = null; + formatterConstDay = null; + formatterStats = null; + formatterBannedUntil = null; + formatterBannedUntilThisYear = null; + for (int i = 0; i < formatterScheduleSend.length; ++i) { + formatterScheduleSend[i] = null; + } } public static boolean isRTLCharacter(char ch) { @@ -2284,7 +2536,7 @@ public static String formatStartsTime(long date, int type, boolean needToday) { } else if (type == 4) { num += 12; } - return LocaleController.getInstance().formatterScheduleSend[num].format(calendar.getTimeInMillis()); + return LocaleController.getInstance().getFormatterScheduleSend(num).format(calendar.getTimeInMillis()); } public static String formatSectionDate(long date) { @@ -2335,9 +2587,9 @@ public static String formatDateForBan(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (year == dateYear) { - return getInstance().formatterBannedUntilThisYear.format(new Date(date)); + return getInstance().getFormatterBannedUntilThisYear().format(new Date(date)); } else { - return getInstance().formatterBannedUntil.format(new Date(date)); + return getInstance().getFormatterBannedUntil().format(new Date(date)); } } catch (Exception e) { FileLog.e(e); @@ -2349,7 +2601,7 @@ public static String stringForMessageListDate(long date) { try { date *= 1000; if (Math.abs(System.currentTimeMillis() - date) >= 31536000000L) { - return getInstance().formatterYear.format(new Date(date)); + return getInstance().getFormatterYear().format(new Date(date)); } else { Calendar rightNow = Calendar.getInstance(); int day = rightNow.get(Calendar.DAY_OF_YEAR); @@ -2358,13 +2610,13 @@ public static String stringForMessageListDate(long date) { int dayDiff = dateDay - day; if (dayDiff == 0 || dayDiff == -1 && System.currentTimeMillis() - date < 60 * 60 * 8 * 1000) { - return getInstance().formatterDay.format(new Date(date)); + return getInstance().getFormatterDay().format(new Date(date)); } else if (dayDiff > -7 && dayDiff <= -1) { - return getInstance().formatterWeek.format(new Date(date)); + return getInstance().getFormatterWeek().format(new Date(date)); } else if (usePersianCalendar) { return new PersianDate(date).getPersianMonthDay(); } else { - return getInstance().formatterDayMonth.format(new Date(date)); + return getInstance().getFormatterDayMonth().format(new Date(date)); } } } catch (Exception e) { @@ -2418,9 +2670,9 @@ public static String formatJoined(long date) { date *= 1000; String format; if (Math.abs(System.currentTimeMillis() - date) < 31536000000L) { - format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterDayMonth.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterDayMonth().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } else { - format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date)), getInstance().formatterDay.format(new Date(date))); + format = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().getFormatterYear().format(new Date(date)), getInstance().getFormatterDay().format(new Date(date))); } return formatString("ChannelOtherSubscriberJoined", R.string.ChannelOtherSubscriberJoined, format); } catch (Exception e) { @@ -2433,7 +2685,7 @@ public static String formatImportedDate(long date) { try { date *= 1000; Date dt = new Date(date); - return String.format("%1$s, %2$s", getInstance().formatterYear.format(dt), getInstance().formatterDay.format(dt)); + return String.format("%1$s, %2$s", getInstance().getFormatterYear().format(dt), getInstance().getFormatterDay().format(dt)); } catch (Exception e) { FileLog.e(e); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java index 54f4b2d49a..f1b732b3f3 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessageObject.java @@ -4456,8 +4456,8 @@ private void updateMessageText(AbstractMap users, AbstractMap< } else if (messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { String date; long time = ((long) messageOwner.date) * 1000; - if (LocaleController.getInstance().formatterDay != null && LocaleController.getInstance().formatterYear != null) { - date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(time), LocaleController.getInstance().formatterDay.format(time)); + if (LocaleController.getInstance().getFormatterDay() != null && LocaleController.getInstance().getFormatterYear() != null) { + date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(time), LocaleController.getInstance().getFormatterDay().format(time)); } else { date = "" + messageOwner.date; } @@ -6649,10 +6649,13 @@ public boolean needDrawShareButton() { } else if (messageOwner.fwd_from != null && messageOwner.fwd_from.from_id instanceof TLRPC.TL_peerChannel && !isOutOwner()) { return true; } else if (isFromUser()) { + TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(messageOwner.from_id.user_id); + if (user != null && user.bot && ("reviews_bot".equals(UserObject.getPublicUsername(user)) || "ReviewInsightsBot".equals(UserObject.getPublicUsername(user)))) { + return true; + } if (getMedia(messageOwner) instanceof TLRPC.TL_messageMediaEmpty || getMedia(messageOwner) == null || getMedia(messageOwner) instanceof TLRPC.TL_messageMediaWebPage && !(getMedia(messageOwner).webpage instanceof TLRPC.TL_webPage)) { return false; } - TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(messageOwner.from_id.user_id); if (user != null && user.bot && !hasExtendedMedia()) { return true; } @@ -8063,6 +8066,9 @@ public static boolean shouldEncryptPhotoOrVideo(int currentAccount, TLRPC.Messag if (message != null && message.media != null && (isVoiceDocument(getDocument(message)) || isRoundVideoMessage(message)) && message.media.ttl_seconds == 0x7FFFFFFF) { return true; } + if (getMedia(message) instanceof TLRPC.TL_messageMediaPaidMedia) { + return true; + } // if (MessagesController.getInstance(currentAccount).isChatNoForwards(getChatId(message)) || message != null && message.noforwards) { // return true; // } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java index e382b19c86..f04d6f7ba6 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java @@ -11704,7 +11704,7 @@ private void migrateDialogs(int offset, int offsetDate, long offsetUser, long of req.offset_id = offset; req.offset_date = offsetDate; if (BuildVars.LOGS_ENABLED) { - FileLog.d("start migrate with id " + offset + " date " + LocaleController.getInstance().formatterStats.format((long) offsetDate * 1000)); + FileLog.d("start migrate with id " + offset + " date " + LocaleController.getInstance().getFormatterStats().format((long) offsetDate * 1000)); } if (offset == 0) { req.offset_peer = new TLRPC.TL_inputPeerEmpty(); @@ -11733,14 +11733,14 @@ private void migrateDialogs(int offset, int offsetDate, long offsetUser, long of for (int a = 0; a < dialogsRes.messages.size(); a++) { TLRPC.Message message = dialogsRes.messages.get(a); if (BuildVars.LOGS_ENABLED) { - FileLog.d("search migrate id " + message.id + " date " + LocaleController.getInstance().formatterStats.format((long) message.date * 1000)); + FileLog.d("search migrate id " + message.id + " date " + LocaleController.getInstance().getFormatterStats().format((long) message.date * 1000)); } if (lastMessage == null || message.date < lastMessage.date) { lastMessage = message; } } if (BuildVars.LOGS_ENABLED) { - FileLog.d("migrate step with id " + lastMessage.id + " date " + LocaleController.getInstance().formatterStats.format((long) lastMessage.date * 1000)); + FileLog.d("migrate step with id " + lastMessage.id + " date " + LocaleController.getInstance().getFormatterStats().format((long) lastMessage.date * 1000)); } if (dialogsRes.dialogs.size() >= 100) { offsetId = lastMessage.id; @@ -11818,7 +11818,7 @@ private void migrateDialogs(int offset, int offsetDate, long offsetUser, long of } offsetId = -1; if (BuildVars.LOGS_ENABLED) { - FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().formatterStats.format((long) date * 1000)); + FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().getFormatterStats().format((long) date * 1000)); } } dialogsRes.messages.remove(a); @@ -11843,7 +11843,7 @@ private void migrateDialogs(int offset, int offsetDate, long offsetUser, long of } offsetId = -1; if (BuildVars.LOGS_ENABLED) { - FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().formatterStats.format((long) date * 1000)); + FileLog.d("migrate stop due to reached loaded dialogs " + LocaleController.getInstance().getFormatterStats().format((long) date * 1000)); } } } @@ -20152,6 +20152,10 @@ public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment) { } public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObject originalMessage) { + return checkCanOpenChat(bundle, fragment, originalMessage, null); + } + + public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObject originalMessage, Browser.Progress progress) { if (bundle == null || fragment == null) { return true; } @@ -20181,7 +20185,13 @@ public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObj if (messageId != 0 && originalMessage != null && chat != null && chat.access_hash == 0) { long did = originalMessage.getDialogId(); if (!DialogObject.isEncryptedDialog(did)) { - AlertDialog progressDialog = new AlertDialog(fragment.getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); + final AlertDialog progressDialog; + if (progress != null) { + progressDialog = null; + progress.init(); + } else { + progressDialog = new AlertDialog(fragment.getParentActivity(), AlertDialog.ALERT_TYPE_SPINNER); + } TLObject req; if (did < 0) { chat = getChat(-did); @@ -20201,7 +20211,12 @@ public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObj if (response != null) { AndroidUtilities.runOnUIThread(() -> { try { - progressDialog.dismiss(); + if (progressDialog != null) { + progressDialog.dismiss(); + } + if (progress != null) { + progress.end(); + } } catch (Exception e) { FileLog.e(e); } @@ -20213,14 +20228,38 @@ public boolean checkCanOpenChat(Bundle bundle, BaseFragment fragment, MessageObj }); } }); - progressDialog.setOnCancelListener(dialog -> { - getConnectionsManager().cancelRequest(reqId, true); - fragment.setVisibleDialog(null); - }); - fragment.setVisibleDialog(progressDialog); - progressDialog.show(); + if (progressDialog != null) { + progressDialog.setOnCancelListener(dialog -> { + getConnectionsManager().cancelRequest(reqId, true); + fragment.setVisibleDialog(null); + }); + fragment.setVisibleDialog(progressDialog); + progressDialog.show(); + } else { + progress.onCancel(() -> { + getConnectionsManager().cancelRequest(reqId, true); + fragment.setVisibleDialog(null); + }); + progress.init(); + } return false; } + } else if (messageId != 0 && originalMessage != null && progress != null) { + progress.init(); + progress.onCancel(ensureMessagesLoaded(-chatId, messageId, new MessagesLoadedCallback() { + @Override + public void onMessagesLoaded(boolean fromCache) { + progress.end(); + fragment.presentFragment(new ChatActivity(bundle), true); + } + + @Override + public void onError() { + progress.end(); + fragment.presentFragment(new ChatActivity(bundle), true); + } + })); + return false; } return true; } @@ -20356,7 +20395,7 @@ public void openByUserName(String username, BaseFragment fragment, int type, Bro } } - public void ensureMessagesLoaded(long dialogId, int messageId, MessagesLoadedCallback callback) { + public Runnable ensureMessagesLoaded(long dialogId, int messageId, MessagesLoadedCallback callback) { SharedPreferences sharedPreferences = MessagesController.getNotificationsSettings(currentAccount); if (messageId == 0) { messageId = sharedPreferences.getInt("diditem" + dialogId, 0); @@ -20376,13 +20415,17 @@ public void ensureMessagesLoaded(long dialogId, int messageId, MessagesLoadedCal if (chatId != 0) { currentChat = getMessagesController().getChat(chatId); if (currentChat == null) { + final boolean[] cancelled = new boolean[1]; + final Runnable[] cancel = new Runnable[1]; MessagesStorage messagesStorage = getMessagesStorage(); messagesStorage.getStorageQueue().postRunnable(() -> { + if (cancelled[0]) return; TLRPC.Chat chat = messagesStorage.getChat(chatId); AndroidUtilities.runOnUIThread(() -> { + if (cancelled[0]) return; if (chat != null) { getMessagesController().putChat(chat, true); - ensureMessagesLoaded(dialogId, finalMessageId, callback); + cancel[0] = ensureMessagesLoaded(dialogId, finalMessageId, callback); } else { if (callback != null) { callback.onError(); @@ -20390,7 +20433,12 @@ public void ensureMessagesLoaded(long dialogId, int messageId, MessagesLoadedCal } }); }); - return; + return () -> { + cancelled[0] = true; + if (cancel[0] != null) { + cancel[0].run(); + } + }; } } @@ -20436,6 +20484,8 @@ public void didReceivedNotification(int id, int account, Object... args) { } else { loadMessagesInternal(dialogId, 0, true, count, finalMessageId, 0, true, 0, classGuid, 2, 0, 0, 0, -1, 0, 0, 0, false, 0, true, false, false, null, 0L); } + + return () -> getConnectionsManager().cancelRequestsForGuid(classGuid); } public int getChatPendingRequestsOnClosed(long chatId) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java index 4c8991dcb2..fc1027a79c 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/NotificationsController.java @@ -1845,7 +1845,7 @@ private String getShortStringForMessage(MessageObject messageObject, String[] us } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { return LocaleController.formatString("NotificationContactNewPhoto", R.string.NotificationContactNewPhoto, name); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { - String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(((long) messageObject.messageOwner.date) * 1000), LocaleController.getInstance().formatterDay.format(((long) messageObject.messageOwner.date) * 1000)); + String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(((long) messageObject.messageOwner.date) * 1000), LocaleController.getInstance().getFormatterDay().format(((long) messageObject.messageOwner.date) * 1000)); return LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, getUserConfig().getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent) { return messageObject.messageText.toString(); @@ -2446,7 +2446,7 @@ private String getStringForMessage(MessageObject messageObject, boolean shortMes } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) { msg = LocaleController.formatString("NotificationContactNewPhoto", R.string.NotificationContactNewPhoto, name); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { - String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(((long) messageObject.messageOwner.date) * 1000), LocaleController.getInstance().formatterDay.format(((long) messageObject.messageOwner.date) * 1000)); + String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(((long) messageObject.messageOwner.date) * 1000), LocaleController.getInstance().getFormatterDay().format(((long) messageObject.messageOwner.date) * 1000)); msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, getUserConfig().getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address); } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent) { msg = messageObject.messageText.toString(); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java index c79ec0e188..2e91f41541 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java @@ -5960,6 +5960,31 @@ public boolean isSendingMessage(int mid) { return sendingMessages.indexOfKey(mid) >= 0 || editingMessages.indexOfKey(mid) >= 0; } + + public boolean isSendingPaidMessage(int mid, int index) { + DelayedMessage delayedMessage = null; + if (delayedMessages != null) { + for (ArrayList arr : delayedMessages.values()) { + if (arr == null) continue; + for (DelayedMessage m : arr) { + if (m.messages == null) continue; + for (TLRPC.Message msg : m.messages) { + if (msg != null && msg.id == mid) { + delayedMessage = m; + break; + } + } + if (delayedMessage != null) break; + } + if (delayedMessage != null) break; + } + } + if (delayedMessage != null && index >= 0 && index < delayedMessage.messages.size()) { + mid = delayedMessage.messages.get(index).id; + } + return sendingMessages.indexOfKey(mid) >= 0 || editingMessages.indexOfKey(mid) >= 0; + } + public boolean isSendingMessageIdDialog(long did) { return sendingMessagesIdDialogs.get(did, 0) > 0; } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java index ab0f2cfcfb..374e5c8ea2 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java @@ -474,6 +474,10 @@ public static float clamp(float value, float maxValue, float minValue) { return Math.max(Math.min(value, maxValue), minValue); } + public static float clamp01(float value) { + return clamp(value, 1f, 0f); + } + public static double clamp(double value, double maxValue, double minValue) { if (Double.isNaN(value)) { return minValue; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/browser/Browser.java b/TMessagesProj/src/main/java/org/telegram/messenger/browser/Browser.java index 0bda6288ea..7d3f587ac0 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/browser/Browser.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/browser/Browser.java @@ -13,6 +13,7 @@ import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.BitmapFactory; import android.net.Uri; @@ -248,20 +249,28 @@ public void onCancel(Runnable onCancelListener) { } public static void openUrl(final Context context, Uri uri, final boolean allowCustom, boolean tryTelegraph) { - openUrl(context, uri, allowCustom, tryTelegraph, false, null); + openUrl(context, uri, allowCustom, tryTelegraph, false, null, null); } public static void openUrl(final Context context, Uri uri, final boolean allowCustom, boolean tryTelegraph, Progress inCaseLoading) { - openUrl(context, uri, allowCustom, tryTelegraph, false, inCaseLoading); + openUrl(context, uri, allowCustom, tryTelegraph, false, inCaseLoading, null); } - public static void openUrl(final Context context, Uri uri, final boolean allowCustom, boolean tryTelegraph, boolean forceNotInternalForApps, Progress inCaseLoading) { + public static void openUrl(final Context context, Uri uri, boolean _allowCustom, boolean tryTelegraph, boolean forceNotInternalForApps, Progress inCaseLoading, String browser) { if (context == null || uri == null) { return; } final int currentAccount = UserConfig.selectedAccount; boolean[] forceBrowser = new boolean[]{false}; boolean internalUri = isInternalUri(uri, forceBrowser); + String browserPackage = getBrowserPackageName(browser); + if (isBrowserPackageInstalled(context, browserPackage, uri)) { + tryTelegraph = false; + _allowCustom = false; + } else { + browserPackage = null; + } + final boolean allowCustom = _allowCustom; if (tryTelegraph) { try { String host = AndroidUtilities.getHostAuthority(uri); @@ -437,6 +446,9 @@ public static void openUrl(final Context context, Uri uri, final boolean allowCu ComponentName componentName = new ComponentName(context.getPackageName(), LaunchActivity.class.getName()); intent.setComponent(componentName); } + if (!TextUtils.isEmpty(browserPackage)) { + intent.setPackage(browserPackage); + } intent.putExtra(android.provider.Browser.EXTRA_CREATE_NEW_TAB, true); intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, context.getPackageName()); intent.putExtra("internal", true); @@ -567,7 +579,55 @@ public static boolean isInternalUri(Uri uri, boolean all, boolean[] forceBrowser return false; } - // © ChatGPT. All puns reserved. 🤖📜 + public static String getBrowserPackageName(String browser) { + if (browser == null) return null; + switch (browser) { + case "google-chrome": + case "chrome": + return "com.android.chrome"; + case "mozilla-firefox": + case "firefox": + return "org.mozilla.firefox"; + case "microsoft-edge": + case "edge": + return "com.microsoft.emmx"; + case "opera": + return "com.opera.browser"; + case "opera-mini": + return "com.opera.mini.native"; + case "brave": + case "brave-browser": + return "com.brave.browser"; + case "duckduckgo": + case "duckduckgo-browser": + return "com.duckduckgo.mobile.android"; + case "samsung": + case "samsung-browser": + return "com.sec.android.app.sbrowser"; + case "vivaldi": + case "vivaldi-browser": + return "com.vivaldi.browser"; + case "kiwi": + case "kiwi-browser": + return "com.kiwibrowser.browser"; + case "uc": + case "uc-browser": + return "com.UCMobile.intl"; + case "tor": + case "tor-browser": + return "org.torproject.torbrowser"; + } + return null; + } + + public static boolean isBrowserPackageInstalled(Context context, String packageName, Uri uri) { + if (packageName == null) return false; + PackageManager packageManager = context.getPackageManager(); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + intent.setPackage(packageName); + return packageManager.resolveActivity(intent, 0) != null; + } + public static String replaceHostname(Uri originalUri, String newHostname) { String scheme = originalUri.getScheme(); String userInfo = originalUri.getUserInfo(); diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java index 014559a298..2ad64e1355 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java @@ -13072,6 +13072,7 @@ public static abstract class ChatFull extends TLObject { public int boosts_unrestrict; public StickerSet emojiset; public boolean can_view_revenue; + public boolean can_view_stars_revenue; public boolean paid_media_allowed; public long inviterId; //custom public int invitesCount; //custom @@ -15706,6 +15707,7 @@ public void readParams(AbstractSerializedData stream, boolean exception) { view_forum_as_messages = (flags2 & 64) != 0; restricted_sponsored = (flags2 & 2048) != 0; can_view_revenue = (flags2 & 4096) != 0; + can_view_stars_revenue = (flags2 & 32768) != 0; paid_media_allowed = (flags2 & 16384) != 0; id = stream.readInt64(exception); about = stream.readString(exception); @@ -15868,6 +15870,7 @@ public void serializeToStream(AbstractSerializedData stream) { flags2 = restricted_sponsored ? (flags2 | 2048) : (flags2 &~ 2048); flags2 = can_view_revenue ? (flags2 | 4096) : (flags2 &~ 4096); flags2 = paid_media_allowed ? (flags2 | 16384) : (flags2 &~ 16384); + flags2 = can_view_stars_revenue ? (flags2 | 32768) : (flags2 &~ 32768); stream.writeInt32(flags2); stream.writeInt64(id); stream.writeString(about); @@ -16015,6 +16018,7 @@ public void readParams(AbstractSerializedData stream, boolean exception) { view_forum_as_messages = (flags2 & 64) != 0; restricted_sponsored = (flags2 & 2048) != 0; can_view_revenue = (flags2 & 4096) != 0; + can_view_stars_revenue = (flags2 & 32768) != 0; id = stream.readInt64(exception); about = stream.readString(exception); if ((flags & 1) != 0) { @@ -16172,6 +16176,7 @@ public void serializeToStream(AbstractSerializedData stream) { flags2 = view_forum_as_messages ? (flags2 | 64) : (flags2 &~ 64); flags2 = restricted_sponsored ? (flags2 | 2048) : (flags2 &~ 2048); flags2 = can_view_revenue ? (flags2 | 4096) : (flags2 &~ 4096); + flags2 = can_view_stars_revenue ? (flags2 | 32768) : (flags2 &~ 32768); stream.writeInt32(flags2); stream.writeInt64(id); stream.writeString(about); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java index bc110caa0b..b9a854186f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/ActionBarLayout.java @@ -193,7 +193,7 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { for (int a = 0; a < count; a++) { View child = getChildAt(a); if (!(child instanceof ActionBar)) { - if (child.getFitsSystemWindows()) { + if (child.getFitsSystemWindows() || child instanceof BaseFragment.AttachedSheetWindow) { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, bottomTabsHeight); } else { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, actionBarHeight + bottomTabsHeight); @@ -219,7 +219,7 @@ protected void onLayout(boolean changed, int l, int t, int r, int b) { View child = getChildAt(a); if (!(child instanceof ActionBar)) { FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) child.getLayoutParams(); - if (child.getFitsSystemWindows()) { + if (child.getFitsSystemWindows() || child instanceof BaseFragment.AttachedSheetWindow) { child.layout( layoutParams.leftMargin, layoutParams.topMargin, @@ -827,9 +827,9 @@ protected boolean drawChild(Canvas canvas, View child, long drawingTime) { float opacity = MathUtils.clamp(widthOffset / (float) width, 0, 0.8f); scrimPaint.setColor(Color.argb((int)(0x99 * opacity), 0x00, 0x00, 0x00)); if (overrideWidthOffset != -1) { - canvas.drawRect(0, 0, getWidth(), getHeight() - getBottomTabsHeight(true), scrimPaint); + canvas.drawRect(0, 0, getWidth(), getHeight() * 1.5f, scrimPaint); } else { - canvas.drawRect(clipLeft, 0, clipRight, getHeight() - getBottomTabsHeight(true), scrimPaint); + canvas.drawRect(clipLeft, 0, clipRight, getHeight() * 1.5f, scrimPaint); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AdjustPanLayoutHelper.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AdjustPanLayoutHelper.java index 35989a9156..2565ab4ff3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AdjustPanLayoutHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/AdjustPanLayoutHelper.java @@ -28,6 +28,7 @@ import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AnimationNotificationsLocker; import org.telegram.messenger.UserConfig; +import org.telegram.ui.LaunchActivity; import java.util.ArrayList; import java.util.List; @@ -172,7 +173,11 @@ public void startTransition(int previousHeight, int contentHeight, boolean isKey additionalContentHeight = ((View) viewParent).getHeight() - contentHeight; } } - setViewHeight(Math.max(previousHeight, contentHeight + additionalContentHeight)); + int bottomTabsHeight = 0; + if (LaunchActivity.instance != null && LaunchActivity.instance.getBottomSheetTabs() != null) { + bottomTabsHeight += LaunchActivity.instance.getBottomSheetTabs().getExpandedHeight(); + } + setViewHeight(Math.max(previousHeight, contentHeight + additionalContentHeight + bottomTabsHeight)); resizableView.requestLayout(); onTransitionStart(isKeyboardVisible, previousHeight, contentHeight); @@ -186,7 +191,7 @@ public void startTransition(int previousHeight, int contentHeight, boolean isKey parent.setTranslationY(-dy); onPanTranslationUpdate(dy, 1f, isKeyboardVisible); from = -dy; - to = 0; + to = -bottomTabsHeight; inverse = true; } else { parent.setTranslationY(previousStartOffset); @@ -219,7 +224,7 @@ public void stopTransition() { setViewHeight(ViewGroup.LayoutParams.MATCH_PARENT); viewsToHeightSet.clear(); resizableView.requestLayout(); - onPanTranslationUpdate(0, isKeyboardVisible ? 1f : 0f, isKeyboardVisible); + onPanTranslationUpdate(0, isKeyboardVisible ? 1f : 0f, isKeyboardVisible); parent.setTranslationY(0); onTransitionEnd(); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java index 557de8fd43..8d72ef7870 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BaseFragment.java @@ -98,6 +98,7 @@ public static interface AttachedSheet { public View getWindowView(); public boolean isShown(); public void dismiss(); + default void dismiss(boolean tabs) { dismiss(); } public void release(); public boolean isFullyVisible(); @@ -114,6 +115,8 @@ public static interface AttachedSheet { public void setOnDismissListener(Runnable onDismiss); } + public static interface AttachedSheetWindow {} + @Nullable public StoryViewer getLastStoryViewer() { if (sheetsStack == null || sheetsStack.isEmpty()) @@ -149,7 +152,7 @@ public void clearSheets() { if (sheetsStack == null || sheetsStack.isEmpty()) return; for (int i = sheetsStack.size() - 1; i >= 0; --i) { - sheetsStack.get(i).release(); + sheetsStack.get(i).dismiss(true); } sheetsStack.clear(); } @@ -289,7 +292,7 @@ public void clearViews() { } public void onRemoveFromParent() { - + clearSheets(); } public void setParentFragment(BaseFragment fragment) { @@ -672,6 +675,16 @@ public void onBecomeFullyVisible() { } } } + if (fullyVisibleListener != null) { + Runnable c = fullyVisibleListener; + fullyVisibleListener = null; + c.run(); + } + } + + private Runnable fullyVisibleListener; + public void whenFullyVisible(Runnable callback) { + fullyVisibleListener = callback; } public int getPreviewHeight() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabs.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabs.java index 99ab9c182f..cf67886164 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabs.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabs.java @@ -6,25 +6,19 @@ import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; -import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Path; -import android.graphics.PixelFormat; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Bundle; -import android.util.Log; import android.view.MotionEvent; import android.view.View; -import android.webkit.WebView; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import androidx.core.graphics.ColorUtils; -import org.checkerframework.checker.units.qual.A; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ContactsController; import org.telegram.messenger.FileLog; @@ -38,7 +32,6 @@ import org.telegram.ui.ChatActivity; import org.telegram.ui.Components.AnimatedColor; import org.telegram.ui.Components.AnimatedFloat; -import org.telegram.ui.Components.AnimatedTextView; import org.telegram.ui.Components.CubicBezierInterpolator; import org.telegram.ui.Components.Text; import org.telegram.ui.LaunchActivity; @@ -46,7 +39,6 @@ import org.telegram.ui.bots.BotWebViewContainer; import org.telegram.ui.bots.BotWebViewSheet; -import java.io.CharArrayReader; import java.util.ArrayList; import java.util.HashMap; @@ -92,12 +84,16 @@ public void openTab(WebTabData tab) { } boolean closed = closeAttachedSheets(); Utilities.Callback open = fragment -> { + if (fragment == null) return; if (fragment instanceof ChatActivity) { if (((ChatActivity) fragment).getChatActivityEnterView() != null) { ((ChatActivity) fragment).getChatActivityEnterView().closeKeyboard(); ((ChatActivity) fragment).getChatActivityEnterView().hidePopup(true, false); } } + if (fragment.getContext() == null) { + return; + } if (AndroidUtilities.isTablet()) { BotWebViewSheet sheet = new BotWebViewSheet(fragment.getContext(), fragment.getResourceProvider()); sheet.setParentActivity(fragment.getParentActivity()); @@ -106,20 +102,24 @@ public void openTab(WebTabData tab) { sheet.show(); } } else { + BottomSheetTabsOverlay overlay = LaunchActivity.instance.getBottomSheetTabsOverlay(); BotWebViewAttachedSheet webViewSheet = fragment.createBotViewer(); webViewSheet.setParentActivity(fragment.getParentActivity()); if (webViewSheet.restoreState(fragment, tab)) { - removeTab(tab, false); - webViewSheet.show(closed); +// if (overlay != null && overlay.isOpened() && overlay.openSheet(webViewSheet, tab, null)) { +// removeTab(tab, false); +// webViewSheet.show(closed, true); +// } else { + removeTab(tab, false); + webViewSheet.show(closed); +// } } } }; if (tab.needsContext && (!(lastFragment instanceof ChatActivity) || ((ChatActivity) lastFragment).getDialogId() != tab.props.botId)) { BaseFragment chatActivity = ChatActivity.of(tab.props.botId); + chatActivity.whenFullyVisible(() -> open.run(chatActivity)); lastFragment.presentFragment(chatActivity); - AndroidUtilities.runOnUIThread(() -> { - open.run(chatActivity); - }, 200); } else { open.run(lastFragment); } @@ -460,7 +460,7 @@ protected void dispatchDraw(Canvas canvas) { getTabBounds(rect, position); drawable.setExpandProgress(0f); drawable.setBackgroundColor(tabColor, tabIsDark > .5f); - drawable.draw(canvas, rect, dp(10), alpha); + drawable.draw(canvas, rect, dp(10), alpha, 1f); } } } @@ -583,7 +583,7 @@ public void setExpandProgress(float expandProgress) { private final Path closePath = new Path(); private final Path expandPath = new Path(); - public void draw(Canvas canvas, RectF bounds, float r, float alpha) { + public void draw(Canvas canvas, RectF bounds, float r, float alpha, float contentAlpha) { final int backgroundColor = ColorUtils.blendARGB(this.backgroundColor, this.tabColor, expandProgress); backgroundPaint.setColor(backgroundColor); backgroundPaint.setAlpha((int) (0xFF * alpha)); @@ -618,24 +618,24 @@ public void draw(Canvas canvas, RectF bounds, float r, float alpha) { canvas.save(); canvas.translate(bounds.left + dp(22 - 4), bounds.centerY() - dp(6)); - iconPaint.setAlpha((int) (0xFF * alpha)); + iconPaint.setAlpha((int) (0xFF * alpha * contentAlpha)); canvas.drawPath(closePath, iconPaint); canvas.restore(); canvas.save(); canvas.translate(bounds.right - dp(22 - 4 + 12.66f), bounds.centerY()); - iconPaint.setAlpha((int) (0xFF * alpha * (1f - expandProgress))); + iconPaint.setAlpha((int) (0xFF * alpha * contentAlpha * (1f - expandProgress))); canvas.drawPath(expandPath, iconPaint); canvas.restore(); if (overrideTitle != null) { overrideTitle .ellipsize((int) (bounds.width() - dp(100))) - .draw(canvas, bounds.left + dp(60), bounds.centerY(), iconColor, (1f - expandProgress) * alpha); + .draw(canvas, bounds.left + dp(60), bounds.centerY(), iconColor, (1f - expandProgress) * alpha * contentAlpha); } title .ellipsize((int) (bounds.width() - dp(100))) - .draw(canvas, bounds.left + dp(60), bounds.centerY(), iconColor, (overrideTitle == null ? 1f : expandProgress) * alpha); + .draw(canvas, bounds.left + dp(60), bounds.centerY(), iconColor, (overrideTitle == null ? 1f : expandProgress) * alpha * contentAlpha); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabsOverlay.java b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabsOverlay.java index 94df343e25..88ee535fa0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabsOverlay.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ActionBar/BottomSheetTabsOverlay.java @@ -3,6 +3,7 @@ import static org.telegram.messenger.AndroidUtilities.dp; import static org.telegram.messenger.AndroidUtilities.lerp; import static org.telegram.messenger.LocaleController.getString; +import static org.telegram.messenger.Utilities.clamp01; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -10,17 +11,14 @@ import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; -import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; -import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RadialGradient; import android.graphics.RectF; -import android.graphics.RenderEffect; import android.graphics.RenderNode; import android.graphics.Shader; import android.graphics.SurfaceTexture; @@ -34,7 +32,6 @@ import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; -import android.view.ViewGroup; import android.webkit.WebView; import android.widget.FrameLayout; import android.widget.OverScroller; @@ -42,7 +39,6 @@ import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; -import com.google.firebase.encoders.ValueEncoder; import com.google.zxing.common.detector.MathUtils; import org.telegram.messenger.AndroidUtilities; @@ -52,7 +48,6 @@ import org.telegram.ui.Components.AnimatedFloat; import org.telegram.ui.Components.ButtonBounce; import org.telegram.ui.Components.CubicBezierInterpolator; -import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.Text; import org.telegram.ui.GradientClip; import org.telegram.ui.bots.BotWebViewAttachedSheet; @@ -67,10 +62,14 @@ public class BottomSheetTabsOverlay extends FrameLayout { private BotWebViewAttachedSheet dismissingSheet; private BotWebViewSheet dismissingSheet2; + private BotWebViewAttachedSheet openingSheet; private BotWebViewMenuContainer dismissingMenuContainer; private BottomSheetTabs.TabDrawable dismissingTab; - private ValueAnimator dismissingAnimator; + private BottomSheetTabs.TabDrawable openingTab; + private float openingTabScroll; + private ValueAnimator animator; private float dismissProgress; + private float openingProgress; private final AnimatedFloat animatedCount = new AnimatedFloat(this, 0, 350, CubicBezierInterpolator.EASE_OUT_QUINT); @@ -88,6 +87,10 @@ public BottomSheetTabsOverlay(Context context) { minimumVelocity = configuration.getScaledMinimumFlingVelocity(); } + public boolean isOpened() { + return openProgress > .1f; + } + @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return false; @@ -398,14 +401,68 @@ public void setSlowerDismiss(boolean slowerDismiss) { this.slowerDismiss = slowerDismiss; } + public boolean openSheet(BotWebViewAttachedSheet sheet, BottomSheetTabs.WebTabData tab, Runnable whenOpened) { + if (sheet == null) return false; + if (tabsView == null) return false; + + if (dismissingSheet != null || openingSheet != null) { + if (animator != null) { + animator.end(); + animator = null; + } + } + + openingSheet = sheet; + sheet.getWindowView().setDrawingFromOverlay(true); + invalidate(); + + if (animator != null) { + animator.cancel(); + } + + openingTab = tabsView.findTabDrawable(tab); + openingTabScroll = openingTab != null ? ((animatedCount.get() - 1 - openingTab.getPosition()) - Math.max(getScrollMin(), getScrollOffset())) / getScrollWindow() : 0; + + openingProgress = 0; + animator = ValueAnimator.ofFloat(0, 1); + animator.addUpdateListener(anm -> { + openingProgress = (float) anm.getAnimatedValue(); + invalidate(); + }); + animator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + sheet.getWindowView().setDrawingFromOverlay(false); + sheet.getWindowView().post(() -> { + openingSheet = null; + openingTab = null; + if (!isOpen) { + clearTabs(); + } + openingProgress = 0; + invalidate(); + }); + + if (whenOpened != null) { + whenOpened.run(); + } + } + }); + AndroidUtilities.applySpring(animator, 260, 30, 1); +// animator.setDuration(5000); + animator.start(); + + return true; + } + public boolean dismissSheet(BotWebViewAttachedSheet sheet) { if (sheet == null) return false; if (tabsView == null) return false; - if (dismissingSheet != null) { - if (dismissingAnimator != null) { - dismissingAnimator.end(); - dismissingAnimator = null; + if (dismissingSheet != null || openingSheet != null) { + if (animator != null) { + animator.end(); + animator = null; } } @@ -413,8 +470,8 @@ public boolean dismissSheet(BotWebViewAttachedSheet sheet) { sheet.getWindowView().setDrawingFromOverlay(true); invalidate(); - if (dismissingAnimator != null) { - dismissingAnimator.cancel(); + if (animator != null) { + animator.cancel(); } BottomSheetTabs.WebTabData tab = sheet.saveState(); @@ -425,12 +482,12 @@ public boolean dismissSheet(BotWebViewAttachedSheet sheet) { } dismissProgress = 0; - dismissingAnimator = ValueAnimator.ofFloat(0, 1); - dismissingAnimator.addUpdateListener(anm -> { + animator = ValueAnimator.ofFloat(0, 1); + animator.addUpdateListener(anm -> { dismissProgress = (float) anm.getAnimatedValue(); invalidate(); }); - dismissingAnimator.addListener(new AnimatorListenerAdapter() { + animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (tab.webView != null && tab.previewBitmap == null && tab.webViewWidth > 0 && tab.webViewHeight > 0) { @@ -447,11 +504,11 @@ public void onAnimationEnd(Animator animation) { } }); if (slowerDismiss || sheet.getFullSize()) { - AndroidUtilities.applySpring(dismissingAnimator, 260, 30, 1); + AndroidUtilities.applySpring(animator, 260, 30, 1); } else { - AndroidUtilities.applySpring(dismissingAnimator, 350, 30, 1); + AndroidUtilities.applySpring(animator, 350, 30, 1); } - dismissingAnimator.start(); + animator.start(); slowerDismiss = false; @@ -462,10 +519,10 @@ public boolean dismissSheet(BotWebViewSheet sheet) { if (sheet == null) return false; if (tabsView == null) return false; - if (dismissingSheet2 != null) { - if (dismissingAnimator != null) { - dismissingAnimator.end(); - dismissingAnimator = null; + if (dismissingSheet != null || openingSheet != null) { + if (animator != null) { + animator.end(); + animator = null; } } @@ -473,8 +530,8 @@ public boolean dismissSheet(BotWebViewSheet sheet) { sheet.getWindowView().setDrawingFromOverlay(true); invalidate(); - if (dismissingAnimator != null) { - dismissingAnimator.cancel(); + if (animator != null) { + animator.cancel(); } BottomSheetTabs.WebTabData tab = sheet.saveState(); @@ -485,12 +542,12 @@ public boolean dismissSheet(BotWebViewSheet sheet) { } dismissProgress = 0; - dismissingAnimator = ValueAnimator.ofFloat(0, 1); - dismissingAnimator.addUpdateListener(anm -> { + animator = ValueAnimator.ofFloat(0, 1); + animator.addUpdateListener(anm -> { dismissProgress = (float) anm.getAnimatedValue(); invalidate(); }); - dismissingAnimator.addListener(new AnimatorListenerAdapter() { + animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (tab.webView != null && tab.previewBitmap == null && tab.webViewWidth > 0 && tab.webViewHeight > 0) { @@ -506,9 +563,9 @@ public void onAnimationEnd(Animator animation) { invalidate(); } }); - AndroidUtilities.applySpring(dismissingAnimator, 350, 30, 1); - dismissingAnimator.setDuration(dismissingAnimator.getDuration() * 2); - dismissingAnimator.start(); + AndroidUtilities.applySpring(animator, 350, 30, 1); + animator.setDuration(animator.getDuration() * 2); + animator.start(); slowerDismiss = false; @@ -523,8 +580,8 @@ public boolean dismissSheet(BotWebViewMenuContainer menuContainer) { menuContainer.setDrawingFromOverlay(true); invalidate(); - if (dismissingAnimator != null) { - dismissingAnimator.cancel(); + if (animator != null) { + animator.cancel(); } BottomSheetTabs.WebTabData tab = menuContainer.saveState(); @@ -535,12 +592,12 @@ public boolean dismissSheet(BotWebViewMenuContainer menuContainer) { } dismissProgress = 0; - dismissingAnimator = ValueAnimator.ofFloat(0, 1); - dismissingAnimator.addUpdateListener(anm -> { + animator = ValueAnimator.ofFloat(0, 1); + animator.addUpdateListener(anm -> { dismissProgress = (float) anm.getAnimatedValue(); invalidate(); }); - dismissingAnimator.addListener(new AnimatorListenerAdapter() { + animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (tab.webView != null && tab.previewBitmap == null && tab.webViewWidth > 0 && tab.webViewHeight > 0) { @@ -557,9 +614,9 @@ public void onAnimationEnd(Animator animation) { invalidate(); } }); - AndroidUtilities.applySpring(dismissingAnimator, 350, 30, 1); - dismissingAnimator.setDuration(dismissingAnimator.getDuration()); - dismissingAnimator.start(); + AndroidUtilities.applySpring(animator, 350, 30, 1); + animator.setDuration(animator.getDuration()); + animator.start(); return true; } @@ -589,12 +646,17 @@ private void prepareBlur(View view) { private final RectF tabsViewBounds = new RectF(); private final ArrayList tabs = new ArrayList<>(); + private View actionBarLayout; public void openTabsView() { if (tabsView == null || !(tabsView.getParent() instanceof View)) return; - View actionBarLayout = (View) tabsView.getParent(); - actionBarLayout.getLocationOnScreen(pos); + actionBarLayout = (View) tabsView.getParent(); + if (actionBarLayout != null) { + actionBarLayout.getLocationOnScreen(pos); + } else { + pos[0] = pos[1] = 0; + } getLocationOnScreen(pos2); tabsViewBounds.set(pos[0] - pos2[0], pos[1] - pos2[1], pos[0] - pos2[0] + actionBarLayout.getWidth(), pos[1] - pos2[1] + actionBarLayout.getHeight()); @@ -605,13 +667,6 @@ public void openTabsView() { } private void clearTabs() { -// for (int i = 0; i < tabs.size(); ++i) { -// TabPreview tab = tabs.get(i); -// if (tab.webView != null) { -// tab.webView.onPause(); -// AndroidUtilities.removeFromParent(tab.webView); -// } -// } tabs.clear(); } @@ -621,12 +676,6 @@ private void prepareTabs() { for (int i = tabs.size() - 1; i >= 0; --i) { BottomSheetTabs.WebTabData tabData = tabs.get(i); -// if (tabData.webView != null) { -// AndroidUtilities.removeFromParent(tabData.webView); -// tabData.webView.onResume(); -// tabData.webView.post(tabData.webView::onPause); -// addView(tabData.webView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT)); -// } BottomSheetTabs.TabDrawable tabDrawable = null; for (int j = 0; j < tabDrawables.size(); ++j) { BottomSheetTabs.TabDrawable d = tabDrawables.get(j); @@ -690,7 +739,7 @@ public void onAnimationEnd(Animator animation) { } openProgress = isOpen ? 1f : 0f; invalidate(); - if (!isOpen) { + if (!isOpen && openingSheet == null) { clearTabs(); } } @@ -714,7 +763,7 @@ private void drawDismissingTab(Canvas canvas) { tabsView.getLocationOnScreen(pos); tabsView.getTabBounds(rect, 0); rect.offset(pos[0] - pos2[0], pos[1] - pos2[1]); - float radius = dismissingSheet.getWindowView().drawInto(canvas, rect, dismissProgress, clipRect); + float radius = dismissingSheet.getWindowView().drawInto(canvas, rect, dismissProgress, clipRect, dismissProgress, false); if (dismissingTab != null) { clipPath.rewind(); @@ -724,7 +773,7 @@ private void drawDismissingTab(Canvas canvas) { final float y = clipRect.top - dp(50) * (1f - dismissProgress); rect.set(clipRect.left, y, clipRect.right, y + dp(50)); tabsView.setupTab(dismissingTab); - dismissingTab.draw(canvas, rect, radius, dismissProgress); + dismissingTab.draw(canvas, rect, radius, dismissProgress, 1f); canvas.restore(); } } @@ -745,7 +794,7 @@ private void drawDismissingTab(Canvas canvas) { final float y = clipRect.top - dp(50) * (1f - dismissProgress); rect.set(clipRect.left, y, clipRect.right, y + dp(50)); tabsView.setupTab(dismissingTab); - dismissingTab.draw(canvas, rect, radius, dismissProgress); + dismissingTab.draw(canvas, rect, radius, dismissProgress, 1f); canvas.restore(); } } @@ -766,7 +815,7 @@ private void drawDismissingTab(Canvas canvas) { final float y = clipRect.top - dp(50) * (1f - dismissProgress); rect.set(clipRect.left, y, clipRect.right, y + dp(50)); tabsView.setupTab(dismissingTab); - dismissingTab.draw(canvas, rect, radius, dismissProgress); + dismissingTab.draw(canvas, rect, radius, dismissProgress, 1f); canvas.restore(); } } @@ -784,9 +833,19 @@ protected boolean verifyDrawable(@NonNull Drawable who) { private GradientClip gradientClip; private void drawTabsPreview(Canvas canvas) { - if (openProgress <= 0) return; + if (openProgress <= 0 && openingProgress <= 0) return; canvas.save(); + + if (actionBarLayout != null) { + actionBarLayout.getLocationOnScreen(pos); + getLocationOnScreen(pos2); + tabsViewBounds.set(pos[0] - pos2[0], pos[1] - pos2[1], pos[0] - pos2[0] + actionBarLayout.getWidth(), pos[1] - pos2[1] + actionBarLayout.getHeight()); + } else { + pos[0] = pos[1] = 0; + tabsViewBounds.set(0, 0, 0, 0); + } + canvas.clipRect(tabsViewBounds); canvas.translate(tabsViewBounds.left, tabsViewBounds.top); @@ -817,11 +876,29 @@ private void drawTabsPreview(Canvas canvas) { } final float count = animatedCount.set(tabCount); boolean reverse = true; - for (int i = (reverse ? 0 : tabs.size() - 1); (reverse ? i < tabs.size() : i >= 0); i = (reverse ? i + 1 : i - 1)) { - final TabPreview tab = tabs.get(i); + final float open = lerp(0, (1f - Utilities.clamp(getScrollWindow() <= 0 ? 0 : (getScrollMin() - getScrollOffset()) / (getScrollWindow() * .15f) * .2f, 1f, 0f)), openProgress); + int openingTabIndex = -1; + for (int i = 0; i < tabs.size() + 1; i++) { + final TabPreview tab; + if (i == tabs.size()) { + if (openingTabIndex >= 0 && openingProgress > .5f) { + tab = tabs.get(openingTabIndex); + } else { + continue; + } + } else { + tab = tabs.get(i); + } + if (i < tabs.size() && tab.tabDrawable == openingTab && openingProgress > .5f) { + openingTabIndex = i; + continue; + } + + final float tabOpen = tab.tabDrawable == openingTab ? 1f : open; + final float opening = tab.tabDrawable == openingTab ? openingProgress : 0f; final float position = count - 1 - tab.tabDrawable.getPosition(); - final float scroll = (position - getScrollOffset()) / getScrollWindow(); + final float scroll = tab.tabDrawable == openingTab ? openingTabScroll : (position - Math.max(getScrollMin(), getScrollOffset())) / getScrollWindow(); final float scrollT = Math.max(scroll, 0f); final float oscrollT = Math.max(Math.min(scroll, 1f), -4); @@ -842,31 +919,29 @@ private void drawTabsPreview(Canvas canvas) { if (alpha <= 0) continue; rect2.set(cx - width / 2f, y, cx + width / 2f, y + height); - tabsView.getTabBounds(rect, Utilities.clamp(tab.tabDrawable.getPosition(), 1, 0)); - rect.offset(tabsView.getX(), tabsView.getY()); - AndroidUtilities.lerpCentered(rect, rect2, openProgress, rect2); + boolean drawSimple = tab.tabDrawable != openingTab && (rect2.top > thisHeight || rect2.bottom < 0 || open < .1f) && position < count - 3; + + if (openingSheet != null && tab.tabDrawable == openingTab) { + BotWebViewAttachedSheet.WindowView windowView = openingSheet.getWindowView(); + rect.set(windowView.getRect()); + AndroidUtilities.lerpCentered(rect2, rect, opening, rect2); + } else { + tabsView.getTabBounds(rect, Utilities.clamp(tab.tabDrawable.getPosition(), 1, 0)); + rect.offset(tabsView.getX(), tabsView.getY()); + AndroidUtilities.lerpCentered(rect, rect2, open, rect2); + } if (tabsView != null) { tabsView.setupTab(tab.tabDrawable); } + if (tab.tabDrawable != openingTab && (rect2.top > thisHeight || rect2.bottom < 0)) + continue; + canvas.save(); tab.clickBounds.set(rect2); if (SharedConfig.botTabs3DEffect) { -// final float scale = lerp(1f, .5f, openProgress); -// canvas.scale(scale, scale, rect2.centerX(), rect2.centerY()); -// scale(tab.clickBounds, scale, rect.centerX(), rect2.centerY()); - Canvas tabCanvas = canvas; -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alpha < 1 && false) { -// if (tab.node == null) { -// tab.node = new RenderNode("a"); -// } -// tab.node.setRenderEffect(RenderEffect.createBlurEffect((1f - alpha) * 300, (1f - alpha) * 300, Shader.TileMode.CLAMP)); -// tab.node.setPosition(0, 0, (int) thisWidth, (int) thisHeight); -// tabCanvas = tab.node.beginRecording(); -// } - tab.matrix.reset(); final int p = 0; @@ -880,41 +955,35 @@ private void drawTabsPreview(Canvas canvas) { tab.src[6] = rect2.left; tab.src[7] = rect2.top + rect2.height() * Sh; -// final float ws = .75f; -// final float wss = 1.2f; -// final float hs = 1f; -// final float wstop = 1f; -// final float wsbottom = 1.2f; -// tab.dst[0] = rect2.centerX() - rect2.width() / 2f * ws * wstop; -// tab.dst[1] = rect2.centerY() - rect2.height() / 2f * hs; -// tab.dst[2] = rect2.centerX() + rect2.width() / 2f * ws * wstop; -// tab.dst[3] = rect2.centerY() - rect2.height() / 2f * hs; -// tab.dst[4] = rect2.centerX() + rect2.width() / 2f * ws * (2f - wsbottom); -// tab.dst[5] = rect2.centerY() + rect2.height() / 2f * hs; -// tab.dst[6] = rect2.centerX() - rect2.width() / 2f * ws * (2f - wsbottom); -// tab.dst[7] = rect2.centerY() + rect2.height() / 2f * hs; - tab.dst[0] = rect2.left; tab.dst[1] = rect2.top - dp(p); tab.dst[2] = rect2.right; tab.dst[3] = rect2.top - dp(p); final float s1 = .83f, s2 = .6f; - tab.dst[4] = rect2.centerX() + rect2.width() / 2f * lerp(1f, s1, openProgress); - tab.dst[5] = rect2.top - dp(p) + (rect2.height() * Sh + dp(p + p)) * lerp(1f, s2, openProgress); - tab.dst[6] = rect2.centerX() - rect2.width() / 2f * lerp(1f, s1, openProgress); - tab.dst[7] = rect2.top - dp(p) + (rect2.height() * Sh + dp(p + p)) * lerp(1f, s2, openProgress); + tab.dst[4] = rect2.centerX() + rect2.width() / 2f * lerp(1f, s1, tabOpen * (1f - opening)); + tab.dst[5] = rect2.top - dp(p) + (rect2.height() * Sh + dp(p + p)) * lerp(1f, s2, tabOpen * (1f - opening)); + tab.dst[6] = rect2.centerX() - rect2.width() / 2f * lerp(1f, s1, tabOpen * (1f - opening)); + tab.dst[7] = rect2.top - dp(p) + (rect2.height() * Sh + dp(p + p)) * lerp(1f, s2, tabOpen * (1f - opening)); tab.matrix.setPolyToPoly(tab.src, 0, tab.dst, 0, 4); tabCanvas.concat(tab.matrix); - tab.draw(tabCanvas, rect2, lerp(tab.tabDrawable.getAlpha(), alpha, openProgress), openProgress); + tab.draw( + tabCanvas, + rect2, + drawSimple, + tab.tabDrawable == openingTab ? 1f : lerp(tab.tabDrawable.getAlpha(), alpha, openProgress), + tab.tabDrawable == openingTab ? 1f : tabOpen * (1f - opening), + opening, + lerp(clamp01(position - count + 2),1f, clamp01((tabOpen - .1f) / .8f)) + ); + + if (openingSheet != null && tab.tabDrawable == openingTab) { + BotWebViewAttachedSheet.WindowView windowView = openingSheet.getWindowView(); + windowView.drawInto(canvas, rect2, 1f, rect2, opening, true); + } canvas.restore(); -// -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alpha < 1 && false) { -// tab.node.endRecording(); -// canvas.drawRenderNode(tab.node); -// } } else { final float s = lerp( 1f, @@ -928,7 +997,7 @@ private void drawTabsPreview(Canvas canvas) { canvas.scale(s, s, rect2.centerX(), rect2.top); scale(tab.clickBounds, s, rect.centerX(), rect2.top); - tab.draw(canvas, rect2, lerp(tab.tabDrawable.getAlpha(), 1f, openProgress), openProgress); + tab.draw(canvas, rect2, drawSimple, lerp(tab.tabDrawable.getAlpha(), 1f, openProgress), open, 0f, lerp(clamp01(position - count + 2), 1f, clamp01((open - .1f) / .8f))); canvas.restore(); } } @@ -1070,27 +1139,38 @@ public TabPreview( private final Matrix gradientMatrix = new Matrix(); private final Paint gradientPaint = new Paint(Paint.ANTI_ALIAS_FLAG); - public void draw(Canvas canvas, RectF bounds, float alpha, float expandProgress) { + public void draw(Canvas canvas, RectF bounds, boolean simple, float alpha, float expandProgress, float openingProgress, float contentAlpha) { alpha *= Utilities.clamp(1f - ((Math.abs(dismissProgress) - .3f) / .7f), 1f, 0f); if (alpha <= 0) return; float tabScaleY = 1f; if (SharedConfig.botTabs3DEffect) { - tabScaleY = lerp(1f, 1.3f, expandProgress); + tabScaleY = lerp(1f, 1.3f, expandProgress * (1f - openingProgress)); } + final float tabTranslateY = openingProgress * (AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() - dp(50)); canvas.save(); canvas.rotate(dismissProgress * 20, bounds.centerX() + dp(50) * dismissProgress, bounds.bottom + dp(350)); final float s = bounce.getScale(.01f); canvas.scale(s, s, bounds.centerX(), bounds.centerY()); final float r = lerp(dp(10), dp(8), expandProgress); + if (simple) { + shadowPaint.setColor(0); + shadowPaint.setShadowLayer(dp(30), 0, dp(10), Theme.multAlpha(0x20000000, alpha * expandProgress * (1f - openingProgress))); + canvas.drawRoundRect(bounds, r, r, shadowPaint); + backgroundPaint.setAlpha((int) (0xFF * alpha)); + canvas.drawRoundRect(bounds, r, r, backgroundPaint); + canvas.restore(); + return; + } + clipPath.rewind(); clipPath.addRoundRect(bounds, r, r, Path.Direction.CW); canvas.save(); shadowPaint.setColor(0); - shadowPaint.setShadowLayer(dp(30), 0, dp(10), Theme.multAlpha(0x20000000, alpha * (expandProgress > .7f ? expandProgress : 0))); + shadowPaint.setShadowLayer(dp(30), 0, dp(10), Theme.multAlpha(0x20000000, alpha * expandProgress * (1f - openingProgress))); canvas.drawPath(clipPath, shadowPaint); canvas.clipPath(clipPath); @@ -1098,8 +1178,8 @@ public void draw(Canvas canvas, RectF bounds, float alpha, float expandProgress) canvas.drawRoundRect(bounds, r, r, backgroundPaint); canvas.save(); - canvas.translate(bounds.left, bounds.top + dp(50) * tabScaleY); - canvas.scale(1f, lerp(1f, 1.25f, expandProgress)); + canvas.translate(bounds.left, bounds.top + dp(50) * tabScaleY + tabTranslateY); + canvas.scale(1f, lerp(1f, 1.25f, expandProgress * (1f - openingProgress))); if (previewNode != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ((RenderNode) previewNode).hasDisplayList()) { RenderNode node = (RenderNode) previewNode; final float s2 = bounds.width() / node.getWidth(); @@ -1121,7 +1201,7 @@ public void draw(Canvas canvas, RectF bounds, float alpha, float expandProgress) canvas.restore(); canvas.save(); - gradientPaint.setAlpha((int) (0xFF * alpha * expandProgress)); + gradientPaint.setAlpha((int) (0xFF * alpha * expandProgress * (1f - openingProgress))); gradientMatrix.reset(); final float gradientScale = bounds.height() / 255f; gradientMatrix.postScale(gradientScale, gradientScale); @@ -1133,9 +1213,10 @@ public void draw(Canvas canvas, RectF bounds, float alpha, float expandProgress) tabBounds.set(bounds); tabBounds.bottom = tabBounds.top + Math.min(bounds.height(), dp(50)); + tabBounds.offset(0, tabTranslateY); tabDrawable.setExpandProgress(expandProgress); canvas.scale(1f, tabScaleY, tabBounds.centerX(), tabBounds.top); - tabDrawable.draw(canvas, tabBounds, r, alpha * alpha); + tabDrawable.draw(canvas, tabBounds, r, alpha * alpha, contentAlpha); canvas.restore(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java index caaec78e39..f0fa60c911 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseLocationAdapter.java @@ -28,6 +28,7 @@ import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stories; +import org.telegram.ui.Components.ListView.AdapterWithDiffUtils; import org.telegram.ui.Components.RecyclerListView; import java.util.ArrayList; @@ -35,7 +36,7 @@ import java.util.List; import java.util.Locale; -public abstract class BaseLocationAdapter extends RecyclerListView.SelectionAdapter { +public abstract class BaseLocationAdapter extends AdapterWithDiffUtils { public final boolean stories; public final boolean biz; @@ -82,7 +83,7 @@ public void searchDelayed(final String query, final Location coordinate) { places.clear(); locations.clear(); searchInProgress = false; - notifyDataSetChanged(); + update(true); } else { if (searchRunnable != null) { Utilities.searchQueue.cancelRunnable(searchRunnable); @@ -483,7 +484,7 @@ public void searchPlacesWithQuery(final String query, final Location coordinate, } BaseLocationAdapter.this.locations.clear(); BaseLocationAdapter.this.locations.addAll(locations); - notifyDataSetChanged(); + update(true); }); }); } else { @@ -525,10 +526,13 @@ public void searchPlacesWithQuery(final String query, final Location coordinate, if (delegate != null) { delegate.didLoadSearchResult(places); } - notifyDataSetChanged(); + update(true); })); + update(true); + } + + protected void update(boolean animated) { notifyDataSetChanged(); -// notifyStartSearch(wasSearched, wasSearching, oldItemCount, animated); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java index 6e139588f9..9ef069a005 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/FiltersView.java @@ -334,7 +334,7 @@ public static void fillTipDates(String query, ArrayList dates) { long minDate = calendar.getTimeInMillis(); calendar.set(year, month, day + 1, 0, 0, 0); long maxDate = calendar.getTimeInMillis() - 1; - dates.add(new DateData(LocaleController.getInstance().formatterWeekLong.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterWeekLong().format(minDate), minDate, maxDate)); return; } if ((matcher = shortDate.matcher(q)).matches()) { @@ -382,7 +382,7 @@ public static void fillTipDates(String query, ArrayList dates) { long minDate = calendar.getTimeInMillis(); calendar.set(year, month, day + 1, 0, 0, 0); long maxDate = calendar.getTimeInMillis() - 1; - dates.add(new DateData(LocaleController.getInstance().formatterYearMax.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterYearMax().format(minDate), minDate, maxDate)); return; } @@ -462,7 +462,7 @@ public static void fillTipDates(String query, ArrayList dates) { } calendar.add(Calendar.MONTH, 1); long maxDate = calendar.getTimeInMillis() - 1; - dates.add(new DateData(LocaleController.getInstance().formatterMonthYear.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterMonthYear().format(minDate), minDate, maxDate)); } } } @@ -480,7 +480,7 @@ private static void createForMonthYear(ArrayList dates, int month, int } calendar.add(Calendar.MONTH, 1); long maxDate = calendar.getTimeInMillis() - 1; - dates.add(new DateData(LocaleController.getInstance().formatterMonthYear.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterMonthYear().format(minDate), minDate, maxDate)); } } @@ -502,9 +502,9 @@ private static void createForDayMonth(ArrayList dates, int day, int mo calendar.set(i, month, day + 2, 0, 0, 0); long maxDate = calendar.getTimeInMillis() - 1; if (i == currentYear) { - dates.add(new DateData(LocaleController.getInstance().formatterDayMonth.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterDayMonth().format(minDate), minDate, maxDate)); } else { - dates.add(new DateData(LocaleController.getInstance().formatterYearMax.format(minDate), minDate, maxDate)); + dates.add(new DateData(LocaleController.getInstance().getFormatterYearMax().format(minDate), minDate, maxDate)); } } } @@ -527,7 +527,7 @@ public static int getDayOfWeek(String q) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", Locale.ENGLISH); for (int i = 0; i < 7; i++) { c.set(Calendar.DAY_OF_WEEK, i); - if (LocaleController.getInstance().formatterWeekLong.format(c.getTime()).toLowerCase().startsWith(q)) { + if (LocaleController.getInstance().getFormatterWeekLong().format(c.getTime()).toLowerCase().startsWith(q)) { return i; } if (dateFormat.format(c.getTime()).toLowerCase().startsWith(q)) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java index d59e869a2c..056579256d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/LocationActivityAdapter.java @@ -750,4 +750,4 @@ public boolean isEnabled(RecyclerView.ViewHolder holder) { private int getThemedColor(int key) { return Theme.getColor(key, resourcesProvider); } -} +} \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java b/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java index 2e169e0235..a3c30887b8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ArticleViewer.java @@ -3690,7 +3690,11 @@ public void toggleSubMenu() { } else { webPageUrl = adapter[0].currentPage.url; } - Browser.openUrl(parentActivity, webPageUrl, true, false); + if (parentActivity == null || parentActivity.isFinishing()) return; + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webPageUrl)); + intent.putExtra(android.provider.Browser.EXTRA_CREATE_NEW_TAB, true); + intent.putExtra(android.provider.Browser.EXTRA_APPLICATION_ID, parentActivity.getPackageName()); + parentActivity.startActivity(intent); } else if (id == settings_item) { BottomSheet.Builder builder = new BottomSheet.Builder(parentActivity); builder.setApplyTopPadding(false); @@ -7189,7 +7193,7 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { } if (currentBlock.date != 0) { - dateLayout = createLayoutForText(this, LocaleController.getInstance().chatFullDate.format((long) currentBlock.date * 1000), null, width - AndroidUtilities.dp(36 + 14 + (avatarVisible ? 40 + 14 : 0)), AndroidUtilities.dp(29), currentBlock, parentAdapter); + dateLayout = createLayoutForText(this, LocaleController.getInstance().getChatFullDate().format((long) currentBlock.date * 1000), null, width - AndroidUtilities.dp(36 + 14 + (avatarVisible ? 40 + 14 : 0)), AndroidUtilities.dp(29), currentBlock, parentAdapter); } else { dateLayout = null; } @@ -9740,11 +9744,11 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { } String description; if (item.published_date != 0 && !TextUtils.isEmpty(item.author)) { - description = LocaleController.formatString("ArticleDateByAuthor", R.string.ArticleDateByAuthor, LocaleController.getInstance().chatFullDate.format((long) item.published_date * 1000), item.author); + description = LocaleController.formatString("ArticleDateByAuthor", R.string.ArticleDateByAuthor, LocaleController.getInstance().getChatFullDate().format((long) item.published_date * 1000), item.author); } else if (!TextUtils.isEmpty(item.author)) { description = LocaleController.formatString("ArticleByAuthor", R.string.ArticleByAuthor, item.author); } else if (item.published_date != 0) { - description = LocaleController.getInstance().chatFullDate.format((long) item.published_date * 1000); + description = LocaleController.getInstance().getChatFullDate().format((long) item.published_date * 1000); } else if (!TextUtils.isEmpty(item.description)) { description = item.description; } else { @@ -11025,11 +11029,11 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { } try { if (currentBlock.published_date != 0 && !TextUtils.isEmpty(author)) { - text = LocaleController.formatString("ArticleDateByAuthor", R.string.ArticleDateByAuthor, LocaleController.getInstance().chatFullDate.format((long) currentBlock.published_date * 1000), author); + text = LocaleController.formatString("ArticleDateByAuthor", R.string.ArticleDateByAuthor, LocaleController.getInstance().getChatFullDate().format((long) currentBlock.published_date * 1000), author); } else if (!TextUtils.isEmpty(author)) { text = LocaleController.formatString("ArticleByAuthor", R.string.ArticleByAuthor, author); } else { - text = LocaleController.getInstance().chatFullDate.format((long) currentBlock.published_date * 1000); + text = LocaleController.getInstance().getChatFullDate().format((long) currentBlock.published_date * 1000); } } catch (Exception e) { FileLog.e(e); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Business/OpeningHoursActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/Business/OpeningHoursActivity.java index f1c722f4e8..1a2245e935 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Business/OpeningHoursActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Business/OpeningHoursActivity.java @@ -468,7 +468,7 @@ public static String timeToString(int time, boolean includeNextDay) { int hours = (time - min) / 60 % 24; Calendar rightNow = Calendar.getInstance(); rightNow.set(0, 0, 0, hours, min); - String str = LocaleController.getInstance().formatterConstDay.format(rightNow.getTime()); + String str = LocaleController.getInstance().getFormatterConstDay().format(rightNow.getTime()); if (time > 24 * 60 && includeNextDay) { return LocaleController.formatString(R.string.BusinessHoursNextDay, str); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java index 90e0e01140..88d806cd42 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatActionCell.java @@ -1249,11 +1249,11 @@ private void buildLayout() { if (currentMessageObject.messageOwner != null && NaConfig.INSTANCE.getShowServicesTime().Bool()) { if (currentMessageObject.messageOwner.action != null) { long date = currentMessageObject.messageOwner.date; - String timestamp = LocaleController.getInstance().formatterDay.format(date * 1000); + String timestamp = LocaleController.getInstance().getFormatterDay().format(date * 1000); text += " · " + timestamp; } else if (currentMessageObject.currentEvent != null){ long date = currentMessageObject.currentEvent.date; - String timestamp = LocaleController.getInstance().formatterDay.format(date * 1000); + String timestamp = LocaleController.getInstance().getFormatterDay().format(date * 1000); text += " " + timestamp; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java index 00ace43051..806f871772 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/ChatMessageCell.java @@ -62,7 +62,6 @@ import android.text.style.ClickableSpan; import android.text.style.LeadingMarginSpan; import android.text.style.URLSpan; -import android.util.Log; import android.util.Pair; import android.util.Property; import android.util.SparseArray; @@ -472,7 +471,7 @@ default void didPressUserStatus(ChatMessageCell cell, TLRPC.User user, TLRPC.Doc } - default void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { + default void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY, boolean asForward) { } default boolean didLongPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { @@ -491,7 +490,7 @@ default void didPressViaBot(ChatMessageCell cell, String username) { default void didPressBoostCounter(ChatMessageCell cell) { } - default void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { + default void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY, boolean asForward) { } default boolean didLongPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { @@ -914,6 +913,7 @@ public boolean isCellAttachedToWindow() { private AvatarSpan forwardAvatar; private ForwardBackground forwardBg; + private LoadingDrawable forwardLoading; public boolean linkPreviewAbove; public boolean captionAbove; private boolean isSmallImage; @@ -1895,7 +1895,7 @@ private boolean checkNameMotionEvent(MotionEvent event) { delegate.didPressViaBot(this, currentViaBotUser != null ? UserObject.getPublicUsername(currentViaBotUser) : currentMessageObject.messageOwner.via_bot_name); } } else if (currentUser != null) { - delegate.didPressUserAvatar(this, currentUser, event.getX(), event.getY()); + delegate.didPressUserAvatar(this, currentUser, event.getX(), event.getY(), false); } else if (currentChat != null) { int id; TLRPC.Chat chat = currentChat; @@ -1909,7 +1909,7 @@ private boolean checkNameMotionEvent(MotionEvent event) { } else { id = 0; } - delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY, false); } } } @@ -4198,7 +4198,7 @@ public boolean onTouchEvent(MotionEvent event) { if (currentUser.id == 0) { delegate.didPressHiddenForward(this); } else { - delegate.didPressUserAvatar(this, currentUser, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(this, currentUser, lastTouchX, lastTouchY, false); } } else if (currentChat != null) { int id; @@ -4213,7 +4213,7 @@ public boolean onTouchEvent(MotionEvent event) { } else { id = 0; } - delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(this, chat != null ? chat : currentChat, id, lastTouchX, lastTouchY, false); } else if (currentMessageObject != null) { delegate.didPressInstantButton(this, drawInstantViewType); } @@ -4248,9 +4248,9 @@ public boolean onTouchEvent(MotionEvent event) { if (currentMessageObject.messageOwner.fwd_from != null) { postId = currentMessageObject.messageOwner.fwd_from.channel_post; } - delegate.didPressChannelAvatar(this, currentForwardChannel, postId, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(this, currentForwardChannel, postId, lastTouchX, lastTouchY, true); } else if (currentForwardUser != null) { - delegate.didPressUserAvatar(this, currentForwardUser, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(this, currentForwardUser, lastTouchX, lastTouchY, true); } else if (currentForwardName != null) { delegate.didPressHiddenForward(this); } @@ -4316,9 +4316,9 @@ public boolean onTouchEvent(MotionEvent event) { if (replyPanelIsForward) { if (delegate != null) { if (currentForwardChannel != null) { - delegate.didPressChannelAvatar(this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY, false); } else if (currentForwardUser != null) { - delegate.didPressUserAvatar(this, currentForwardUser, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(this, currentForwardUser, lastTouchX, lastTouchY, false); } else if (currentForwardName != null) { delegate.didPressHiddenForward(this); } @@ -4886,7 +4886,7 @@ private void didClickedImage() { if (uid != 0) { user = MessagesController.getInstance(currentAccount).getUser(uid); } - delegate.didPressUserAvatar(this, user, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(this, user, lastTouchX, lastTouchY, false); } else if (currentMessageObject.type == MessageObject.TYPE_ROUND_VIDEO) { if (buttonState != -1) { didPressButton(true, false); @@ -7385,7 +7385,7 @@ private void setMessageContent(MessageObject messageObject, MessageObject.Groupe } String text; - String time = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000); + String time = LocaleController.getInstance().getFormatterDay().format((long) (messageObject.messageOwner.date) * 1000); TLRPC.TL_messageActionPhoneCall call = (TLRPC.TL_messageActionPhoneCall) messageObject.messageOwner.action; boolean isMissed = call.reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed; if (messageObject.isOutOwner()) { @@ -7966,21 +7966,19 @@ private void setMessageContent(MessageObject messageObject, MessageObject.Groupe groupMedia.setOverrideWidth(-1); groupMedia.setMessageObject(messageObject, pinnedBottom, pinnedTop); backgroundWidth = groupMedia.width + dp(8 + 9); + availableTimeWidth = backgroundWidth - AndroidUtilities.dp(31); measureTime(messageObject); - if (drawCommentButton && totalCommentWidth + AndroidUtilities.dp(20) > backgroundWidth) { - backgroundWidth = totalCommentWidth + AndroidUtilities.dp(20); + if (drawCommentButton && totalCommentWidth + AndroidUtilities.dp(28) > backgroundWidth) { + backgroundWidth = totalCommentWidth + AndroidUtilities.dp(28); groupMedia.setOverrideWidth(backgroundWidth - dp(8 + 9)); } - if (timeWidth + dp(25) > backgroundWidth) { - backgroundWidth = timeWidth + dp(25); + int timeWidthTotal = timeWidth + dp((SharedConfig.bubbleRadius >= 10 ? 22 : 18) + (messageObject.isOutOwner() ? 20 : 0) + 20); + if (timeWidthTotal > backgroundWidth) { + backgroundWidth = timeWidthTotal; groupMedia.setOverrideWidth(backgroundWidth - dp(8 + 9)); } mediaBackground = false; - int timeWidthTotal = timeWidth + AndroidUtilities.dp((SharedConfig.bubbleRadius >= 10 ? 22 : 18) + (messageObject.isOutOwner() ? 20 : 0)); - if (backgroundWidth < timeWidthTotal) { - backgroundWidth = timeWidthTotal; - } int widthForCaption = backgroundWidth - dp(20); int additionHeight = 0; @@ -8061,7 +8059,7 @@ private void setMessageContent(MessageObject messageObject, MessageObject.Groupe reactionsLayoutInBubble.positionOffsetY -= AndroidUtilities.dp(12); } if (!messageObject.isRestrictedMessage && messageObject.caption != null) { - reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(14); + reactionsLayoutInBubble.positionOffsetY += AndroidUtilities.dp(!drawCommentButton ? 14 : 1); } totalHeight += reactionsLayoutInBubble.totalHeight; } @@ -9897,7 +9895,7 @@ private void updateFlagSecure() { Activity activity = AndroidUtilities.findActivity(getContext()); Window window = activity == null ? null : activity.getWindow(); if (window != null) { - flagSecure = new FlagSecureReason(window, () -> currentMessageObject != null && !NekoXConfig.disableFlagSecure && currentMessageObject.messageOwner != null && (currentMessageObject.messageOwner.noforwards || currentMessageObject.isVoiceOnce() || currentMessageObject.hasRevealedExtendedMedia())); + flagSecure = new FlagSecureReason(window, () -> currentMessageObject != null && !NekoXConfig.disableFlagSecure && currentMessageObject.messageOwner != null && (currentMessageObject.type == MessageObject.TYPE_PAID_MEDIA || currentMessageObject.messageOwner.noforwards || currentMessageObject.isVoiceOnce() || currentMessageObject.hasRevealedExtendedMedia())); if (attachedToWindow) { flagSecure.attach(); } @@ -15821,12 +15819,12 @@ private void measureTime(MessageObject messageObject) { } else if (currentMessageObject.scheduled && currentMessageObject.messageOwner.date == 0x7FFFFFFE) { timeString = ""; } else if (currentMessageObject.realDate != 0) { - timeString = LocaleController.formatSmallDateChat(currentMessageObject.realDate) + ", " + LocaleController.getInstance().formatterDay.format((long) (currentMessageObject.realDate) * 1000); + timeString = LocaleController.formatSmallDateChat(currentMessageObject.realDate) + ", " + LocaleController.getInstance().getFormatterDay().format((long) (currentMessageObject.realDate) * 1000); } else if (currentMessageObject.isRepostPreview) { - timeString = LocaleController.formatSmallDateChat(messageObject.messageOwner.date) + ", " + LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000); + timeString = LocaleController.formatSmallDateChat(messageObject.messageOwner.date) + ", " + LocaleController.getInstance().getFormatterDay().format((long) (messageObject.messageOwner.date) * 1000); } else if (edited) { String customStr = NaConfig.INSTANCE.getCustomEditedMessage().String(); - timeString = (customStr.equals("") ? getString("EditedMessage", R.string.EditedMessage) : customStr) + " " + LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000); + timeString = (customStr.equals("") ? getString("EditedMessage", R.string.EditedMessage) : customStr) + " " + LocaleController.getInstance().getFormatterDay().format((long) (messageObject.messageOwner.date) * 1000); } else if (currentMessageObject.isSaved && currentMessageObject.messageOwner.fwd_from != null && (currentMessageObject.messageOwner.fwd_from.date != 0 || currentMessageObject.messageOwner.fwd_from.saved_date != 0)) { int date = currentMessageObject.messageOwner.fwd_from.saved_date; if (date == 0) { @@ -15834,7 +15832,7 @@ private void measureTime(MessageObject messageObject) { } timeString = LocaleController.formatSeenDate(date); } else { - timeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000); + timeString = LocaleController.getInstance().getFormatterDay().format((long) (messageObject.messageOwner.date) * 1000); } if (NaConfig.INSTANCE.getShowMessageID().Bool() && messageObject.messageOwner != null && (isChat || isMegagroup || ChatObject.isChannel(currentChat))) { timeString = timeString + " | " + messageObject.messageOwner.id; @@ -18917,7 +18915,7 @@ public void drawNamesLayout(Canvas canvas, float alpha) { } } else { forwardNameY = AndroidUtilities.dp(7) + (drawNameLayout ? AndroidUtilities.dp(6) + (int) Theme.chat_namePaint.getTextSize() : 0) + (drawTopic && topicButton != null ? topicButton.height() + AndroidUtilities.dp(7 + (currentMessageObject.type != MessageObject.TYPE_TEXT ? 3 : 0)) : 0); - if (!drawNameLayout && (currentMessageObject.type == MessageObject.TYPE_GIF || currentMessageObject.type == MessageObject.TYPE_PHOTO || currentMessageObject.type == MessageObject.TYPE_VIDEO || currentMessageObject.type == MessageObject.TYPE_STORY)) { + if (!drawNameLayout && (currentMessageObject.type == MessageObject.TYPE_GIF || currentMessageObject.type == MessageObject.TYPE_PHOTO || currentMessageObject.type == MessageObject.TYPE_VIDEO || currentMessageObject.type == MessageObject.TYPE_STORY || currentMessageObject.type == MessageObject.TYPE_PAID_MEDIA || currentMessageObject.type == MessageObject.TYPE_FILE)) { forwardNameY += dp(2); } if (!drawNameLayout && currentMessageObject.type == MessageObject.TYPE_TEXT && !drawPinnedTop) { @@ -18993,6 +18991,7 @@ public void drawNamesLayout(Canvas canvas, float alpha) { canvas.save(); canvas.translate(forwardNameXLocal, forwardNameY); + final boolean forwardLoading = delegate != null && delegate.isProgressLoading(this, ChatActivity.PROGRESS_FORWARD); if (forwardBg != null) { final float s = forwardBg.bounce.getScale(.02f); canvas.scale(s, s, forwardBg.bounds.centerX(), forwardBg.bounds.centerY()); @@ -19001,7 +19000,7 @@ public void drawNamesLayout(Canvas canvas, float alpha) { } else { forwardBg.setColor(Theme.multAlpha(Theme.chat_forwardNamePaint.getColor(), .15f)); } - forwardBg.draw(canvas); + forwardBg.draw(canvas, forwardLoading); } for (int a = 0; a < 2; a++) { canvas.save(); @@ -22304,9 +22303,9 @@ public boolean performAccessibilityAction(int action, Bundle arguments) { } else if (action == R.id.acc_action_open_forwarded_origin) { if (delegate != null) { if (currentForwardChannel != null) { - delegate.didPressChannelAvatar(ChatMessageCell.this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(ChatMessageCell.this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY, false); } else if (currentForwardUser != null) { - delegate.didPressUserAvatar(ChatMessageCell.this, currentForwardUser, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(ChatMessageCell.this, currentForwardUser, lastTouchX, lastTouchY, false); } else if (currentForwardName != null) { delegate.didPressHiddenForward(ChatMessageCell.this); } @@ -22656,7 +22655,7 @@ public ProfileSpan(TLRPC.User user) { @Override public void onClick(@NonNull View view) { if (delegate != null) { - delegate.didPressUserAvatar(ChatMessageCell.this, user, 0, 0); + delegate.didPressUserAvatar(ChatMessageCell.this, user, 0, 0, false); } } } @@ -23341,7 +23340,7 @@ public boolean performAction(int virtualViewId, int action, Bundle arguments) { } else if (action == AccessibilityNodeInfo.ACTION_CLICK) { if (virtualViewId == PROFILE) { if (delegate != null) { - delegate.didPressUserAvatar(ChatMessageCell.this, currentUser, 0, 0); + delegate.didPressUserAvatar(ChatMessageCell.this, currentUser, 0, 0, false); } } else if (virtualViewId >= LINK_CAPTION_IDS_START) { ClickableSpan link = getLinkById(virtualViewId, true); @@ -23414,9 +23413,9 @@ public boolean performAction(int virtualViewId, int action, Bundle arguments) { } else if (virtualViewId == FORWARD) { if (delegate != null) { if (currentForwardChannel != null) { - delegate.didPressChannelAvatar(ChatMessageCell.this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY); + delegate.didPressChannelAvatar(ChatMessageCell.this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post, lastTouchX, lastTouchY, false); } else if (currentForwardUser != null) { - delegate.didPressUserAvatar(ChatMessageCell.this, currentForwardUser, lastTouchX, lastTouchY); + delegate.didPressUserAvatar(ChatMessageCell.this, currentForwardUser, lastTouchX, lastTouchY, false); } else if (currentForwardName != null) { delegate.didPressHiddenForward(ChatMessageCell.this); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupMedia.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupMedia.java index 7d5ab04e13..aebf3e8768 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupMedia.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/GroupMedia.java @@ -27,6 +27,8 @@ import androidx.annotation.NonNull; import androidx.collection.LongSparseArray; +import com.google.android.exoplayer2.offline.Download; + import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.DownloadController; import org.telegram.messenger.FileLoader; @@ -36,6 +38,7 @@ import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject.GroupedMessagePosition; +import org.telegram.messenger.R; import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SharedConfig; import org.telegram.messenger.Utilities; @@ -597,15 +600,11 @@ public void drawImages(Canvas canvas, boolean withSpoilers) { if (messageObject.isSending()) { SendMessagesHelper sendMessagesHelper = SendMessagesHelper.getInstance(messageObject.currentAccount); long[] progress = ImageLoader.getInstance().getFileProgressSizes(h.attachPath); - float loadingProgress = 0; - boolean sending = sendMessagesHelper.isSendingMessage(messageObject.getId()); + final boolean sending = sendMessagesHelper.isSendingPaidMessage(messageObject.getId(), i); if (progress == null && sending) { - loadingProgress = 1.0f; - } else if (progress != null) { - loadingProgress = DownloadController.getProgress(progress); + h.radialProgress.setProgress(1.0f, true); + h.setIcon(h.album ? MediaActionDrawable.ICON_CHECK : h.getDefaultIcon()); } - h.radialProgress.setProgress(loadingProgress, false); - h.setIcon(sending && loadingProgress < 1.0f ? MediaActionDrawable.ICON_CANCEL : (h.album ? MediaActionDrawable.ICON_CHECK : h.getDefaultIcon())); } else if (FileLoader.getInstance(messageObject.currentAccount).isLoadingFile(h.filename)) { h.setIcon(MediaActionDrawable.ICON_CANCEL); } else { @@ -620,7 +619,7 @@ public void drawImages(Canvas canvas, boolean withSpoilers) { canvas.clipPath(clipPath2); canvas.translate(l, t); canvas.saveLayerAlpha(0, 0, (int) (r - l), (int) (b - t), (int) (0xFF * hiddenAlpha), Canvas.ALL_SAVE_FLAG); - spoilerEffect.draw(canvas, cell, (int) (r - l), (int) (b - t), 1f); + spoilerEffect.draw(canvas, cell, (int) (r - l), (int) (b - t), 1f, cell.drawingToBitmap); canvas.restore(); canvas.restore(); cell.invalidate(); @@ -734,7 +733,7 @@ public void updateMedia(TLRPC.MessageExtendedMedia media, MessageObject msg) { this.media = media; autoplay = false; - final String filter = w + "_" + h; + String filter = w + "_" + h; if (media instanceof TLRPC.TL_messageExtendedMediaPreview) { hidden = true; filename = null; @@ -747,7 +746,11 @@ public void updateMedia(TLRPC.MessageExtendedMedia media, MessageObject msg) { AndroidUtilities.adjustBrightnessColorMatrix(colorMatrix, -.1f); this.imageReceiver.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); } else if (media instanceof TLRPC.TL_messageExtendedMedia) { - hidden = false; + hidden = msg.isRepostPreview; + if (hidden) { + filter += "_b3"; + } + final int cacheType = 0; this.imageReceiver.setColorFilter(null); @@ -760,23 +763,15 @@ public void updateMedia(TLRPC.MessageExtendedMedia media, MessageObject msg) { TLRPC.PhotoSize thumbSize = FileLoader.getClosestPhotoSizeWithSize(mediaPhoto.photo.sizes, Math.min(w, h) / 100, false, photoSize, false); ImageLocation photoLocation = ImageLocation.getForPhoto(photoSize, mediaPhoto.photo); ImageLocation thumbLocation = ImageLocation.getForPhoto(thumbSize, mediaPhoto.photo); -// if (msg.isSending()) { -// sendingPhotoLocation = photoLocation; -// sendingPhotoLocationDialogId = msg.getDialogId(); -// sendingPhotoLocationMessageId = msg.getId(); -// } -// if (sendingPhotoLocation != null && sendingPhotoLocationDialogId == msg.getDialogId() && sendingPhotoLocationMessageId == msg.getId()) { -// thumbLocation = sendingPhotoLocation; -// } imageReceiver.setImage( photoLocation, filter, thumbLocation, filter, 0, null, - msg, 0 + msg, cacheType ); } else if (messageMedia instanceof TLRPC.TL_messageMediaDocument) { TLRPC.TL_messageMediaDocument mediaDocument = (TLRPC.TL_messageMediaDocument) messageMedia; - autoplay = !album && video && SharedConfig.isAutoplayVideo(); + autoplay = !hidden && !album && video && SharedConfig.isAutoplayVideo(); // if (!TextUtils.isEmpty(extMedia.attachPath)) { // imageReceiver.setImage(ImageLocation.getForPath(extMedia.attachPath), filter + (autoplay ? "_g" : ""), null, null, msg, 0); // return; @@ -788,20 +783,12 @@ public void updateMedia(TLRPC.MessageExtendedMedia media, MessageObject msg) { ImageLocation mediaLocation = ImageLocation.getForDocument(mediaDocument.document); ImageLocation photoLocation = ImageLocation.getForDocument(photoSize, mediaDocument.document); ImageLocation thumbLocation = ImageLocation.getForDocument(thumbSize, mediaDocument.document); -// if (msg.isSending()) { -// sendingPhotoLocation = photoLocation; -// sendingPhotoLocationDialogId = msg.getDialogId(); -// sendingPhotoLocationMessageId = msg.getId(); -// } -// if (sendingPhotoLocation != null && sendingPhotoLocationDialogId == msg.getDialogId() && sendingPhotoLocationMessageId == msg.getId()) { -// thumbLocation = sendingPhotoLocation; -// } imageReceiver.setImage( - mediaLocation, filter + (autoplay ? "_g" : ""), + autoplay ? mediaLocation : null, filter + (autoplay ? "_g" : ""), photoLocation, filter, - thumbLocation, filter, null, + thumbLocation, filter, null, 0, null, - msg, 0 + msg, cacheType ); return; } @@ -811,19 +798,11 @@ public void updateMedia(TLRPC.MessageExtendedMedia media, MessageObject msg) { TLRPC.PhotoSize thumbSize = FileLoader.getClosestPhotoSizeWithSize(mediaDocument.document.thumbs, Math.min(w, h), false, photoSize, false); ImageLocation photoLocation = ImageLocation.getForDocument(photoSize, mediaDocument.document); ImageLocation thumbLocation = ImageLocation.getForDocument(thumbSize, mediaDocument.document); -// if (msg.isSending()) { -// sendingPhotoLocation = photoLocation; -// sendingPhotoLocationDialogId = msg.getDialogId(); -// sendingPhotoLocationMessageId = msg.getId(); -// } -// if (sendingPhotoLocation != null && sendingPhotoLocationDialogId == msg.getDialogId() && sendingPhotoLocationMessageId == msg.getId()) { -// thumbLocation = sendingPhotoLocation; -// } imageReceiver.setImage( photoLocation, filter, thumbLocation, filter, 0, null, - msg, 0 + msg, cacheType ); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java index b85e84fa8e..7bc80f65e8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/PhotoAttachPhotoCell.java @@ -669,7 +669,7 @@ public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { } if (photoEntry != null) { sb.append(". "); - sb.append(LocaleController.getInstance().formatterStats.format(photoEntry.dateTaken * 1000L)); + sb.append(LocaleController.getInstance().getFormatterStats().format(photoEntry.dateTaken * 1000L)); } info.setText(sb); if (checkBox.isChecked()) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java index 389400c578..364ebd6419 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedDocumentCell.java @@ -357,7 +357,7 @@ public void setPhotoEntry(MediaController.PhotoEntry entry) { if (builder.length() > 0) { builder.append(", "); } - builder.append(LocaleController.getInstance().formatterStats.format(entry.dateTaken)); + builder.append(LocaleController.getInstance().getFormatterStats().format(entry.dateTaken)); dateTextView.setText(builder); placeholderImageView.setVisibility(GONE); } @@ -518,7 +518,7 @@ private void updateDateView() { .append(fromName)); rightDateTextView.setText(LocaleController.stringForMessageListDate(message.messageOwner.date)); } else { - dateTextView.setText(String.format("%s, %s", fileSize, LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))))); + dateTextView.setText(String.format("%s, %s", fileSize, LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))))); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StatisticPostInfoCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StatisticPostInfoCell.java index d7b4a8a7da..b07209417f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Cells/StatisticPostInfoCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Cells/StatisticPostInfoCell.java @@ -235,8 +235,8 @@ public void setData(StatisticActivity.RecentPostInfo postInfo, boolean isLast) { views.setText(String.format(LocaleController.getPluralString("Views", postInfo.getViews()), AndroidUtilities.formatWholeNumber(postInfo.getViews(), 0))); Date time = new Date(postInfo.getDate() * 1000L); - String monthTxt = LocaleController.getInstance().formatterYear.format(time); - String timeTxt = LocaleController.getInstance().formatterDay.format(time); + String monthTxt = LocaleController.getInstance().getFormatterYear().format(time); + String timeTxt = LocaleController.getInstance().getFormatterDay().format(time); date.setText(LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, monthTxt, timeTxt)); shares.setText(AndroidUtilities.formatWholeNumber(postInfo.getForwards(), 0)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java index 828eefb7ee..7f46a0848c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChannelAdminLogActivity.java @@ -2438,6 +2438,7 @@ private void loadAntispamUser(long userId) { @Override public void onRemoveFromParent() { MediaController.getInstance().setTextureView(videoTextureView, null, null, false); + super.onRemoveFromParent(); } private void hideFloatingDateView(boolean animated) { @@ -2909,7 +2910,7 @@ public boolean needPlayMessage(ChatMessageCell cell, MessageObject messageObject } @Override - public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { + public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY, boolean asForward) { if (chat != null && chat != currentChat) { Bundle args = new Bundle(); args.putLong("chat_id", chat.id); @@ -2928,7 +2929,7 @@ public void didPressOther(ChatMessageCell cell, float x, float y) { } @Override - public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { + public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY, boolean asForward) { if (user != null && user.id != UserConfig.getInstance(currentAccount).getClientUserId()) { openProfile(user); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChannelMonetizationLayout.java b/TMessagesProj/src/main/java/org/telegram/ui/ChannelMonetizationLayout.java index 33367fd79f..68d9e680f2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChannelMonetizationLayout.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChannelMonetizationLayout.java @@ -114,6 +114,7 @@ public class ChannelMonetizationLayout extends SizeNotifierFrameLayout implement private final CharSequence titleInfo; private final CharSequence balanceInfo; + private final CharSequence proceedsInfo; private final CharSequence starsBalanceInfo; private final LinearLayout balanceLayout; @@ -154,15 +155,24 @@ public void updateList() { } } + public final boolean tonRevenueAvailable; + public final boolean starsRevenueAvailable; + public ChannelMonetizationLayout( Context context, BaseFragment fragment, int currentAccount, long dialogId, - Theme.ResourcesProvider resourcesProvider + Theme.ResourcesProvider resourcesProvider, + + boolean tonRevenueAvailable, + boolean starsRevenueAvailable ) { super(context); + this.tonRevenueAvailable = tonRevenueAvailable; + this.starsRevenueAvailable = starsRevenueAvailable; + DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US); symbols.setDecimalSeparator('.'); formatter = new DecimalFormat("#.##", symbols); @@ -183,6 +193,9 @@ public ChannelMonetizationLayout( balanceInfo = AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(MessagesController.getInstance(currentAccount).channelRevenueWithdrawalEnabled ? R.string.MonetizationBalanceInfo : R.string.MonetizationBalanceInfoNotAvailable), -1, REPLACING_TAG_TYPE_LINK_NBSP, () -> { Browser.openUrl(getContext(), getString(R.string.MonetizationBalanceInfoLink)); }), true); + proceedsInfo = AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(R.string.MonetizationProceedsInfo), -1, REPLACING_TAG_TYPE_LINK_NBSP, () -> { + Browser.openUrl(getContext(), getString(R.string.MonetizationProceedsInfoLink)); + }, resourcesProvider), true); starsBalanceInfo = AndroidUtilities.replaceArrows(AndroidUtilities.replaceSingleTag(getString(R.string.MonetizationStarsInfo), () -> { Browser.openUrl(getContext(), getString(R.string.MonetizationStarsInfoLink)); }), true); @@ -680,6 +693,7 @@ private void setStarsBalance(long crypto_amount, int blockedUntil) { private double stars_rate; private void loadStarsStats() { + if (!starsRevenueAvailable) return; TLRPC.TL_payments_getStarsRevenueStats req2 = new TLRPC.TL_payments_getStarsRevenueStats(); req2.peer = MessagesController.getInstance(currentAccount).getInputPeer(dialogId); req2.dark = Theme.isCurrentThemeDark(); @@ -695,6 +709,12 @@ private void loadStarsStats() { } setupBalances(stats.status); + if (!tonRevenueAvailable) { + progress.animate().alpha(0).setDuration(380).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> { + progress.setVisibility(View.GONE); + }).start(); + } + if (listView != null) { listView.adapter.update(true); } @@ -719,58 +739,63 @@ private void initLevel() { loadStarsStats(); - TLObject req; - if (ChatObject.isMegagroup(chat)) { - return; - } else { - TL_stats.TL_getBroadcastRevenueStats getBroadcastStats = new TL_stats.TL_getBroadcastRevenueStats(); - getBroadcastStats.dark = Theme.isCurrentThemeDark(); - getBroadcastStats.channel = MessagesController.getInstance(currentAccount).getInputChannel(-dialogId); - req = getBroadcastStats; - } - int stats_dc = -1; - TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); - if (chatFull != null) { - stats_dc = chatFull.stats_dc; - initialSwitchOffValue = switchOffValue = chatFull.restricted_sponsored; - } - if (stats_dc == -1) return; - ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { - if (res instanceof TL_stats.TL_broadcastRevenueStats) { - TL_stats.TL_broadcastRevenueStats stats = (TL_stats.TL_broadcastRevenueStats) res; + if (tonRevenueAvailable) { + TLObject req; + if (ChatObject.isMegagroup(chat)) { + return; + } else { + TL_stats.TL_getBroadcastRevenueStats getBroadcastStats = new TL_stats.TL_getBroadcastRevenueStats(); + getBroadcastStats.dark = Theme.isCurrentThemeDark(); + getBroadcastStats.channel = MessagesController.getInstance(currentAccount).getInputChannel(-dialogId); + req = getBroadcastStats; + } + int stats_dc = -1; + TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(-dialogId); + if (chatFull != null) { + stats_dc = chatFull.stats_dc; + initialSwitchOffValue = switchOffValue = chatFull.restricted_sponsored; + } + if (stats_dc == -1) return; + ConnectionsManager.getInstance(currentAccount).sendRequest(req, (res, err) -> AndroidUtilities.runOnUIThread(() -> { + if (res instanceof TL_stats.TL_broadcastRevenueStats) { + TL_stats.TL_broadcastRevenueStats stats = (TL_stats.TL_broadcastRevenueStats) res; - impressionsChart = StatisticActivity.createViewData(stats.top_hours_graph, getString(R.string.MonetizationGraphImpressions), 0); - if (stats.revenue_graph != null) { - stats.revenue_graph.rate = (float) (1_000_000_000.0 / 100.0 / stats.usd_rate); - } - revenueChart = StatisticActivity.createViewData(stats.revenue_graph, getString(R.string.MonetizationGraphRevenue), 2); - if (impressionsChart != null) { - impressionsChart.useHourFormat = true; - } + impressionsChart = StatisticActivity.createViewData(stats.top_hours_graph, getString(R.string.MonetizationGraphImpressions), 0); + if (stats.revenue_graph != null) { + stats.revenue_graph.rate = (float) (1_000_000_000.0 / 100.0 / stats.usd_rate); + } + revenueChart = StatisticActivity.createViewData(stats.revenue_graph, getString(R.string.MonetizationGraphRevenue), 2); + if (impressionsChart != null) { + impressionsChart.useHourFormat = true; + } - ton_rate = stats.usd_rate; - setupBalances(stats.balances); + ton_rate = stats.usd_rate; + setupBalances(stats.balances); - progress.animate().alpha(0).setDuration(380).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> { - progress.setVisibility(View.GONE); - }).start(); + progress.animate().alpha(0).setDuration(380).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> { + progress.setVisibility(View.GONE); + }).start(); - checkLearnSheet(); - } - }), null, null, 0, stats_dc, ConnectionsManager.ConnectionTypeGeneric, true); + checkLearnSheet(); + } + }), null, null, 0, stats_dc, ConnectionsManager.ConnectionTypeGeneric, true); + } } public void setupBalances(TLRPC.TL_broadcastRevenueBalances balances) { if (ton_rate == 0) { return; } + availableValue.contains1 = true; availableValue.crypto_amount = balances.available_balance; availableValue.amount = (long) (availableValue.crypto_amount / 1_000_000_000.0 * ton_rate * 100.0); setBalance(availableValue.crypto_amount, availableValue.amount); availableValue.currency = "USD"; + lastWithdrawalValue.contains1 = true; lastWithdrawalValue.crypto_amount = balances.current_balance; lastWithdrawalValue.amount = (long) (lastWithdrawalValue.crypto_amount / 1_000_000_000.0 * ton_rate * 100.0); lastWithdrawalValue.currency = "USD"; + lifetimeValue.contains1 = true; lifetimeValue.crypto_amount = balances.overall_revenue; lifetimeValue.amount = (long) (lifetimeValue.crypto_amount / 1_000_000_000.0 * ton_rate * 100.0); lifetimeValue.currency = "USD"; @@ -860,16 +885,18 @@ private void fillItems(ArrayList items, UniversalAdapter adapter) { if (chatFull != null) { stats_dc = chatFull.stats_dc; } - items.add(UItem.asCenterShadow(titleInfo)); - if (impressionsChart != null && !impressionsChart.isEmpty) { - items.add(UItem.asChart(StatisticActivity.VIEW_TYPE_BAR_LINEAR, stats_dc, impressionsChart)); - items.add(UItem.asShadow(-1, null)); - } - if (revenueChart != null && !revenueChart.isEmpty) { - items.add(UItem.asChart(StatisticActivity.VIEW_TYPE_STACKBAR, stats_dc, revenueChart)); - items.add(UItem.asShadow(-2, null)); + if (tonRevenueAvailable) { + items.add(UItem.asCenterShadow(titleInfo)); + if (impressionsChart != null && !impressionsChart.isEmpty) { + items.add(UItem.asChart(StatisticActivity.VIEW_TYPE_BAR_LINEAR, stats_dc, impressionsChart)); + items.add(UItem.asShadow(-1, null)); + } + if (revenueChart != null && !revenueChart.isEmpty) { + items.add(UItem.asChart(StatisticActivity.VIEW_TYPE_STACKBAR, stats_dc, revenueChart)); + items.add(UItem.asShadow(-2, null)); + } } - if (starsRevenueChart != null && !starsRevenueChart.isEmpty) { + if (starsRevenueAvailable && starsRevenueChart != null && !starsRevenueChart.isEmpty) { items.add(UItem.asChart(StatisticActivity.VIEW_TYPE_STACKBAR, stats_dc, starsRevenueChart)); items.add(UItem.asShadow(-3, null)); } @@ -878,22 +905,24 @@ private void fillItems(ArrayList items, UniversalAdapter adapter) { items.add(UItem.asProceedOverview(availableValue)); items.add(UItem.asProceedOverview(lastWithdrawalValue)); items.add(UItem.asProceedOverview(lifetimeValue)); - items.add(UItem.asShadow(-4, null)); + items.add(UItem.asShadow(-4, proceedsInfo)); } if (chat != null && chat.creator) { - items.add(UItem.asBlackHeader(getString(R.string.MonetizationBalance))); - items.add(UItem.asCustom(balanceLayout)); - items.add(UItem.asShadow(-5, balanceInfo)); - } - if (chat != null && chat.creator) { - final int switchOffLevel = MessagesController.getInstance(currentAccount).channelRestrictSponsoredLevelMin; - items.add(UItem.asCheck(CHECK_SWITCHOFF, PeerColorActivity.withLevelLock(getString(R.string.MonetizationSwitchOff), currentBoostLevel < switchOffLevel ? switchOffLevel : 0)).setChecked(currentBoostLevel >= switchOffLevel && switchOffValue)); - items.add(UItem.asShadow(-8, getString(R.string.MonetizationSwitchOffInfo))); - } - if (chat != null && chat.creator) { - items.add(UItem.asBlackHeader(getString(R.string.MonetizationStarsBalance))); - items.add(UItem.asCustom(STARS_BALANCE, starsBalanceLayout)); - items.add(UItem.asShadow(-6, starsBalanceInfo)); + if (tonRevenueAvailable) { + items.add(UItem.asBlackHeader(getString(R.string.MonetizationBalance))); + items.add(UItem.asCustom(balanceLayout)); + items.add(UItem.asShadow(-5, balanceInfo)); + + final int switchOffLevel = MessagesController.getInstance(currentAccount).channelRestrictSponsoredLevelMin; + items.add(UItem.asCheck(CHECK_SWITCHOFF, PeerColorActivity.withLevelLock(getString(R.string.MonetizationSwitchOff), currentBoostLevel < switchOffLevel ? switchOffLevel : 0)).setChecked(currentBoostLevel >= switchOffLevel && switchOffValue)); + items.add(UItem.asShadow(-8, getString(R.string.MonetizationSwitchOffInfo))); + } + + if (starsRevenueAvailable) { + items.add(UItem.asBlackHeader(getString(R.string.MonetizationStarsBalance))); + items.add(UItem.asCustom(STARS_BALANCE, starsBalanceLayout)); + items.add(UItem.asShadow(-6, starsBalanceInfo)); + } } if (transactionsLayout.hasTransactions()) { items.add(UItem.asFullscreenCustom(transactionsLayout, 0)); @@ -1047,7 +1076,14 @@ public void set(ProceedOverview value) { final long crypto_amount = i == 0 ? value.crypto_amount : value.crypto_amount2; final long amount = i == 0 ? value.amount : value.amount2; - if (i == 1 && !value.contains2) continue; + if (i == 0 && !value.contains1) { + amountContainer[i].setVisibility(View.GONE); + continue; + } + if (i == 1 && !value.contains2) { + amountContainer[i].setVisibility(View.GONE); + continue; + } CharSequence s = crypto_currency + " "; if ("TON".equalsIgnoreCase(crypto_currency)) { @@ -1066,6 +1102,7 @@ public void set(ProceedOverview value) { cryptoAmount.setSpan(new RelativeSizeSpan(13f / 16f), index, cryptoAmount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } + amountContainer[i].setVisibility(View.VISIBLE); cryptoAmountView[i].setText(cryptoAmount); amountView[i].setText("≈" + BillingController.getInstance().formatCurrency(amount, value.currency)); } @@ -1079,6 +1116,7 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { public static class ProceedOverview { + public boolean contains1 = true; public String crypto_currency; public CharSequence text; public long crypto_amount; @@ -1099,6 +1137,7 @@ public static ProceedOverview as(String cryptoCurrency, CharSequence text) { public static ProceedOverview as(String cryptoCurrency, String cryptoCurrency2, CharSequence text) { ProceedOverview o = new ProceedOverview(); + o.contains1 = false; o.crypto_currency = cryptoCurrency; o.crypto_currency2 = cryptoCurrency2; o.text = text; @@ -1552,7 +1591,7 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { } } - public static class ChannelTransactionsView extends LinearLayout { + public class ChannelTransactionsView extends LinearLayout { private final int currentAccount; private final ViewPagerFixed viewPager; @@ -1711,7 +1750,7 @@ private void loadTransactions(int type) { final boolean hadTransactions = hasTransactions(); final boolean hadTheseTransactions = hasTransactions(type); if (type == TON_TRANSACTIONS) { - if (tonTransactions.size() >= tonTransactionsTotalCount && tonTransactionsTotalCount != 0) + if (tonTransactions.size() >= tonTransactionsTotalCount && tonTransactionsTotalCount != 0 || !tonRevenueAvailable) return; loadingTransactions[type] = true; TL_stats.TL_getBroadcastRevenueTransactions req = new TL_stats.TL_getBroadcastRevenueTransactions(); @@ -1737,7 +1776,7 @@ private void loadTransactions(int type) { } })); } else if (type == STARS_TRANSACTIONS) { - if (starsLastOffset == null) + if (starsLastOffset == null || !starsRevenueAvailable) return; loadingTransactions[type] = true; TLRPC.TL_payments_getStarsTransactions req = new TLRPC.TL_payments_getStarsTransactions(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Charts/view_data/ChartHeaderView.java b/TMessagesProj/src/main/java/org/telegram/ui/Charts/view_data/ChartHeaderView.java index c1ce68b501..1c384355b7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Charts/view_data/ChartHeaderView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Charts/view_data/ChartHeaderView.java @@ -111,9 +111,9 @@ public void setDates(long start, long end) { } final String newText; if (end - start >= 86400000L) { - newText = LocaleController.getInstance().formatterYear.format(new Date(start)) + " — " + LocaleController.getInstance().formatterYear.format(new Date(end)); + newText = LocaleController.getInstance().getFormatterYear().format(new Date(start)) + " — " + LocaleController.getInstance().getFormatterYear().format(new Date(end)); } else { - newText = LocaleController.getInstance().formatterYear.format(new Date(start)); + newText = LocaleController.getInstance().getFormatterYear().format(new Date(start)); } dates.setText(newText); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index a704b70897..f56c1b332c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -251,7 +251,6 @@ import org.telegram.ui.Delegates.ChatActivityMemberRequestsDelegate; import org.telegram.ui.Stars.StarsController; import org.telegram.ui.Stars.StarsIntroActivity; -import org.telegram.ui.Stories.SelfStoryViewsPage; import org.telegram.ui.Stories.StoriesListPlaceProvider; import org.telegram.ui.Stories.StoriesUtilities; import org.telegram.ui.Stories.recorder.HintView2; @@ -13481,6 +13480,7 @@ public void onRemoveFromParent() { } else { MediaController.getInstance().setTextureView(videoTextureView, null, null, false); } + super.onRemoveFromParent(); } protected void setIgnoreAttachOnPause(boolean value) { @@ -15969,6 +15969,7 @@ private void removeSelectedMessageHighlight() { public static final int PROGRESS_BOT_BUTTON = 3; public static final int PROGRESS_GIFT = 4; public static final int PROGRESS_PAID_MEDIA = 5; + public static final int PROGRESS_FORWARD = 6; private int progressDialogAtMessageId; private int progressDialogAtMessageType; @@ -34222,6 +34223,33 @@ public void end(boolean replaced) { } : null; } + private Browser.Progress makeProgressForForward(ChatMessageCell cell) { + if (progressDialogCurrent != null) { + progressDialogCurrent.cancel(true); + progressDialogCurrent = null; + } + return progressDialogCurrent = cell != null && cell.getMessageObject() != null ? new Browser.Progress() { + @Override + public void init() { + progressDialogAtMessageId = cell.getMessageObject().getId(); + progressDialogAtMessageType = PROGRESS_FORWARD; + + cell.invalidate(); + } + + @Override + public void end(boolean replaced) { + if (!replaced) { + AndroidUtilities.runOnUIThread(() -> { + if (progressDialogAtMessageId == cell.getMessageObject().getId()) { + resetProgressDialogLoading(); + } + }, 240); + } + } + } : null; + } + private Browser.Progress makeProgressForBotButton(ChatMessageCell cell, String url) { if (progressDialogCurrent != null) { progressDialogCurrent.cancel(true); @@ -36660,7 +36688,7 @@ public void didPressTime(ChatMessageCell cell) { } @Override - public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY) { + public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int postId, float touchX, float touchY, boolean asForward) { if (chat == null) { return; } @@ -36668,7 +36696,7 @@ public void didPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, int pos processRowSelect(cell, true, touchX, touchY); return; } - openChat(cell, chat, postId); + openChat(cell, chat, postId, asForward); } @Override @@ -36764,7 +36792,7 @@ public void didPressUserStatus(ChatMessageCell cell, TLRPC.User user, TLRPC.Docu } @Override - public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY) { + public void didPressUserAvatar(ChatMessageCell cell, TLRPC.User user, float touchX, float touchY, boolean asForward) { if (actionBar.isActionModeShowed() || reportType >= 0) { processRowSelect(cell, true, touchX, touchY); return; @@ -36876,7 +36904,7 @@ public boolean didLongPressChannelAvatar(ChatMessageCell cell, TLRPC.Chat chat, break; case OPEN_GROUP: case OPEN_CHANNEL: - openChat(cell, chat, 0); + openChat(cell, chat, 0, false); break; } }); @@ -36928,7 +36956,7 @@ private void openDialog(ChatMessageCell cell, TLRPC.User user) { } } - private void openChat(ChatMessageCell cell, TLRPC.Chat chat, int postId) { + private void openChat(ChatMessageCell cell, TLRPC.Chat chat, int postId, boolean asForward) { if (currentChat != null && chat.id == currentChat.id) { if (avatarContainer != null && postId == 0) { avatarContainer.openProfile(false); @@ -36941,8 +36969,26 @@ private void openChat(ChatMessageCell cell, TLRPC.Chat chat, int postId) { if (postId != 0) { args.putInt("message_id", postId); } - if (getMessagesController().checkCanOpenChat(args, ChatActivity.this, cell.getMessageObject())) { - presentFragment(new ChatActivity(args)); + Browser.Progress progress = asForward ? makeProgressForForward(cell) : null; + if (getMessagesController().checkCanOpenChat(args, ChatActivity.this, cell.getMessageObject(), progress)) { + ChatActivity chatActivity = new ChatActivity(args); + if (progress != null && postId != 0) { + progress.onCancel(getMessagesController().ensureMessagesLoaded(-chat.id, postId, new MessagesController.MessagesLoadedCallback() { + @Override + public void onMessagesLoaded(boolean fromCache) { + progress.end(); + presentFragment(chatActivity); + } + @Override + public void onError() { + progress.end(); + presentFragment(chatActivity); + } + })); + progress.init(); + } else { + presentFragment(chatActivity); + } } } } @@ -37616,7 +37662,7 @@ public void end(boolean replaced) { if (!safe && !Browser.isInternalUri(uri, null)) { AlertsCreator.showOpenUrlAlert(ChatActivity.this, url, true, true, true, !safe, progressDialogCurrent, themeDelegate); } else { - Browser.openUrl(getContext(), uri, true, true, false, progressDialogCurrent); + Browser.openUrl(getContext(), uri, true, true, false, progressDialogCurrent, null); } } @@ -38291,7 +38337,7 @@ public void end(boolean replaced) { return; } } - Browser.openUrl(getParentActivity(), Uri.parse(webPage.url), true, true, false, progressDialogCurrent); + Browser.openUrl(getParentActivity(), Uri.parse(webPage.url), true, true, false, progressDialogCurrent, null); } else { if (messageObject.isSponsored()) { logSponsoredClicked(messageObject); @@ -38316,7 +38362,7 @@ public void end(boolean replaced) { } } }; - Browser.openUrl(getContext(), Uri.parse(messageObject.sponsoredUrl), true, false, false, progressDialogCurrent); + Browser.openUrl(getContext(), Uri.parse(messageObject.sponsoredUrl), true, false, false, progressDialogCurrent, null); } } else { TLRPC.WebPage webPage = messageObject.getStoryMentionWebpage(); @@ -38360,7 +38406,7 @@ public void end(boolean replaced) { } } }; - Browser.openUrl(getParentActivity(), Uri.parse(webPage.url), true, true, false, progressDialogCurrent); + Browser.openUrl(getParentActivity(), Uri.parse(webPage.url), true, true, false, progressDialogCurrent, null); } } } @@ -41484,17 +41530,20 @@ public ThanosEffect getChatThanosEffect() { if (getContext() == null || !ThanosEffect.supports() || chatListView == null || contentView == null) { return null; } - chatListThanosEffect = new ThanosEffect(getContext(), () -> { - if (removingFromParent) { + final ThanosEffect[] thisThanosEffect = new ThanosEffect[1]; + final ThanosEffect thanosEffect = new ThanosEffect(getContext(), () -> { + if (removingFromParent || thisThanosEffect[0] == null) { return; } - ThanosEffect thisThanosEffect = chatListThanosEffect; - if (thisThanosEffect != null) { + ThanosEffect effect = thisThanosEffect[0]; + AndroidUtilities.removeFromParent(effect); + thisThanosEffect[0] = null; + if (chatListThanosEffect == effect) { chatListThanosEffect = null; - contentView.removeView(thisThanosEffect); } }); - contentView.addView(chatListThanosEffect, 1 + contentView.indexOfChild(chatListView), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); + thisThanosEffect[0] = chatListThanosEffect = thanosEffect; + contentView.addView(thanosEffect, 1 + contentView.indexOfChild(chatListView), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); } return chatListThanosEffect; } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java index 44a2adf516..a0c27334ce 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AlertsCreator.java @@ -1246,7 +1246,7 @@ public static void showOpenUrlAlert(BaseFragment fragment, String url, boolean p } long inlineReturn = (fragment instanceof ChatActivity) ? ((ChatActivity) fragment).getInlineReturn() : 0; if (Browser.isInternalUrl(url, null) || !ask || NekoConfig.skipOpenLinkConfirm.Bool()) { - Browser.openUrl(fragment.getParentActivity(), Uri.parse(url), inlineReturn == 0, tryTelegraph, forceNotInternalForApps && checkInternalBotApp(url), progress); + Browser.openUrl(fragment.getParentActivity(), Uri.parse(url), inlineReturn == 0, tryTelegraph, forceNotInternalForApps && checkInternalBotApp(url), progress, null); } else { String urlFinal = url; // if (punycode) { @@ -3102,7 +3102,7 @@ public static boolean checkScheduleDate(TextView button, TextView infoText, long } else if (type == 3) { num += 9; } - button.setText(LocaleController.getInstance().formatterScheduleSend[num].format(time)); + button.setText(LocaleController.getInstance().getFormatterScheduleSend(num).format(time)); } if (infoText != null) { int diff = (int) ((time - systemTime) / 1000); @@ -3349,16 +3349,16 @@ public CharSequence getAccessibilityClassName() { calendar.setTimeInMillis(date); int year = calendar.get(Calendar.YEAR); LocaleController loc = LocaleController.getInstance(); - final String week = loc.formatterWeek.format(date) + ", "; + final String week = loc.getFormatterWeek().format(date) + ", "; if (year == currentYear) { return ( - LocaleController.getInstance().formatterWeek.format(date) + + LocaleController.getInstance().getFormatterWeek().format(date) + ", " + - LocaleController.getInstance().formatterScheduleDay.format(date) + LocaleController.getInstance().getFormatterScheduleDay().format(date) ); } else { - return week + loc.formatterScheduleYear.format(date); + return week + loc.getFormatterScheduleYear().format(date); } } }); @@ -3537,9 +3537,9 @@ public CharSequence getAccessibilityClassName() { calendar.setTimeInMillis(date); int year = calendar.get(Calendar.YEAR); if (year == currentYear) { - return LocaleController.getInstance().formatterScheduleDay.format(date); + return LocaleController.getInstance().getFormatterScheduleDay().format(date); } else { - return LocaleController.getInstance().formatterScheduleYear.format(date); + return LocaleController.getInstance().getFormatterScheduleYear().format(date); } } }); @@ -3967,11 +3967,11 @@ public CharSequence getAccessibilityClassName() { int year = calendar.get(Calendar.YEAR); int yearDay = calendar.get(Calendar.DAY_OF_YEAR); if (year == currentYear && yearDay < currentDayYear + 7) { - return LocaleController.getInstance().formatterWeek.format(date) + ", " + LocaleController.getInstance().formatterScheduleDay.format(date); + return LocaleController.getInstance().getFormatterWeek().format(date) + ", " + LocaleController.getInstance().getFormatterScheduleDay().format(date); } else if (year == currentYear) { - return LocaleController.getInstance().formatterScheduleDay.format(date); + return LocaleController.getInstance().getFormatterScheduleDay().format(date); } else { - return LocaleController.getInstance().formatterScheduleYear.format(date); + return LocaleController.getInstance().getFormatterScheduleYear().format(date); } } }); @@ -6419,7 +6419,7 @@ public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User u if (isActiveGiveawayAndOwner) { TLRPC.TL_messageMediaGiveaway giveaway = (TLRPC.TL_messageMediaGiveaway) selectedMessage.messageOwner.media; long untilDate = giveaway.until_date * 1000L; - giveawayEndDate = LocaleController.getInstance().formatterGiveawayMonthDayYear.format(new Date(untilDate)); + giveawayEndDate = LocaleController.getInstance().getFormatterGiveawayMonthDayYear().format(new Date(untilDate)); isActiveGiveawayAndOwner = System.currentTimeMillis() < untilDate; } } else if (count == 1) { @@ -6430,7 +6430,7 @@ public static void createDeleteMessagesAlert(BaseFragment fragment, TLRPC.User u if (isActiveGiveawayAndOwner) { TLRPC.TL_messageMediaGiveaway giveaway = (TLRPC.TL_messageMediaGiveaway) msg.messageOwner.media; long untilDate = giveaway.until_date * 1000L; - giveawayEndDate = LocaleController.getInstance().formatterGiveawayMonthDayYear.format(new Date(untilDate)); + giveawayEndDate = LocaleController.getInstance().getFormatterGiveawayMonthDayYear().format(new Date(untilDate)); isActiveGiveawayAndOwner = System.currentTimeMillis() < untilDate; } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java index 7c88af13ce..7a7784c8b6 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AnimatedFileDrawable.java @@ -122,10 +122,10 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable, private RectF actualDrawRect = new RectF(); - private BitmapShader[] renderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private BitmapShader[] nextRenderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private BitmapShader[] nextRenderingShader2 = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private BitmapShader[] backgroundShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final BitmapShader[] renderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final BitmapShader[] nextRenderingShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final BitmapShader[] nextRenderingShader2 = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final BitmapShader[] backgroundShader = new BitmapShader[1 + DrawingInBackgroundThreadDrawable.THREAD_COUNT]; ArrayList unusedBitmaps = new ArrayList<>(); private BitmapShader renderingShaderBackgroundDraw; @@ -155,15 +155,15 @@ public class AnimatedFileDrawable extends BitmapDrawable implements Animatable, private float scaleFactor = 1f; public boolean isWebmSticker; private final TLRPC.Document document; - private RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private Matrix[] shaderMatrixBackground = new Matrix[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; - private Path[] roundPathBackground = new Path[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final RectF[] dstRectBackground = new RectF[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final Paint[] backgroundPaint = new Paint[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final Matrix[] shaderMatrixBackground = new Matrix[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; + private final Path[] roundPathBackground = new Path[DrawingInBackgroundThreadDrawable.THREAD_COUNT]; private View parentView; - private ArrayList secondParentViews = new ArrayList<>(); + private final ArrayList secondParentViews = new ArrayList<>(); - private ArrayList parents = new ArrayList<>(); + private final ArrayList parents = new ArrayList<>(); private AnimatedFileDrawableStream stream; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java index 15d6297fb7..9d91a31f17 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/AudioPlayerAlert.java @@ -1656,16 +1656,18 @@ private void showAlbumCover(boolean show, boolean animated) { blurredAnimationInProgress = true; BaseFragment fragment = parentActivity.getActionBarLayout().getFragmentStack().get(parentActivity.getActionBarLayout().getFragmentStack().size() - 1); View fragmentView = fragment.getFragmentView(); - int w = (int) (fragmentView.getMeasuredWidth() / 6.0f); - int h = (int) (fragmentView.getMeasuredHeight() / 6.0f); - Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - canvas.scale(1.0f / 6.0f, 1.0f / 6.0f); - fragmentView.draw(canvas); - canvas.translate(containerView.getLeft() - getLeftInset(), 0); - containerView.draw(canvas); - Utilities.stackBlurBitmap(bitmap, Math.max(7, Math.max(w, h) / 180)); - blurredView.setBackground(new BitmapDrawable(bitmap)); + if (fragmentView != null) { + int w = (int) (fragmentView.getMeasuredWidth() / 6.0f); + int h = (int) (fragmentView.getMeasuredHeight() / 6.0f); + Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + canvas.scale(1.0f / 6.0f, 1.0f / 6.0f); + fragmentView.draw(canvas); + canvas.translate(containerView.getLeft() - getLeftInset(), 0); + containerView.draw(canvas); + Utilities.stackBlurBitmap(bitmap, Math.max(7, Math.max(w, h) / 180)); + blurredView.setBackground(new BitmapDrawable(bitmap)); + } blurredView.setVisibility(View.VISIBLE); blurredView.animate().alpha(1.0f).setDuration(180).setListener(new AnimatorListenerAdapter() { @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java index 8859a501b8..e0b607fb1c 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAttachAlert.java @@ -2844,6 +2844,7 @@ public int getFillColor() { boolean hasMessageToEffect = false; MessageObject messageWithCaption = null; + boolean canHaveStars = false; ArrayList messageObjects = new ArrayList<>(); int id = 0; if (currentAttachLayout == photoLayout || currentAttachLayout == photoPreviewLayout) { @@ -2951,6 +2952,7 @@ public int getFillColor() { if (messageWithCaption == null && !TextUtils.isEmpty(msg.message)) { messageWithCaption = messageObject; } + canHaveStars = true; } } } @@ -3145,7 +3147,7 @@ R.raw.position_above, getString(R.string.CaptionBelow), } }); } - if (chatActivity != null && ChatObject.isChannelAndNotMegaGroup(chatActivity.getCurrentChat()) && chatActivity.getCurrentChatInfo() != null && chatActivity.getCurrentChatInfo().paid_media_allowed) { + if (canHaveStars && chatActivity != null && ChatObject.isChannelAndNotMegaGroup(chatActivity.getCurrentChat()) && chatActivity.getCurrentChatInfo() != null && chatActivity.getCurrentChatInfo().paid_media_allowed) { ActionBarMenuSubItem item = options.add(R.drawable.menu_feature_paid, getString(R.string.PaidMediaButton), null).getLast(); item.setOnClickListener(v -> { if (photoLayout == null) return; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardBackground.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardBackground.java index 3374bdb0e8..dff7d2b91a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardBackground.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ForwardBackground.java @@ -138,14 +138,45 @@ public void setPressed(boolean pressed, float x, float y) { view.invalidate(); } - public void draw(Canvas canvas) { + private LoadingDrawable loadingDrawable; + + public void draw(Canvas canvas, boolean loading) { canvas.save(); canvas.clipPath(path); if (rippleDrawable != null) { rippleDrawable.setBounds(bounds); rippleDrawable.draw(canvas); } + + if (loading) { + if (loadingDrawable == null) { + loadingDrawable = new LoadingDrawable(); + loadingDrawable.setAppearByGradient(true); + } else if (loadingDrawable.isDisappeared() || loadingDrawable.isDisappearing()) { + loadingDrawable.reset(); + loadingDrawable.resetDisappear(); + } + } else if (loadingDrawable != null && !loadingDrawable.isDisappearing() && !loadingDrawable.isDisappeared()) { + loadingDrawable.disappear(); + } + canvas.restore(); + + if (loadingDrawable != null && !loadingDrawable.isDisappeared()) { + loadingDrawable.usePath(path); + loadingDrawable.setColors( + Theme.multAlpha(rippleDrawableColor, .7f), + Theme.multAlpha(rippleDrawableColor, 1.3f), + Theme.multAlpha(rippleDrawableColor, 1.5f), + Theme.multAlpha(rippleDrawableColor, 2f) + ); + loadingDrawable.setBounds(bounds); + canvas.save(); + loadingDrawable.draw(canvas); + canvas.restore(); + view.invalidate(); + } + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/MessagePrivateSeenView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/MessagePrivateSeenView.java index 7b8b9b1e42..970e845c4d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/MessagePrivateSeenView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/MessagePrivateSeenView.java @@ -314,13 +314,13 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { minWidth = Math.max(minWidth, dp(40 + 96 + 8)); minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.getString(R.string.PmReadUnknown))); minWidth = Math.max(minWidth, dp(40 + 16 + 8) + valueTextView.getPaint().measureText(LocaleController.getString(R.string.PmRead) + premiumTextView.getPaint().measureText(LocaleController.getString(R.string.PmReadShowWhen)))); - minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadTodayAt, LocaleController.getInstance().formatterDay.format(new Date(date))))); + minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadTodayAt, LocaleController.getInstance().getFormatterDay().format(new Date(date))))); if (messageDiff > 60 * 60 * 24) { - minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadYesterdayAt, LocaleController.getInstance().formatterDay.format(new Date(date))))); + minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadYesterdayAt, LocaleController.getInstance().getFormatterDay().format(new Date(date))))); } if (messageDiff > 60 * 60 * 24 * 2) { - minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadDateTimeAt, LocaleController.getInstance().formatterDayMonth.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))))); - minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadDateTimeAt, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))))); + minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadDateTimeAt, LocaleController.getInstance().getFormatterDayMonth().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))))); + minWidth = Math.max(minWidth, dp(40 + 8) + valueTextView.getPaint().measureText(LocaleController.formatString(R.string.PmReadDateTimeAt, LocaleController.getInstance().getFormatterYear().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))))); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/BoostDialogs.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/BoostDialogs.java index ab3b546a0d..989e025211 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/BoostDialogs.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/BoostDialogs.java @@ -79,7 +79,7 @@ public static void processApplyGiftCodeError(TLRPC.TL_error error, FrameLayout c if (error.text.contains("PREMIUM_SUB_ACTIVE_UNTIL_")) { String strDate = error.text.replace("PREMIUM_SUB_ACTIVE_UNTIL_", ""); long date = Long.parseLong(strDate); - String formattedDate = LocaleController.getInstance().formatterBoostExpired.format(new Date(date * 1000L)); + String formattedDate = LocaleController.getInstance().getFormatterBoostExpired().format(new Date(date * 1000L)); String subTitleText = getString("GiftPremiumActivateErrorText", R.string.GiftPremiumActivateErrorText); SpannableStringBuilder subTitleWithLink = AndroidUtilities.replaceSingleTag( subTitleText, @@ -302,9 +302,9 @@ public CharSequence getAccessibilityClassName() { calendar.setTimeInMillis(date); int year = calendar.get(Calendar.YEAR); if (year == currentYear) { - return LocaleController.getInstance().formatterScheduleDay.format(date); + return LocaleController.getInstance().getFormatterScheduleDay().format(date); } else { - return LocaleController.getInstance().formatterScheduleYear.format(date); + return LocaleController.getInstance().getFormatterScheduleYear().format(date); } } }); @@ -502,10 +502,10 @@ public static boolean checkReduceQuantity(List sliderValues, Context co public static void showAbout(boolean isChannel, String from, long msgDate, TLRPC.TL_payments_giveawayInfo giveawayInfo, TLRPC.TL_messageMediaGiveaway giveaway, Context context, Theme.ResourcesProvider resourcesProvider) { int quantity = giveaway.quantity; String months = formatPluralString("BoldMonths", giveaway.months); - String endDate = LocaleController.getInstance().formatterGiveawayMonthDay.format(new Date(giveaway.until_date * 1000L)); + String endDate = LocaleController.getInstance().getFormatterGiveawayMonthDay().format(new Date(giveaway.until_date * 1000L)); - String fromTime = LocaleController.getInstance().formatterDay.format(new Date(giveawayInfo.start_date * 1000L)); - String fromDate = LocaleController.getInstance().formatterGiveawayMonthDayYear.format(new Date(giveawayInfo.start_date * 1000L)); + String fromTime = LocaleController.getInstance().getFormatterDay().format(new Date(giveawayInfo.start_date * 1000L)); + String fromDate = LocaleController.getInstance().getFormatterGiveawayMonthDayYear().format(new Date(giveawayInfo.start_date * 1000L)); boolean isSeveralChats = giveaway.channels.size() > 1; AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider); builder.setTitle(getString("BoostingGiveAwayAbout", R.string.BoostingGiveAwayAbout)); @@ -550,7 +550,7 @@ public static void showAbout(boolean isChannel, String from, long msgDate, TLRPC String title = badChat != null ? badChat.title : ""; stringBuilder.append(replaceTags(formatString(isChannel ? R.string.BoostingGiveawayNotEligibleAdmin : R.string.BoostingGiveawayNotEligibleAdminGroup, title))); } else if (giveawayInfo.joined_too_early_date != 0) { - String date = LocaleController.getInstance().formatterGiveawayMonthDayYear.format(new Date(giveawayInfo.joined_too_early_date * 1000L)); + String date = LocaleController.getInstance().getFormatterGiveawayMonthDayYear().format(new Date(giveawayInfo.joined_too_early_date * 1000L)); stringBuilder.append(replaceTags(formatString("BoostingGiveawayNotEligible", R.string.BoostingGiveawayNotEligible, date))); } else { if (isSeveralChats) { @@ -573,10 +573,10 @@ public static void showAboutEnd(boolean isChannel, String from, long msgDate, TL } int quantity = giveaway.quantity; String months = formatPluralString("BoldMonths", giveaway.months); - String endDate = LocaleController.getInstance().formatterGiveawayMonthDay.format(new Date(giveaway.until_date * 1000L)); + String endDate = LocaleController.getInstance().getFormatterGiveawayMonthDay().format(new Date(giveaway.until_date * 1000L)); - String fromTime = LocaleController.getInstance().formatterDay.format(new Date(giveawayInfo.start_date * 1000L)); - String fromDate = LocaleController.getInstance().formatterGiveawayMonthDayYear.format(new Date(giveawayInfo.start_date * 1000L)); + String fromTime = LocaleController.getInstance().getFormatterDay().format(new Date(giveawayInfo.start_date * 1000L)); + String fromDate = LocaleController.getInstance().getFormatterGiveawayMonthDayYear().format(new Date(giveawayInfo.start_date * 1000L)); boolean isSeveralChats = giveaway.channels.size() > 1; AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider); builder.setTitle(getString("BoostingGiveawayEnd", R.string.BoostingGiveawayEnd)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/adapters/GiftInfoAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/adapters/GiftInfoAdapter.java index 081079743a..e662ae645a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/adapters/GiftInfoAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/adapters/GiftInfoAdapter.java @@ -190,8 +190,8 @@ public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int positi cell.setText(text); } else { Date date = new Date(giftCode.used_date * 1000L); - String monthTxt = LocaleController.getInstance().formatterYear.format(date); - String timeTxt = LocaleController.getInstance().formatterDay.format(date); + String monthTxt = LocaleController.getInstance().getFormatterYear().format(date); + String timeTxt = LocaleController.getInstance().getFormatterDay().format(date); String fullDateStr = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, monthTxt, timeTxt); cell.setText(LocaleController.formatString("BoostingUsedLinkDate", R.string.BoostingUsedLinkDate, fullDateStr)); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/DateEndCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/DateEndCell.java index 0b6c696951..86d106c21d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/DateEndCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/DateEndCell.java @@ -49,8 +49,8 @@ public DateEndCell(@NonNull Context context, Theme.ResourcesProvider resourcesPr public void setDate(long time) { selectedTime = time; Date date = new Date(time); - String monthTxt = LocaleController.getInstance().formatterDayMonth.format(date); - String timeTxt = LocaleController.getInstance().formatterDay.format(date); + String monthTxt = LocaleController.getInstance().getFormatterDayMonth().format(date); + String timeTxt = LocaleController.getInstance().getFormatterDay().format(date); timeTextView.setText(LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, monthTxt, timeTxt)); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/TableCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/TableCell.java index 45e44d62ee..57726ee91a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/TableCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/TableCell.java @@ -203,8 +203,8 @@ public void getOutline(View view, Outline outline) { public void setData(TLRPC.TL_payments_checkedGiftCode giftCode, Utilities.Callback onObjectClicked) { this.giftCode = giftCode; Date date = new Date(giftCode.date * 1000L); - String monthTxt = LocaleController.getInstance().formatterYear.format(date); - String timeTxt = LocaleController.getInstance().formatterDay.format(date); + String monthTxt = LocaleController.getInstance().getFormatterYear().format(date); + String timeTxt = LocaleController.getInstance().getFormatterDay().format(date); dateTextView.setText(LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, monthTxt, timeTxt)); reasonTextView.setTextColor(Theme.getColor(giftCode.via_giveaway ? Theme.key_dialogTextBlue : Theme.key_dialogTextBlack, resourcesProvider)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/msg/GiveawayMessageCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/msg/GiveawayMessageCell.java index 1e39f7ec65..a86d601cdc 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/msg/GiveawayMessageCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/msg/GiveawayMessageCell.java @@ -311,8 +311,8 @@ public void setMessageContent(MessageObject messageObject, int parentWidth, int SpannableStringBuilder bottomStringBuilder = new SpannableStringBuilder(dateTitle); bottomStringBuilder.setSpan(new RelativeSizeSpan(1.05f), 0, dateTitle.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); Date date = new Date(giveaway.until_date * 1000L); - String monthTxt = LocaleController.getInstance().formatterGiveawayCard.format(date); - String timeTxt = LocaleController.getInstance().formatterDay.format(date); + String monthTxt = LocaleController.getInstance().getFormatterGiveawayCard().format(date); + String timeTxt = LocaleController.getInstance().getFormatterDay().format(date); bottomStringBuilder.append("\n"); bottomStringBuilder.append(formatString("formatDateAtTime", R.string.formatDateAtTime, monthTxt, timeTxt)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/selector/SelectorUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/selector/SelectorUserCell.java index 8fee73d247..c6dc58f115 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/selector/SelectorUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/selector/SelectorUserCell.java @@ -168,7 +168,7 @@ public void setBoost(TL_stories.TL_myBoost boost) { titleTextView.setText(chat.title); subtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogTextGray3, resourcesProvider)); - setSubtitle(LocaleController.formatString("BoostExpireOn", R.string.BoostExpireOn, LocaleController.getInstance().formatterBoostExpired.format(new Date(boost.expires * 1000L)))); + setSubtitle(LocaleController.formatString("BoostExpireOn", R.string.BoostExpireOn, LocaleController.getInstance().getFormatterBoostExpired().format(new Date(boost.expires * 1000L)))); if (boost.cooldown_until_date > 0) { long diff = boost.cooldown_until_date * 1000L - System.currentTimeMillis(); @@ -191,7 +191,7 @@ public void updateTimer() { subtitleTextView.setAlpha(0.65f); setCheckboxAlpha(0.3f, false); } else { - setSubtitle(LocaleController.formatString("BoostExpireOn", R.string.BoostExpireOn, LocaleController.getInstance().formatterBoostExpired.format(new Date(boost.expires * 1000L)))); + setSubtitle(LocaleController.formatString("BoostExpireOn", R.string.BoostExpireOn, LocaleController.getInstance().getFormatterBoostExpired().format(new Date(boost.expires * 1000L)))); if (titleTextView.getAlpha() < 1f) { titleTextView.animate().alpha(1f).start(); subtitleTextView.animate().alpha(1f).start(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/statistics/GiftedUserCell.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/statistics/GiftedUserCell.java index 0acb344187..e86017c62f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/statistics/GiftedUserCell.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/Premium/boosts/cells/statistics/GiftedUserCell.java @@ -105,8 +105,8 @@ public void setStatus(TL_stories.TL_boost boost) { avatarImageView.setForUserOrChat(null, avatarDrawable); nameTextView.setRightDrawable(null); } - String date = LocaleController.getInstance().formatterScheduleDay.format(new Date(boost.expires * 1000L)); - String time = LocaleController.getInstance().formatterDay.format(new Date(boost.expires * 1000L)); + String date = LocaleController.getInstance().getFormatterScheduleDay().format(new Date(boost.expires * 1000L)); + String time = LocaleController.getInstance().getFormatterDay().format(new Date(boost.expires * 1000L)); statusTextView.setText(LocaleController.formatString("BoostingShortMonths", R.string.BoostingShortMonths, months) + " • " + LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, date, time)); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java index 729a0a61de..46cc8c4b94 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/RecyclerListView.java @@ -1963,7 +1963,7 @@ public void setEmptyView(View view) { } } else { emptyViewAnimateToVisibility = -1; - checkIfEmpty(updateEmptyViewAnimated()); + checkIfEmpty(false); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrimOptions.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrimOptions.java index f9ea7ab055..fcc4bd4266 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrimOptions.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ScrimOptions.java @@ -441,7 +441,7 @@ public void setScrim(ChatMessageCell cell, CharacterStyle link, CharSequence rep r = Math.max(r, layout.getLineRight(i)); } - x += Math.min(xoffset, xwidth - Math.max(0, r - l)); + x += Math.max(0, Math.min(xoffset, xwidth - Math.max(0, r - l))); } final Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/ThanosEffect.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/ThanosEffect.java index 9bc8494127..d4e202c331 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/ThanosEffect.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/ThanosEffect.java @@ -194,6 +194,11 @@ public void kill() { if (drawThread != null) { drawThread.kill(); } + if (whenDone != null) { + Runnable runnable = whenDone; + whenDone = null; + runnable.run(); + } } public void scroll(int dx, int dy) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/UItem.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/UItem.java index ecb4140962..3d8400feb7 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/UItem.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/UItem.java @@ -59,11 +59,19 @@ public class UItem extends AdapterWithDiffUtils.Item { public boolean withUsername = true; - public UItem(int viewType, boolean selectable) { super(viewType, selectable); } + public UItem(int viewType) { + super(viewType, false); + } + + public UItem(int viewType, Object object) { + super(viewType, false); + this.object = object; + } + public static UItem asCustom(int id, View view) { UItem i = new UItem(UniversalAdapter.VIEW_TYPE_CUSTOM, false); i.id = id; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DataUsage2Activity.java b/TMessagesProj/src/main/java/org/telegram/ui/DataUsage2Activity.java index eaa7b4326a..ce4c7f9408 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DataUsage2Activity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DataUsage2Activity.java @@ -346,8 +346,8 @@ private void updateRows(boolean animated) { itemInners.add(new ItemInner(VIEW_TYPE_CHART)); final String sinceText = totalSize > 0 ? - LocaleController.formatString("YourNetworkUsageSince", R.string.YourNetworkUsageSince, LocaleController.getInstance().formatterStats.format(getResetStatsDate())) : - LocaleController.formatString("NoNetworkUsageSince", R.string.NoNetworkUsageSince, LocaleController.getInstance().formatterStats.format(getResetStatsDate())); + LocaleController.formatString("YourNetworkUsageSince", R.string.YourNetworkUsageSince, LocaleController.getInstance().getFormatterStats().format(getResetStatsDate())) : + LocaleController.formatString("NoNetworkUsageSince", R.string.NoNetworkUsageSince, LocaleController.getInstance().getFormatterStats().format(getResetStatsDate())); itemInners.add(ItemInner.asSubtitle(sinceText)); ArrayList sections = new ArrayList<>(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java index a9c2c9d536..c4c8aca787 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DataUsageActivity.java @@ -807,7 +807,7 @@ public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { case 3: { TextInfoPrivacyCell cell = (TextInfoPrivacyCell) holder.itemView; cell.setBackground(Theme.getThemedDrawableByKey(mContext, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow)); - cell.setText(LocaleController.formatString("NetworkUsageSince", R.string.NetworkUsageSince, LocaleController.getInstance().formatterStats.format(StatsController.getInstance(currentAccount).getResetStatsDate(currentType)))); + cell.setText(LocaleController.formatString("NetworkUsageSince", R.string.NetworkUsageSince, LocaleController.getInstance().getFormatterStats().format(StatsController.getInstance(currentAccount).getResetStatsDate(currentType)))); break; } default: diff --git a/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java index a0494f8f1c..302d98a32f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/DialogsActivity.java @@ -433,6 +433,8 @@ public void updateList(boolean animated) { private FilterTabsView filterTabsView; private boolean askingForPermissions; private RLottieDrawable passcodeDrawable; + private int searchViewPagerIndex; + @Nullable private SearchViewPager searchViewPager; private SharedMediaLayout.SharedMediaPreloader sharedMediaPreloader; public DialogStoriesCell dialogStoriesCell; @@ -473,17 +475,28 @@ public void updateList(boolean animated) { private Paint actionBarDefaultPaint = new Paint(); private NumberTextView selectedDialogsCountTextView; - private ArrayList actionModeViews = new ArrayList<>(); + private final ArrayList actionModeViews = new ArrayList<>(); + @Nullable private ActionBarMenuItem deleteItem; + @Nullable private ActionBarMenuItem pinItem; + @Nullable private ActionBarMenuItem muteItem; + @Nullable private ActionBarMenuItem archive2Item; + @Nullable private ActionBarMenuSubItem pin2Item; + @Nullable private ActionBarMenuSubItem addToFolderItem; + @Nullable private ActionBarMenuSubItem removeFromFolderItem; + @Nullable private ActionBarMenuSubItem archiveItem; + @Nullable private ActionBarMenuSubItem clearItem; + @Nullable private ActionBarMenuSubItem readItem; + @Nullable private ActionBarMenuSubItem blockItem; private float additionalFloatingTranslation; @@ -1112,7 +1125,9 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { topBulletin.updatePosition(); } } - searchViewPager.setTranslationY(searchViewPagerTranslationY); + if (searchViewPager != null) { + searchViewPager.setTranslationY(searchViewPagerTranslationY); + } } } @@ -1310,7 +1325,9 @@ protected void onLayout(boolean changed, int l, int t, int r, int b) { child.layout(childLeft, childTop, childLeft + width, childTop + height); } - searchViewPager.setKeyboardHeight(keyboardSize); + if (searchViewPager != null) { + searchViewPager.setKeyboardHeight(keyboardSize); + } notifyHeightChanged(); updateContextViewPosition(); updateCommentView(); @@ -3116,7 +3133,7 @@ public void onPreToggleSearch() { searchContainer.addView(speedItem, speedParams); searchItem.setSearchAdditionalButton(speedItem); - updateSpeedItem(searchViewPager.getCurrentPosition() == 2); + updateSpeedItem(searchViewPager != null && searchViewPager.getCurrentPosition() == 2); } } @@ -3226,13 +3243,15 @@ public void onSearchCollapse() { @Override public void onTextChanged(EditText editText) { String text = editText.getText().toString(); - if (text.length() != 0 || (searchViewPager.dialogsSearchAdapter != null && searchViewPager.dialogsSearchAdapter.hasRecentSearch()) || searchFiltersWasShowed || hasStories) { + if (text.length() != 0 || (searchViewPager != null && searchViewPager.dialogsSearchAdapter != null && searchViewPager.dialogsSearchAdapter.hasRecentSearch()) || searchFiltersWasShowed || hasStories) { searchWas = true; if (!searchIsShowed) { showSearch(true, false, true); } } - searchViewPager.onTextChanged(text); + if (searchViewPager != null) { + searchViewPager.onTextChanged(text); + } } @Override @@ -3240,8 +3259,10 @@ public void onSearchFilterCleared(FiltersView.MediaFilterData filterData) { if (!searchIsShowed) { return; } - searchViewPager.removeSearchFilter(filterData); - searchViewPager.onTextChanged(searchItem.getSearchField().getText().toString()); + if (searchViewPager != null) { + searchViewPager.removeSearchFilter(filterData); + searchViewPager.onTextChanged(searchItem.getSearchField().getText().toString()); + } updateFiltersView(true, null, null, false, true); } @@ -3703,7 +3724,194 @@ public void onDeletePressed(int id) { sideMenu.getAdapter().notifyDataSetChanged(); } - createActionMode(null); +// createActionMode(null); + + actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { + @Override + public void onItemClick(int id) { + if ((id == SearchViewPager.forwardItemId || id == SearchViewPager.gotoItemId || id == SearchViewPager.deleteItemId || id == SearchViewPager.speedItemId) && searchViewPager != null) { + searchViewPager.onActionBarItemClick(id); + return; + } + if (id == -1) { + if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.hasFragment()) { + if (actionBar.isActionModeShowed()) { + if (searchViewPager != null && searchViewPager.getVisibility() == View.VISIBLE && searchViewPager.actionModeShowing()) { + searchViewPager.hideActionMode(); + } else { + hideActionMode(true); + } + } else { + rightSlidingDialogContainer.finishPreview(); + searchViewPager.updateTabs(); + return; + } + } else if (filterTabsView != null && filterTabsView.isEditing()) { + filterTabsView.setIsEditing(false); + showDoneItem(false); + } else if (actionBar.isActionModeShowed()) { + if (searchViewPager != null && searchViewPager.getVisibility() == View.VISIBLE && searchViewPager.actionModeShowing()) { + searchViewPager.hideActionMode(); + } else { + hideActionMode(true); + } + } else if (onlySelect || folderId != 0) { + finishFragment(); + } else if (parentLayout != null && parentLayout.getDrawerLayoutContainer() != null) { + parentLayout.getDrawerLayoutContainer().openDrawer(false); + } + } else if (id == 1) { + if (getParentActivity() == null) { + return; + } + SharedConfig.appLocked = true; + SharedConfig.saveConfig(); + int[] position = new int[2]; + passcodeItem.getLocationInWindow(position); + ((LaunchActivity) getParentActivity()).showPasscodeActivity(false, true, position[0] + passcodeItem.getMeasuredWidth() / 2, position[1] + passcodeItem.getMeasuredHeight() / 2, () -> passcodeItem.setAlpha(1.0f), () -> passcodeItem.setAlpha(0.0f)); + getNotificationsController().showNotifications(); + updatePasscodeButton(); + } else if (id == 2) { + presentFragment(new ProxyListActivity()); + } else if (id == 3) { + showSearch(true, true, true); + actionBar.openSearchField(true); + } else if (id == 5) { + presentFragment(new ArchiveSettingsActivity()); + } else if (id == 6) { + showArchiveHelp(); + } else if (id == nekox_scanqr) { + if (Build.VERSION.SDK_INT >= 23) { + if (getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { + getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, 22); + return; + } + } + CameraScanActivity.showAsSheet(DialogsActivity.this, true, CameraScanActivity.TYPE_QR, new CameraScanActivity.CameraScanActivityDelegate() { + + @Override + public void didFindQr(String text) { + ProxyUtil.showLinkAlert(getParentActivity(), text); + } + + @Override + public boolean processQr(String text, Runnable onLoadEnd) { + onLoadEnd.run(); + return false; + } + }); + } else if (id >= 10 && id < 10 + accounts) { + if (getParentActivity() == null) { + return; + } + DialogsActivityDelegate oldDelegate = delegate; + LaunchActivity launchActivity = (LaunchActivity) getParentActivity(); + launchActivity.switchToAccount(id - 10, true); + + DialogsActivity dialogsActivity = new DialogsActivity(arguments); + dialogsActivity.setDelegate(oldDelegate); + launchActivity.presentFragment(dialogsActivity, false, true); + } else if (id == add_to_folder) { + FiltersListBottomSheet sheet = new FiltersListBottomSheet(DialogsActivity.this, selectedDialogs); + sheet.setDelegate((filter, checked) -> { + ArrayList alwaysShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, true, false); + if (!checked) { + int currentCount; + if (filter != null) { + currentCount = filter.alwaysShow.size(); + } else { + currentCount = 0; + } + int totalCount = currentCount + alwaysShow.size(); + if ((totalCount > getMessagesController().dialogFiltersChatsLimitDefault && !getUserConfig().isPremium()) || totalCount > getMessagesController().dialogFiltersChatsLimitPremium) { + showDialog(new LimitReachedBottomSheet(DialogsActivity.this, fragmentView.getContext(), LimitReachedBottomSheet.TYPE_CHATS_IN_FOLDER, currentAccount, null)); + return; + } + } + if (filter != null) { + if (checked) { + for (int a = 0; a < selectedDialogs.size(); a++) { + filter.neverShow.add(selectedDialogs.get(a)); + filter.alwaysShow.remove(selectedDialogs.get(a)); + } + FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, true, false, DialogsActivity.this, null); + long did; + if (selectedDialogs.size() == 1) { + did = selectedDialogs.get(0); + } else { + did = 0; + } + final UndoView undoView = getUndoView(); + if (undoView != null) { + undoView.showWithAction(did, UndoView.ACTION_REMOVED_FROM_FOLDER, selectedDialogs.size(), filter, null, null); + } + } else { + if (!alwaysShow.isEmpty()) { + for (int a = 0; a < alwaysShow.size(); a++) { + filter.neverShow.remove(alwaysShow.get(a)); + } + filter.alwaysShow.addAll(alwaysShow); + FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, true, false, DialogsActivity.this, null); + } + long did; + if (alwaysShow.size() == 1) { + did = alwaysShow.get(0); + } else { + did = 0; + } + final UndoView undoView = getUndoView(); + if (undoView != null) { + undoView.showWithAction(did, UndoView.ACTION_ADDED_TO_FOLDER, alwaysShow.size(), filter, null, null); + } + } + } else { + presentFragment(new FilterCreateActivity(null, alwaysShow)); + } + hideActionMode(true); + }); + showDialog(sheet); + } else if (id == remove_from_folder) { + MessagesController.DialogFilter filter = getMessagesController().getDialogFilters().get(viewPages[0].selectedType); + ArrayList neverShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, false, false); + + int currentCount; + if (filter != null) { + currentCount = filter.neverShow.size(); + } else { + currentCount = 0; + } + if (currentCount + neverShow.size() > 100) { + showDialog(AlertsCreator.createSimpleAlert(getParentActivity(), LocaleController.getString("FilterAddToAlertFullTitle", R.string.FilterAddToAlertFullTitle), LocaleController.getString("FilterAddToAlertFullText", R.string.FilterAddToAlertFullText)).create()); + return; + } + if (!neverShow.isEmpty()) { + filter.neverShow.addAll(neverShow); + for (int a = 0; a < neverShow.size(); a++) { + Long did = neverShow.get(a); + filter.alwaysShow.remove(did); + filter.pinnedDialogs.delete(did); + } + if (filter.isChatlist()) { + filter.neverShow.clear(); + } + FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, false, false, DialogsActivity.this, null); + } + long did; + if (neverShow.size() == 1) { + did = neverShow.get(0); + } else { + did = 0; + } + final UndoView undoView = getUndoView(); + if (undoView != null) { + undoView.showWithAction(did, UndoView.ACTION_REMOVED_FROM_FOLDER, neverShow.size(), filter, null, null); + } + hideActionMode(false); + } else if (id == pin || id == read || id == delete || id == clear || id == mute || id == archive || id == block || id == archive2 || id == pin2) { + performSelectedDialogsAction(selectedDialogs, id, true, false); + } + } + }); ContentView contentView = new ContentView(context); fragmentView = contentView; @@ -4347,340 +4555,84 @@ public void onScroll() { } } - int type = 0; - if (searchString != null) { - type = 2; - } else if (!onlySelect) { - type = 1; - } - searchViewPager = new SearchViewPager(context, this, type, initialDialogsType, folderId, new SearchViewPager.ChatPreviewDelegate() { - @Override - public void startChatPreview(RecyclerListView listView, DialogCell cell) { - showChatPreview(cell); - } + searchViewPagerIndex = contentView.getChildCount(); - @Override - public void move(float dy) { - if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { - movePreviewFragment(dy); - } - } + filtersView = new FiltersView(getParentActivity(), null); + filtersView.setOnItemClickListener((view, position) -> { + filtersView.cancelClickRunnables(true); + addSearchFilter(filtersView.getFilterAt(position)); + }); + contentView.addView(filtersView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP)); + filtersView.setVisibility(View.GONE); - @Override - public void finish() { - if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { + if (initialDialogsType != DIALOGS_TYPE_WIDGET) { + floatingButton2Container = new FrameLayout(context); + floatingButton2Container.setVisibility(onlySelect && initialDialogsType != 10 || folderId != 0 || !storiesEnabled ? View.GONE : View.VISIBLE); + contentView.addView(floatingButton2Container, LayoutHelper.createFrame((Build.VERSION.SDK_INT >= 21 ? 36 : 40), (Build.VERSION.SDK_INT >= 21 ? 36 : 40), (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 24 : 0, 0, LocaleController.isRTL ? 0 : 24, 14 + 60 + 8)); + floatingButton2Container.setOnClickListener(v -> { + if (parentLayout != null && parentLayout.isInPreviewMode()) { finishPreviewFragment(); + return; } - } - }) { - @Override - protected void onTabPageSelected(int position) { - updateSpeedItem(position == 2); - } - @Override - protected long getDialogId(String query) { - if (query != null && query.length() > 0 && rightSlidingDialogContainer != null && rightSlidingDialogContainer.getFragment() instanceof TopicsFragment) { - return ((TopicsFragment) rightSlidingDialogContainer.getFragment()).getDialogId(); - } - return 0; + Bundle args = new Bundle(); + args.putBoolean("destroyAfterSelect", true); + presentFragment(new ContactsActivity(args)); + }); + if (Build.VERSION.SDK_INT >= 21) { + StateListAnimator animator = new StateListAnimator(); + animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(floatingButton2Container, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); + animator.addState(new int[]{}, ObjectAnimator.ofFloat(floatingButton2Container, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); + floatingButton2Container.setStateListAnimator(animator); + floatingButton2Container.setOutlineProvider(new ViewOutlineProvider() { + @SuppressLint("NewApi") + @Override + public void getOutline(View view, Outline outline) { + outline.setOval(0, 0, dp(36), dp(36)); + } + }); } - @Override - protected boolean onBackProgress(float progress) { - return false; -// setSearchAnimationProgress(1f - progress, true); -// return true; - } + floatingButton2 = new RLottieImageView(context); + floatingButton2.setScaleType(ImageView.ScaleType.CENTER); + floatingButton2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY)); + floatingButton2.setImageResource(R.drawable.fab_compose_small); + floatingButton2Container.setContentDescription(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle)); + floatingButton2Container.addView(floatingButton2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); -// @Override -// protected void onBack() { -// actionBar.onSearchFieldVisibilityChanged(searchItem.toggleSearch(false)); -// } + floating2ProgressView = new RadialProgressView(context); + floating2ProgressView.setProgressColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon)); + floating2ProgressView.setScaleX(0.1f); + floating2ProgressView.setScaleY(0.1f); + floating2ProgressView.setAlpha(0f); + floating2ProgressView.setVisibility(View.GONE); + floating2ProgressView.setSize(dp(22)); + floatingButton2Container.addView(floating2ProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); + } - @Override - protected boolean includeDownloads() { - if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.hasFragment()) { - return false; - } - return true; + floatingButtonContainer = new FrameLayout(context); + floatingButtonContainer.setVisibility(onlySelect && initialDialogsType != 10 || folderId != 0 ? View.GONE : View.VISIBLE); + contentView.addView(floatingButtonContainer, 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)); + floatingButtonContainer.setOnClickListener(v -> { + if (parentLayout != null && parentLayout.isInPreviewMode()) { + finishPreviewFragment(); + return; } - }; - contentView.addView(searchViewPager); - - searchViewPager.dialogsSearchAdapter.setDelegate(new DialogsSearchAdapter.DialogsSearchAdapterDelegate() { - @Override - public void searchStateChanged(boolean search, boolean animated) { - if (searchViewPager.emptyView.getVisibility() == View.VISIBLE) { - animated = true; + if (initialDialogsType == DIALOGS_TYPE_WIDGET) { + if (delegate == null || selectedDialogs.isEmpty()) { + return; } - if (searching && searchWas && searchViewPager.emptyView != null) { - if (search || searchViewPager.dialogsSearchAdapter.getItemCount() != 0) { - searchViewPager.emptyView.showProgress(true, animated); - } else { - searchViewPager.emptyView.showProgress(false, animated); - } + ArrayList topicKeys = new ArrayList<>(); + for (int i = 0; i < selectedDialogs.size(); i++) { + topicKeys.add(MessagesStorage.TopicKey.of(selectedDialogs.get(i), 0)); } - if (search && searchViewPager.dialogsSearchAdapter.getItemCount() == 0) { - searchViewPager.cancelEnterAnimation(); + delegate.didSelectDialogs(DialogsActivity.this, topicKeys, null, false, null); + } else { + if (floatingButton.getVisibility() != View.VISIBLE) { + return; } - } - - @Override - public void didPressedBlockedDialog(View view, long did) { - showPremiumBlockedToast(view, did); - } - @Override - public void didPressedOnSubDialog(long did) { - if (onlySelect) { - if (!validateSlowModeDialog(did)) { - return; - } - if (!selectedDialogs.isEmpty()) { - boolean checked = addOrRemoveSelectedDialog(did, null); - findAndUpdateCheckBox(did, checked); - updateSelectedCount(); - actionBar.closeSearchField(); - } else { - didSelectResult(did, 0, true, false); - } - } else { - Bundle args = new Bundle(); - if (DialogObject.isUserDialog(did)) { - args.putLong("user_id", did); - } else { - args.putLong("chat_id", -did); - } - closeSearch(); - if (AndroidUtilities.isTablet() && viewPages != null) { - for (int a = 0; a < viewPages.length; a++) { - viewPages[a].dialogsAdapter.setOpenedDialogId(openedDialogId.dialogId = did); - } - updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG); - } - if (searchString != null) { - if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) { - getNotificationCenter().postNotificationName(NotificationCenter.closeChats); - presentFragment(new ChatActivity(args)); - } - } else { - if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) { - presentFragment(new ChatActivity(args)); - } - } - } - } - - @Override - public void needRemoveHint(long did) { - if (getParentActivity() == null) { - return; - } - TLRPC.User user = getMessagesController().getUser(did); - if (user == null) { - return; - } - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - builder.setTitle(LocaleController.getString("ChatHintsDeleteAlertTitle", R.string.ChatHintsDeleteAlertTitle)); - builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("ChatHintsDeleteAlert", R.string.ChatHintsDeleteAlert, ContactsController.formatName(user.first_name, user.last_name)))); - builder.setPositiveButton(LocaleController.getString("StickersRemove", R.string.StickersRemove), (dialogInterface, i) -> getMediaDataController().removePeer(did)); - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - AlertDialog dialog = builder.create(); - showDialog(dialog); - TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); - if (button != null) { - button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); - } - } - - @Override - public void needClearList() { - AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); - if (searchViewPager.dialogsSearchAdapter.isSearchWas() && searchViewPager.dialogsSearchAdapter.isRecentSearchDisplayed()) { - builder.setTitle(LocaleController.getString("ClearSearchAlertPartialTitle", R.string.ClearSearchAlertPartialTitle)); - builder.setMessage(LocaleController.formatPluralString("ClearSearchAlertPartial", searchViewPager.dialogsSearchAdapter.getRecentResultsCount())); - builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (dialogInterface, i) -> { - searchViewPager.dialogsSearchAdapter.clearRecentSearch(); - }); - } else { - builder.setTitle(LocaleController.getString("ClearSearchAlertTitle", R.string.ClearSearchAlertTitle)); - builder.setMessage(LocaleController.getString("ClearSearchAlert", R.string.ClearSearchAlert)); - builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton), (dialogInterface, i) -> { - if (searchViewPager.dialogsSearchAdapter.isRecentSearchDisplayed()) { - searchViewPager.dialogsSearchAdapter.clearRecentSearch(); - } else { - searchViewPager.dialogsSearchAdapter.clearRecentHashtags(); - } - }); - } - builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); - AlertDialog dialog = builder.create(); - showDialog(dialog); - TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); - if (button != null) { - button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); - } - } - - @Override - public void runResultsEnterAnimation() { - if (searchViewPager != null) { - searchViewPager.runResultsEnterAnimation(); - } - } - - @Override - public boolean isSelected(long dialogId) { - return selectedDialogs.contains(dialogId); - } - - @Override - public long getSearchForumDialogId() { - if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.getFragment() instanceof TopicsFragment) { - return ((TopicsFragment) rightSlidingDialogContainer.getFragment()).getDialogId(); - } - return 0; - } - }); - - searchViewPager.channelsSearchListView.setOnItemClickListener((view, position, x, y) -> { - Object obj = searchViewPager.channelsSearchAdapter.getObject(position); - if (obj instanceof TLRPC.Chat) { - Bundle args = new Bundle(); - args.putLong("chat_id", ((TLRPC.Chat) obj).id); - ChatActivity chatActivity = new ChatActivity(args); - chatActivity.setNextChannels(searchViewPager.channelsSearchAdapter.getNextChannels(position)); - presentFragment(chatActivity); - } else if (obj instanceof MessageObject) { - MessageObject msg = (MessageObject) obj; - Bundle args = new Bundle(); - if (msg.getDialogId() >= 0) { - args.putLong("user_id", msg.getDialogId()); - } else { - args.putLong("chat_id", -msg.getDialogId()); - } - args.putInt("message_id", msg.getId()); - ChatActivity chatActivity = new ChatActivity(args); - presentFragment(highlightFoundQuote(chatActivity, msg)); - } - }); - - searchViewPager.searchListView.setOnItemClickListener((view, position, x, y) -> { - if (view instanceof ProfileSearchCell && ((ProfileSearchCell) view).isBlocked()) { - showPremiumBlockedToast(view, ((ProfileSearchCell) view).getDialogId()); - return; - } - if (initialDialogsType == DIALOGS_TYPE_WIDGET) { - onItemLongClick(searchViewPager.searchListView, view, position, x, y, -1, searchViewPager.dialogsSearchAdapter); - return; - } - onItemClick(view, position, searchViewPager.dialogsSearchAdapter, x, y); - }); - searchViewPager.searchListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListenerExtended() { - @Override - public boolean onItemClick(View view, int position, float x, float y) { - if (view instanceof ProfileSearchCell && ((ProfileSearchCell) view).isBlocked()) { - showPremiumBlockedToast(view, ((ProfileSearchCell) view).getDialogId()); - return true; - } - return onItemLongClick(searchViewPager.searchListView, view, position, x, y, -1, searchViewPager.dialogsSearchAdapter); - } - - @Override - public void onMove(float dx, float dy) { - if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { - movePreviewFragment(dy); - } - } - - @Override - public void onLongClickRelease() { - if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { - finishPreviewFragment(); - } - } - }); - - searchViewPager.setFilteredSearchViewDelegate((showMediaFilters, users, dates, archive) -> DialogsActivity.this.updateFiltersView(showMediaFilters, users, dates, archive, true)); - searchViewPager.setVisibility(View.GONE); - - filtersView = new FiltersView(getParentActivity(), null); - filtersView.setOnItemClickListener((view, position) -> { - filtersView.cancelClickRunnables(true); - addSearchFilter(filtersView.getFilterAt(position)); - }); - contentView.addView(filtersView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP)); - filtersView.setVisibility(View.GONE); - - if (initialDialogsType != DIALOGS_TYPE_WIDGET) { - floatingButton2Container = new FrameLayout(context); - floatingButton2Container.setVisibility(onlySelect && initialDialogsType != 10 || folderId != 0 || !storiesEnabled ? View.GONE : View.VISIBLE); - contentView.addView(floatingButton2Container, LayoutHelper.createFrame((Build.VERSION.SDK_INT >= 21 ? 36 : 40), (Build.VERSION.SDK_INT >= 21 ? 36 : 40), (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 24 : 0, 0, LocaleController.isRTL ? 0 : 24, 14 + 60 + 8)); - floatingButton2Container.setOnClickListener(v -> { - if (parentLayout != null && parentLayout.isInPreviewMode()) { - finishPreviewFragment(); - return; - } - - Bundle args = new Bundle(); - args.putBoolean("destroyAfterSelect", true); - presentFragment(new ContactsActivity(args)); - }); - if (Build.VERSION.SDK_INT >= 21) { - StateListAnimator animator = new StateListAnimator(); - animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(floatingButton2Container, View.TRANSLATION_Z, dp(2), dp(4)).setDuration(200)); - animator.addState(new int[]{}, ObjectAnimator.ofFloat(floatingButton2Container, View.TRANSLATION_Z, dp(4), dp(2)).setDuration(200)); - floatingButton2Container.setStateListAnimator(animator); - floatingButton2Container.setOutlineProvider(new ViewOutlineProvider() { - @SuppressLint("NewApi") - @Override - public void getOutline(View view, Outline outline) { - outline.setOval(0, 0, dp(36), dp(36)); - } - }); - } - - floatingButton2 = new RLottieImageView(context); - floatingButton2.setScaleType(ImageView.ScaleType.CENTER); - floatingButton2.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY)); - floatingButton2.setImageResource(R.drawable.fab_compose_small); - floatingButton2Container.setContentDescription(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle)); - floatingButton2Container.addView(floatingButton2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - - floating2ProgressView = new RadialProgressView(context); - floating2ProgressView.setProgressColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon)); - floating2ProgressView.setScaleX(0.1f); - floating2ProgressView.setScaleY(0.1f); - floating2ProgressView.setAlpha(0f); - floating2ProgressView.setVisibility(View.GONE); - floating2ProgressView.setSize(dp(22)); - floatingButton2Container.addView(floating2ProgressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); - } - - floatingButtonContainer = new FrameLayout(context); - floatingButtonContainer.setVisibility(onlySelect && initialDialogsType != 10 || folderId != 0 ? View.GONE : View.VISIBLE); - contentView.addView(floatingButtonContainer, 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)); - floatingButtonContainer.setOnClickListener(v -> { - if (parentLayout != null && parentLayout.isInPreviewMode()) { - finishPreviewFragment(); - return; - } - if (initialDialogsType == DIALOGS_TYPE_WIDGET) { - if (delegate == null || selectedDialogs.isEmpty()) { - return; - } - ArrayList topicKeys = new ArrayList<>(); - for (int i = 0; i < selectedDialogs.size(); i++) { - topicKeys.add(MessagesStorage.TopicKey.of(selectedDialogs.get(i), 0)); - } - delegate.didSelectDialogs(DialogsActivity.this, topicKeys, null, false, null); - } else { - if (floatingButton.getVisibility() != View.VISIBLE) { - return; - } - - if (!storiesEnabled) { + if (!storiesEnabled) { Bundle args = new Bundle(); args.putBoolean("destroyAfterSelect", true); presentFragment(new ContactsActivity(args)); @@ -5454,7 +5406,9 @@ public void openAnimationFinished(boolean backward) { fixScrollYAfterArchiveOpened = true; fragmentView.invalidate(); } - searchViewPager.updateTabs(); + if (searchViewPager != null) { + searchViewPager.updateTabs(); + } updateDrawerSwipeEnabled(); updateFilterTabs(false, true); } @@ -6407,7 +6361,7 @@ private void updateContextViewPosition() { } private void updateFiltersView(boolean showMediaFilters, ArrayList users, ArrayList dates, boolean archive, boolean animated) { - if (!searchIsShowed || onlySelect && initialDialogsType != DIALOGS_TYPE_FORWARD) { + if (!searchIsShowed || onlySelect && initialDialogsType != DIALOGS_TYPE_FORWARD || searchViewPager == null) { return; } boolean hasMediaFilter = false; @@ -6459,7 +6413,7 @@ private void updateFiltersView(boolean showMediaFilters, ArrayList users } private void addSearchFilter(FiltersView.MediaFilterData filter) { - if (!searchIsShowed) { + if (!searchIsShowed || searchViewPager == null) { return; } ArrayList currentSearchFilters = searchViewPager.getCurrentSearchFilters(); @@ -6591,195 +6545,8 @@ private void createActionMode(String tag) { actionModeViews.add(deleteItem); actionModeViews.add(otherItem); - if (tag == null) { - actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { - @Override - public void onItemClick(int id) { - if ((id == SearchViewPager.forwardItemId || id == SearchViewPager.gotoItemId || id == SearchViewPager.deleteItemId || id == SearchViewPager.speedItemId) && searchViewPager != null) { - searchViewPager.onActionBarItemClick(id); - return; - } - if (id == -1) { - if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.hasFragment()) { - if (actionBar.isActionModeShowed()) { - if (searchViewPager != null && searchViewPager.getVisibility() == View.VISIBLE && searchViewPager.actionModeShowing()) { - searchViewPager.hideActionMode(); - } else { - hideActionMode(true); - } - } else { - rightSlidingDialogContainer.finishPreview(); - searchViewPager.updateTabs(); - return; - } - } else if (filterTabsView != null && filterTabsView.isEditing()) { - filterTabsView.setIsEditing(false); - showDoneItem(false); - } else if (actionBar.isActionModeShowed()) { - if (searchViewPager != null && searchViewPager.getVisibility() == View.VISIBLE && searchViewPager.actionModeShowing()) { - searchViewPager.hideActionMode(); - } else { - hideActionMode(true); - } - } else if (onlySelect || folderId != 0) { - finishFragment(); - } else if (parentLayout != null && parentLayout.getDrawerLayoutContainer() != null) { - parentLayout.getDrawerLayoutContainer().openDrawer(false); - } - } else if (id == 1) { - if (getParentActivity() == null) { - return; - } - SharedConfig.appLocked = true; - SharedConfig.saveConfig(); - int[] position = new int[2]; - passcodeItem.getLocationInWindow(position); - ((LaunchActivity) getParentActivity()).showPasscodeActivity(false, true, position[0] + passcodeItem.getMeasuredWidth() / 2, position[1] + passcodeItem.getMeasuredHeight() / 2, () -> passcodeItem.setAlpha(1.0f), () -> passcodeItem.setAlpha(0.0f)); - getNotificationsController().showNotifications(); - updatePasscodeButton(); - } else if (id == 2) { - presentFragment(new ProxyListActivity()); - } else if (id == 3) { - showSearch(true, true, true); - actionBar.openSearchField(true); - } else if (id == 5) { - presentFragment(new ArchiveSettingsActivity()); - } else if (id == 6) { - showArchiveHelp(); - } else if (id == nekox_scanqr) { - if (Build.VERSION.SDK_INT >= 23) { - if (getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { - getParentActivity().requestPermissions(new String[]{Manifest.permission.CAMERA}, 22); - return; - } - } - CameraScanActivity.showAsSheet(DialogsActivity.this, true, CameraScanActivity.TYPE_QR, new CameraScanActivity.CameraScanActivityDelegate() { - - @Override - public void didFindQr(String text) { - ProxyUtil.showLinkAlert(getParentActivity(), text); - } - - @Override - public boolean processQr(String text, Runnable onLoadEnd) { - onLoadEnd.run(); - return false; - } - }); - } else if (id >= 10 && id < 10 + accounts) { - if (getParentActivity() == null) { - return; - } - DialogsActivityDelegate oldDelegate = delegate; - LaunchActivity launchActivity = (LaunchActivity) getParentActivity(); - launchActivity.switchToAccount(id - 10, true); - - DialogsActivity dialogsActivity = new DialogsActivity(arguments); - dialogsActivity.setDelegate(oldDelegate); - launchActivity.presentFragment(dialogsActivity, false, true); - } else if (id == add_to_folder) { - FiltersListBottomSheet sheet = new FiltersListBottomSheet(DialogsActivity.this, selectedDialogs); - sheet.setDelegate((filter, checked) -> { - ArrayList alwaysShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, true, false); - if (!checked) { - int currentCount; - if (filter != null) { - currentCount = filter.alwaysShow.size(); - } else { - currentCount = 0; - } - int totalCount = currentCount + alwaysShow.size(); - if ((totalCount > getMessagesController().dialogFiltersChatsLimitDefault && !getUserConfig().isPremium()) || totalCount > getMessagesController().dialogFiltersChatsLimitPremium) { - showDialog(new LimitReachedBottomSheet(DialogsActivity.this, fragmentView.getContext(), LimitReachedBottomSheet.TYPE_CHATS_IN_FOLDER, currentAccount, null)); - return; - } - } - if (filter != null) { - if (checked) { - for (int a = 0; a < selectedDialogs.size(); a++) { - filter.neverShow.add(selectedDialogs.get(a)); - filter.alwaysShow.remove(selectedDialogs.get(a)); - } - FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, true, false, DialogsActivity.this, null); - long did; - if (selectedDialogs.size() == 1) { - did = selectedDialogs.get(0); - } else { - did = 0; - } - final UndoView undoView = getUndoView(); - if (undoView != null) { - undoView.showWithAction(did, UndoView.ACTION_REMOVED_FROM_FOLDER, selectedDialogs.size(), filter, null, null); - } - } else { - if (!alwaysShow.isEmpty()) { - for (int a = 0; a < alwaysShow.size(); a++) { - filter.neverShow.remove(alwaysShow.get(a)); - } - filter.alwaysShow.addAll(alwaysShow); - FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, true, false, DialogsActivity.this, null); - } - long did; - if (alwaysShow.size() == 1) { - did = alwaysShow.get(0); - } else { - did = 0; - } - final UndoView undoView = getUndoView(); - if (undoView != null) { - undoView.showWithAction(did, UndoView.ACTION_ADDED_TO_FOLDER, alwaysShow.size(), filter, null, null); - } - } - } else { - presentFragment(new FilterCreateActivity(null, alwaysShow)); - } - hideActionMode(true); - }); - showDialog(sheet); - } else if (id == remove_from_folder) { - MessagesController.DialogFilter filter = getMessagesController().getDialogFilters().get(viewPages[0].selectedType); - ArrayList neverShow = FiltersListBottomSheet.getDialogsCount(DialogsActivity.this, filter, selectedDialogs, false, false); - - int currentCount; - if (filter != null) { - currentCount = filter.neverShow.size(); - } else { - currentCount = 0; - } - if (currentCount + neverShow.size() > 100) { - showDialog(AlertsCreator.createSimpleAlert(getParentActivity(), LocaleController.getString("FilterAddToAlertFullTitle", R.string.FilterAddToAlertFullTitle), LocaleController.getString("FilterAddToAlertFullText", R.string.FilterAddToAlertFullText)).create()); - return; - } - if (!neverShow.isEmpty()) { - filter.neverShow.addAll(neverShow); - for (int a = 0; a < neverShow.size(); a++) { - Long did = neverShow.get(a); - filter.alwaysShow.remove(did); - filter.pinnedDialogs.delete(did); - } - if (filter.isChatlist()) { - filter.neverShow.clear(); - } - FilterCreateActivity.saveFilterToServer(filter, filter.flags, filter.emoticon, filter.name, filter.color, filter.alwaysShow, filter.neverShow, filter.pinnedDialogs, false, false, true, false, false, DialogsActivity.this, null); - } - long did; - if (neverShow.size() == 1) { - did = neverShow.get(0); - } else { - did = 0; - } - final UndoView undoView = getUndoView(); - if (undoView != null) { - undoView.showWithAction(did, UndoView.ACTION_REMOVED_FROM_FOLDER, neverShow.size(), filter, null, null); - } - hideActionMode(false); - } else if (id == pin || id == read || id == delete || id == clear || id == mute || id == archive || id == block || id == archive2 || id == pin2) { - performSelectedDialogsAction(selectedDialogs, id, true, false); - } - } - }); - } - } + updateCounters(false); + } public void closeSearching() { if (actionBar != null && actionBar.isSearchFieldVisible()) { @@ -7015,7 +6782,9 @@ protected void onPanTranslationUpdate(float y) { topBulletin.updatePosition(); } } - searchViewPager.setTranslationY(searchViewPagerTranslationY); + if (searchViewPager != null) { + searchViewPager.setTranslationY(searchViewPagerTranslationY); + } } else { for (int a = 0; a < viewPages.length; a++) { viewPages[a].setTranslationY(y); @@ -7026,7 +6795,9 @@ protected void onPanTranslationUpdate(float y) { topBulletin.updatePosition(); } } - searchViewPager.setTranslationY(panTranslationY + searchViewPagerTranslationY); + if (searchViewPager != null) { + searchViewPager.setTranslationY(panTranslationY + searchViewPagerTranslationY); + } } } @@ -7258,7 +7029,9 @@ public boolean onBackPressed() { } else if (rightSlidingDialogContainer.hasFragment()) { if (rightSlidingDialogContainer.getFragment().onBackPressed()) { rightSlidingDialogContainer.finishPreview(); - searchViewPager.updateTabs(); + if (searchViewPager != null) { + searchViewPager.updateTabs(); + } } return false; } else if (filterOptions != null) { @@ -7270,7 +7043,7 @@ public boolean onBackPressed() { showDoneItem(false); return false; } else if (actionBar != null && actionBar.isActionModeShowed()) { - if (searchViewPager.getVisibility() == View.VISIBLE) { + if (searchViewPager != null && searchViewPager.getVisibility() == View.VISIBLE) { searchViewPager.hideActionMode(); hideActionMode(true); } else { @@ -7298,7 +7071,9 @@ public void onBecomeFullyHidden() { actionBar.closeSearchField(); } if (searchObject != null) { - searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + if (searchViewPager != null) { + searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + } searchObject = null; } closeSearchFieldOnHide = false; @@ -7354,6 +7129,7 @@ public void onBecomeFullyVisible() { canShowStoryHint = false; storyHint.show(); } + AndroidUtilities.runOnUIThread(this::createSearchViewPager, 200); } private void showArchiveHelp() { @@ -7446,6 +7222,8 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat private void showSearch(boolean show, boolean startFromDownloads, boolean animated, boolean forceNotOnlyDialogs) { if (!show) { updateSpeedItem(false); + } else { + createSearchViewPager(); } if (initialDialogsType != 0 && initialDialogsType != 3) { animated = false; @@ -7467,13 +7245,15 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat } else { onlyDialogsAdapter = onlyDialogsAdapter(); } - searchViewPager.showOnlyDialogsAdapter(onlyDialogsAdapter); + if (searchViewPager != null) { + searchViewPager.showOnlyDialogsAdapter(onlyDialogsAdapter); + } whiteActionBar = !onlyDialogsAdapter || hasStories; if (whiteActionBar) { searchFiltersWasShowed = true; } ContentView contentView = (ContentView) fragmentView; - if (searchTabsView == null && !onlyDialogsAdapter) { + if (searchTabsView == null && searchViewPager != null && !onlyDialogsAdapter) { searchTabsView = searchViewPager.createTabsView(false, 8); int filtersViewPosition = -1; if (filtersView != null) { @@ -7507,10 +7287,12 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat editText.setHintTextColor(Theme.getColor(Theme.key_actionBarDefaultSearchPlaceholder)); editText.setTextColor(Theme.getColor(Theme.key_actionBarDefaultSearch)); } - searchViewPager.setKeyboardHeight(((ContentView) fragmentView).getKeyboardHeight()); updateDrawerSwipeEnabled(); + if (searchViewPager != null) { + searchViewPager.setKeyboardHeight(((ContentView) fragmentView).getKeyboardHeight()); + searchViewPager.clear(); + } - searchViewPager.clear(); if (folderId != 0 && (rightSlidingDialogContainer == null || !rightSlidingDialogContainer.hasFragment())) { FiltersView.MediaFilterData filterData = new FiltersView.MediaFilterData(R.drawable.chats_archive, R.string.ArchiveSearchFilter, null, FiltersView.FILTER_TYPE_ARCHIVE); addSearchFilter(filterData); @@ -7519,7 +7301,7 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat updateDrawerSwipeEnabled(); } - if (animated && searchViewPager.dialogsSearchAdapter.hasRecentSearch()) { + if (animated && searchViewPager != null && searchViewPager.dialogsSearchAdapter.hasRecentSearch()) { AndroidUtilities.setAdjustResizeToNothing(getParentActivity(), classGuid); } else { AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid); @@ -7533,8 +7315,11 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat final boolean budget = SharedConfig.getDevicePerformanceClass() == SharedConfig.PERFORMANCE_CLASS_LOW || !LiteMode.isEnabled(LiteMode.FLAG_CHAT_SCALE); if (animated) { if (show) { - searchViewPager.setVisibility(View.VISIBLE); - searchViewPager.reset(); + if (searchViewPager != null) { + searchViewPager.setVisibility(View.VISIBLE); + searchViewPager.reset(); + } + updateFiltersView(true, null, null, false, false); if (searchTabsView != null) { searchTabsView.hide(false, false); @@ -7547,7 +7332,9 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat setDialogsListFrozen(true); viewPages[0].listView.setVerticalScrollBarEnabled(false); - searchViewPager.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + if (searchViewPager != null) { + searchViewPager.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite)); + } searchAnimator = new AnimatorSet(); ArrayList animators = new ArrayList<>(); animators.add(ObjectAnimator.ofFloat(viewPages[0], View.ALPHA, show ? 0.0f : 1.0f)); @@ -7562,17 +7349,19 @@ private void showSearch(boolean show, boolean startFromDownloads, boolean animat rightSlidingDialogContainer.setVisibility(View.VISIBLE); animators.add(ObjectAnimator.ofFloat(rightSlidingDialogContainer, View.ALPHA, show ? 0.0f : 1.0f)); } - animators.add(ObjectAnimator.ofFloat(searchViewPager, View.ALPHA, show ? 1.0f : 0.0f)); - if (hasStories) { - float translationY = dp(DialogStoriesCell.HEIGHT_IN_DP) + scrollYOffset; - animators.add(ObjectAnimator.ofFloat(searchViewPager, SEARCH_TRANSLATION_Y, show ? 0 : translationY)); - } - if (!budget) { - animators.add(ObjectAnimator.ofFloat(searchViewPager, View.SCALE_X, show ? 1.0f : 1.05f)); - animators.add(ObjectAnimator.ofFloat(searchViewPager, View.SCALE_Y, show ? 1.0f : 1.05f)); - } else { - searchViewPager.setScaleX(1); - searchViewPager.setScaleY(1); + if (searchViewPager != null) { + animators.add(ObjectAnimator.ofFloat(searchViewPager, View.ALPHA, show ? 1.0f : 0.0f)); + if (hasStories) { + float translationY = dp(DialogStoriesCell.HEIGHT_IN_DP) + scrollYOffset; + animators.add(ObjectAnimator.ofFloat(searchViewPager, SEARCH_TRANSLATION_Y, show ? 0 : translationY)); + } + if (!budget) { + animators.add(ObjectAnimator.ofFloat(searchViewPager, View.SCALE_X, show ? 1.0f : 1.05f)); + animators.add(ObjectAnimator.ofFloat(searchViewPager, View.SCALE_Y, show ? 1.0f : 1.05f)); + } else { + searchViewPager.setScaleX(1); + searchViewPager.setScaleY(1); + } } if (passcodeItem != null) { animators.add(ObjectAnimator.ofFloat(passcodeItem.getIconView(), View.ALPHA, show ? 0 : 1f)); @@ -7655,12 +7444,16 @@ public void onAnimationEnd(Animator animation) { } else { searchItem.collapseSearchFilters(); whiteActionBar = false; - searchViewPager.setVisibility(View.GONE); + if (searchViewPager != null) { + searchViewPager.setVisibility(View.GONE); + } if (searchTabsView != null) { searchTabsView.setVisibility(View.GONE); } searchItem.clearSearchFilters(); - searchViewPager.clear(); + if (searchViewPager != null) { + searchViewPager.clear(); + } filtersView.setVisibility(View.GONE); viewPages[0].listView.show(); if (!onlySelect) { @@ -7679,7 +7472,9 @@ public void onAnimationEnd(Animator animation) { setSearchAnimationProgress(show ? 1f : 0, false); viewPages[0].listView.setVerticalScrollBarEnabled(true); - searchViewPager.setBackground(null); + if (searchViewPager != null) { + searchViewPager.setBackground(null); + } searchAnimator = null; if (downloadsItem != null) { @@ -7720,14 +7515,17 @@ public void onAnimationCancel(Animator animation) { viewPages[0].setScaleX(1); viewPages[0].setScaleY(1); } - searchViewPager.setAlpha(show ? 1.0f : 0.0f); filtersView.setAlpha(show ? 1.0f : 0.0f); - if (!budget) { - searchViewPager.setScaleX(show ? 1.0f : 1.1f); - searchViewPager.setScaleY(show ? 1.0f : 1.1f); - } else { - searchViewPager.setScaleX(1); - searchViewPager.setScaleY(1); + if (searchViewPager != null) { + searchViewPager.setAlpha(show ? 1.0f : 0.0f); + if (!budget) { + searchViewPager.setScaleX(show ? 1.0f : 1.1f); + searchViewPager.setScaleY(show ? 1.0f : 1.1f); + } else { + searchViewPager.setScaleX(1); + searchViewPager.setScaleY(1); + } + searchViewPager.setVisibility(show ? View.VISIBLE : View.GONE); } if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { filterTabsView.setTranslationY(show ? -dp(44) : 0); @@ -7747,7 +7545,6 @@ public void onAnimationCancel(Animator animation) { dialogStoriesCell.setVisibility(View.GONE); } } - searchViewPager.setVisibility(show ? View.VISIBLE : View.GONE); setSearchAnimationProgress(show ? 1f : 0, false); fragmentView.invalidate(); @@ -7755,13 +7552,13 @@ public void onAnimationCancel(Animator animation) { downloadsItem.setAlpha(show ? 0 : 1f); } } - if (initialSearchType >= 0) { + if (initialSearchType >= 0 && searchViewPager != null) { searchViewPager.setPosition(searchViewPager.getPositionForType(initialSearchType)); } if (!show) { initialSearchType = -1; } - if (show && startFromDownloads) { + if (show && startFromDownloads && searchViewPager != null) { searchViewPager.showDownloads(); updateSpeedItem(true); } @@ -7769,7 +7566,7 @@ public void onAnimationCancel(Animator animation) { public boolean onlyDialogsAdapter() { int dialogsCount = getMessagesController().getTotalDialogsCount(); - return onlySelect || !searchViewPager.dialogsSearchAdapter.hasRecentSearch() || dialogsCount <= 10 && !hasStories; + return onlySelect || searchViewPager != null && !searchViewPager.dialogsSearchAdapter.hasRecentSearch() || dialogsCount <= 10 && !hasStories; } private void updateFilterTabsVisibility(boolean animated) { @@ -8077,7 +7874,7 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt } else { return; } - } else if (adapter == searchViewPager.dialogsSearchAdapter) { + } else if (searchViewPager != null && adapter == searchViewPager.dialogsSearchAdapter) { Object obj = searchViewPager.dialogsSearchAdapter.getItem(position); isGlobalSearch = searchViewPager.dialogsSearchAdapter.isGlobalSearch(position); if (obj instanceof TLRPC.User) { @@ -8106,10 +7903,12 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt if (ChatObject.isForum(chat)) { topicId = MessageObject.getTopicId(messageObject.currentAccount, messageObject.messageOwner, true); } - searchViewPager.dialogsSearchAdapter.addHashtagsFromMessage(searchViewPager.dialogsSearchAdapter.getLastSearchString()); + if (searchViewPager != null) { + searchViewPager.dialogsSearchAdapter.addHashtagsFromMessage(searchViewPager.dialogsSearchAdapter.getLastSearchString()); + } } else if (obj instanceof String) { String str = (String) obj; - if (searchViewPager.dialogsSearchAdapter.isHashtagSearch()) { + if (searchViewPager != null && searchViewPager.dialogsSearchAdapter.isHashtagSearch()) { actionBar.openSearchField(str, false); } else if (!str.equals("section")) { NewContactBottomSheet activity = new NewContactBottomSheet(DialogsActivity.this, getContext()); @@ -8146,7 +7945,7 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt return; } boolean checked = addOrRemoveSelectedDialog(dialogId, view); - if (adapter == searchViewPager.dialogsSearchAdapter) { + if (searchViewPager != null && adapter == searchViewPager.dialogsSearchAdapter) { actionBar.closeSearchField(); findAndUpdateCheckBox(dialogId, checked); } @@ -8189,7 +7988,9 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt closeSearch(); } else { if (searchObject != null) { - searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + if (searchViewPager != null) { + searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + } searchObject = null; } } @@ -8197,7 +7998,7 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt args.putInt("dialog_folder_id", folderId); args.putInt("dialog_filter_id", filterId); if (AndroidUtilities.isTablet() && (!getMessagesController().isForum(dialogId) || !canOpenInRightSlidingView)) { - if (openedDialogId.dialogId == dialogId && adapter != searchViewPager.dialogsSearchAdapter) { + if (openedDialogId.dialogId == dialogId && (searchViewPager == null || adapter != searchViewPager.dialogsSearchAdapter)) { if (getParentActivity() instanceof LaunchActivity) { LaunchActivity launchActivity = (LaunchActivity) getParentActivity(); List rightFragments = launchActivity.getRightActionBarLayout().getFragmentStack(); @@ -8217,7 +8018,7 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt return; } } - if (searchViewPager.actionModeShowing()) { + if (searchViewPager != null && searchViewPager.actionModeShowing()) { searchViewPager.hideActionMode(); } if (dialogId == getUserConfig().getClientUserId() && getMessagesController().savedViewAsChats) { @@ -8267,7 +8068,9 @@ private void onItemClick(View view, int position, RecyclerListView.Adapter adapt topicsFragment.parentDialogsActivity = this; rightSlidingDialogContainer.presentFragment(getParentLayout(), topicsFragment); } - searchViewPager.updateTabs(); + if (searchViewPager != null) { + searchViewPager.updateTabs(); + } } } } @@ -8366,7 +8169,7 @@ private boolean onItemLongClick(RecyclerListView listView, View view, int positi if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.hasFragment()) { return false; } - if (adapter == searchViewPager.dialogsSearchAdapter) { + if (searchViewPager != null && adapter == searchViewPager.dialogsSearchAdapter) { Object item = searchViewPager.dialogsSearchAdapter.getItem(position); if (!searchViewPager.dialogsSearchAdapter.isSearchWas()) { AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); @@ -8404,7 +8207,7 @@ private boolean onItemLongClick(RecyclerListView listView, View view, int positi } } TLRPC.Dialog dialog; - if (adapter == searchViewPager.dialogsSearchAdapter) { + if (searchViewPager != null && adapter == searchViewPager.dialogsSearchAdapter) { if (onlySelect) { onItemClick(view, position, adapter, x, y); return false; @@ -9796,142 +9599,130 @@ private void updateCounters(boolean hide) { canDeleteCount++; } } -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { -// TransitionSet transition = new TransitionSet(); -// transition.addTransition(new Visibility() { -// @Override -// public Animator onAppear(ViewGroup sceneRoot, View view, TransitionValues startValues, TransitionValues endValues) { -// AnimatorSet set = new AnimatorSet(); -// set.playTogether( -// ObjectAnimator.ofFloat(view, View.ALPHA, 0, 1f), -// ObjectAnimator.ofFloat(view, View.SCALE_X, 0.5f, 1f), -// ObjectAnimator.ofFloat(view, View.SCALE_Y, 0.5f, 1f) -// ); -// set.setInterpolator(CubicBezierInterpolator.DEFAULT); -// return set; -// } -// -// @Override -// public Animator onDisappear(ViewGroup sceneRoot, View view, TransitionValues startValues, TransitionValues endValues) { -// AnimatorSet set = new AnimatorSet(); -// set.playTogether( -// ObjectAnimator.ofFloat(view, View.ALPHA, view.getAlpha(), 0f), -// ObjectAnimator.ofFloat(view, View.SCALE_X, view.getScaleX(), 0.5f), -// ObjectAnimator.ofFloat(view, View.SCALE_Y, view.getScaleX(), 0.5f) -// ); -// set.setInterpolator(CubicBezierInterpolator.DEFAULT); -// return set; -// } -// }).addTransition(new ChangeBounds()); -// transition.setOrdering(TransitionSet.ORDERING_TOGETHER); -// transition.setInterpolator(CubicBezierInterpolator.EASE_OUT); -// transition.setDuration(150); -// TransitionManager.beginDelayedTransition(actionBar.getActionMode(), transition); -// } - if (canDeleteCount != count) { - deleteItem.setVisibility(View.GONE); - } else { - deleteItem.setVisibility(View.VISIBLE); - } - if (canClearCacheCount != 0 && canClearCacheCount != count || canClearHistoryCount != 0 && canClearHistoryCount != count) { - clearItem.setVisibility(View.GONE); - } else { - clearItem.setVisibility(View.VISIBLE); - if (canClearCacheCount != 0) { - clearItem.setText(LocaleController.getString("ClearHistoryCache", R.string.ClearHistoryCache)); + if (deleteItem != null) { + if (canDeleteCount != count) { + deleteItem.setVisibility(View.GONE); } else { - clearItem.setText(LocaleController.getString("ClearHistory", R.string.ClearHistory)); + deleteItem.setVisibility(View.VISIBLE); } } - if (canUnarchiveCount != 0) { - final String contentDescription = LocaleController.getString("Unarchive", R.string.Unarchive); - archiveItem.setTextAndIcon(contentDescription, R.drawable.msg_unarchive); - archive2Item.setIcon(R.drawable.msg_unarchive); - archive2Item.setContentDescription(contentDescription); - if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { - archive2Item.setVisibility(View.VISIBLE); - archiveItem.setVisibility(View.GONE); + if (clearItem != null) { + if (canClearCacheCount != 0 && canClearCacheCount != count || canClearHistoryCount != 0 && canClearHistoryCount != count) { + clearItem.setVisibility(View.GONE); } else { - archiveItem.setVisibility(View.VISIBLE); - archive2Item.setVisibility(View.GONE); + clearItem.setVisibility(View.VISIBLE); + if (canClearCacheCount != 0) { + clearItem.setText(LocaleController.getString("ClearHistoryCache", R.string.ClearHistoryCache)); + } else { + clearItem.setText(LocaleController.getString("ClearHistory", R.string.ClearHistory)); + } } - } else if (canArchiveCount != 0) { - final String contentDescription = LocaleController.getString("Archive", R.string.Archive); - archiveItem.setTextAndIcon(contentDescription, R.drawable.msg_archive); - archive2Item.setIcon(R.drawable.msg_archive); - archive2Item.setContentDescription(contentDescription); - if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { - archive2Item.setVisibility(View.VISIBLE); - archiveItem.setVisibility(View.GONE); + } + if (archiveItem != null && archive2Item != null) { + if (canUnarchiveCount != 0) { + final String contentDescription = LocaleController.getString("Unarchive", R.string.Unarchive); + archiveItem.setTextAndIcon(contentDescription, R.drawable.msg_unarchive); + archive2Item.setIcon(R.drawable.msg_unarchive); + archive2Item.setContentDescription(contentDescription); + if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { + archive2Item.setVisibility(View.VISIBLE); + archiveItem.setVisibility(View.GONE); + } else { + archiveItem.setVisibility(View.VISIBLE); + archive2Item.setVisibility(View.GONE); + } + } else if (canArchiveCount != 0) { + final String contentDescription = LocaleController.getString("Archive", R.string.Archive); + archiveItem.setTextAndIcon(contentDescription, R.drawable.msg_archive); + archive2Item.setIcon(R.drawable.msg_archive); + archive2Item.setContentDescription(contentDescription); + if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { + archive2Item.setVisibility(View.VISIBLE); + archiveItem.setVisibility(View.GONE); + } else { + archiveItem.setVisibility(View.VISIBLE); + archive2Item.setVisibility(View.GONE); + } } else { - archiveItem.setVisibility(View.VISIBLE); + archiveItem.setVisibility(View.GONE); archive2Item.setVisibility(View.GONE); } - } else { - archiveItem.setVisibility(View.GONE); - archive2Item.setVisibility(View.GONE); } - if (canPinCount + canUnpinCount != count) { - pinItem.setVisibility(View.GONE); - pin2Item.setVisibility(View.GONE); - } else { - if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { - pin2Item.setVisibility(View.VISIBLE); + if (pinItem != null && pin2Item != null) { + if (canPinCount + canUnpinCount != count) { pinItem.setVisibility(View.GONE); - } else { - pinItem.setVisibility(View.VISIBLE); pin2Item.setVisibility(View.GONE); + } else { + if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE) { + pin2Item.setVisibility(View.VISIBLE); + pinItem.setVisibility(View.GONE); + } else { + pinItem.setVisibility(View.VISIBLE); + pin2Item.setVisibility(View.GONE); + } } } - if (cantBlockCount != 0) { - blockItem.setVisibility(View.GONE); - } else { - blockItem.setVisibility(View.VISIBLE); - } - boolean cantRemoveFromFolder = filterTabsView == null || filterTabsView.getVisibility() != View.VISIBLE || filterTabsView.currentTabIsDefault(); - if (!cantRemoveFromFolder) { - try { - final int dialogsCount = getDialogsArray(currentAccount, viewPages[0].dialogsAdapter.getDialogsType(), folderId, dialogsListFrozen).size(); - cantRemoveFromFolder = count >= dialogsCount; - } catch (Exception ignore) { + if (blockItem != null) { + if (cantBlockCount != 0) { + blockItem.setVisibility(View.GONE); + } else { + blockItem.setVisibility(View.VISIBLE); } } - if (cantRemoveFromFolder) { - removeFromFolderItem.setVisibility(View.GONE); - } else { - removeFromFolderItem.setVisibility(View.VISIBLE); + if (removeFromFolderItem != null) { + boolean cantRemoveFromFolder = filterTabsView == null || filterTabsView.getVisibility() != View.VISIBLE || filterTabsView.currentTabIsDefault(); + if (!cantRemoveFromFolder) { + try { + final int dialogsCount = getDialogsArray(currentAccount, viewPages[0].dialogsAdapter.getDialogsType(), folderId, dialogsListFrozen).size(); + cantRemoveFromFolder = count >= dialogsCount; + } catch (Exception ignore) { + } + } + if (cantRemoveFromFolder) { + removeFromFolderItem.setVisibility(View.GONE); + } else { + removeFromFolderItem.setVisibility(View.VISIBLE); + } } - if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE && filterTabsView.currentTabIsDefault() && !FiltersListBottomSheet.getCanAddDialogFilters(this, selectedDialogs).isEmpty()) { - addToFolderItem.setVisibility(View.VISIBLE); - } else { - addToFolderItem.setVisibility(View.GONE); + if (addToFolderItem != null) { + if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE && filterTabsView.currentTabIsDefault() && !FiltersListBottomSheet.getCanAddDialogFilters(this, selectedDialogs).isEmpty()) { + addToFolderItem.setVisibility(View.VISIBLE); + } else { + addToFolderItem.setVisibility(View.GONE); + } } - if (canUnmuteCount != 0) { - muteItem.setIcon(R.drawable.msg_unmute); - muteItem.setContentDescription(LocaleController.getString("ChatsUnmute", R.string.ChatsUnmute)); - } else { - muteItem.setIcon(R.drawable.msg_mute); - muteItem.setContentDescription(LocaleController.getString("ChatsMute", R.string.ChatsMute)); + if (muteItem != null) { + if (canUnmuteCount != 0) { + muteItem.setIcon(R.drawable.msg_unmute); + muteItem.setContentDescription(LocaleController.getString("ChatsUnmute", R.string.ChatsUnmute)); + } else { + muteItem.setIcon(R.drawable.msg_mute); + muteItem.setContentDescription(LocaleController.getString("ChatsMute", R.string.ChatsMute)); + } } - if (canReadCount != 0) { - readItem.setTextAndIcon(LocaleController.getString("MarkAsRead", R.string.MarkAsRead), R.drawable.msg_markread); - readItem.setVisibility(View.VISIBLE); - } else { - if (forumCount == 0) { - readItem.setTextAndIcon(LocaleController.getString("MarkAsUnread", R.string.MarkAsUnread), R.drawable.msg_markunread); + if (readItem != null) { + if (canReadCount != 0) { + readItem.setTextAndIcon(LocaleController.getString("MarkAsRead", R.string.MarkAsRead), R.drawable.msg_markread); readItem.setVisibility(View.VISIBLE); } else { - readItem.setVisibility(View.GONE); + if (forumCount == 0) { + readItem.setTextAndIcon(LocaleController.getString("MarkAsUnread", R.string.MarkAsUnread), R.drawable.msg_markunread); + readItem.setVisibility(View.VISIBLE); + } else { + readItem.setVisibility(View.GONE); + } } } - if (canPinCount != 0) { - pinItem.setIcon(R.drawable.msg_pin); - pinItem.setContentDescription(LocaleController.getString("PinToTop", R.string.PinToTop)); - pin2Item.setText(LocaleController.getString("DialogPin", R.string.DialogPin)); - } else { - pinItem.setIcon(R.drawable.msg_unpin); - pinItem.setContentDescription(LocaleController.getString("UnpinFromTop", R.string.UnpinFromTop)); - pin2Item.setText(LocaleController.getString("DialogUnpin", R.string.DialogUnpin)); + if (pinItem != null && pin2Item != null) { + if (canPinCount != 0) { + pinItem.setIcon(R.drawable.msg_pin); + pinItem.setContentDescription(LocaleController.getString("PinToTop", R.string.PinToTop)); + pin2Item.setText(LocaleController.getString("DialogPin", R.string.DialogPin)); + } else { + pinItem.setIcon(R.drawable.msg_unpin); + pinItem.setContentDescription(LocaleController.getString("UnpinFromTop", R.string.UnpinFromTop)); + pin2Item.setText(LocaleController.getString("DialogUnpin", R.string.DialogUnpin)); + } } } @@ -10076,7 +9867,9 @@ private void closeSearch() { actionBar.closeSearchField(); } if (searchObject != null) { - searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + if (searchViewPager != null) { + searchViewPager.dialogsSearchAdapter.putRecentSearch(searchDialogId, searchObject); + } searchObject = null; } } else { @@ -10089,7 +9882,8 @@ protected RecyclerListView getListView() { } protected RecyclerListView getSearchListView() { - return searchViewPager.searchListView; + createSearchViewPager(); + return searchViewPager != null ? searchViewPager.searchListView : null; } public void createUndoView() { @@ -11418,7 +11212,7 @@ private void updateVisibleRows(int mask, boolean animated) { for (int a = 0; a < count; a++) { View child = list.getChildAt(a); if (child instanceof DialogCell) { - if (list.getAdapter() != searchViewPager.dialogsSearchAdapter) { + if (searchViewPager == null || list.getAdapter() != searchViewPager.dialogsSearchAdapter) { DialogCell cell = (DialogCell) child; if ((mask & MessagesController.UPDATE_MASK_REORDER) != 0) { cell.onReorderStateChanged(actionBar.isActionModeShowed(), true); @@ -12650,10 +12444,12 @@ public void setShowSearch(String query, int i) { if (!searchItem.getSearchField().getText().toString().equals(query)) { searchItem.getSearchField().setText(query); } - int p = searchViewPager.getPositionForType(i); - if (p >= 0) { - if (searchViewPager.getTabsView().getCurrentTabId() != p) { - searchViewPager.getTabsView().scrollToTab(p, p); + if (searchViewPager != null) { + int p = searchViewPager.getPositionForType(i); + if (p >= 0) { + if (searchViewPager.getTabsView().getCurrentTabId() != p) { + searchViewPager.getTabsView().scrollToTab(p, p); + } } } } @@ -12691,7 +12487,9 @@ public List onGetDebugItems() { public boolean closeLastFragment() { if (rightSlidingDialogContainer.hasFragment()) { rightSlidingDialogContainer.finishPreview(); - searchViewPager.updateTabs(); + if (searchViewPager != null) { + searchViewPager.updateTabs(); + } return true; } return super.closeLastFragment(); @@ -12863,4 +12661,265 @@ public void onAnimationEnd(Animator animation) { } } } + + public void createSearchViewPager() { + if (searchViewPager != null && searchViewPager.getParent() == fragmentView) return; + if (fragmentView == null) return; + if (getContext() == null) return; + + int type = 0; + if (searchString != null) { + type = 2; + } else if (!onlySelect) { + type = 1; + } + searchViewPager = new SearchViewPager(getContext(), this, type, initialDialogsType, folderId, new SearchViewPager.ChatPreviewDelegate() { + @Override + public void startChatPreview(RecyclerListView listView, DialogCell cell) { + showChatPreview(cell); + } + + @Override + public void move(float dy) { + if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { + movePreviewFragment(dy); + } + } + + @Override + public void finish() { + if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { + finishPreviewFragment(); + } + } + }) { + @Override + protected void onTabPageSelected(int position) { + updateSpeedItem(position == 2); + } + + @Override + protected long getDialogId(String query) { + if (query != null && query.length() > 0 && rightSlidingDialogContainer != null && rightSlidingDialogContainer.getFragment() instanceof TopicsFragment) { + return ((TopicsFragment) rightSlidingDialogContainer.getFragment()).getDialogId(); + } + return 0; + } + + @Override + protected boolean onBackProgress(float progress) { + return false; +// setSearchAnimationProgress(1f - progress, true); +// return true; + } + +// @Override +// protected void onBack() { +// actionBar.onSearchFieldVisibilityChanged(searchItem.toggleSearch(false)); +// } + + @Override + protected boolean includeDownloads() { + if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.hasFragment()) { + return false; + } + return true; + } + }; + ((ContentView) fragmentView).addView(searchViewPager, searchViewPagerIndex); + + searchViewPager.dialogsSearchAdapter.setDelegate(new DialogsSearchAdapter.DialogsSearchAdapterDelegate() { + @Override + public void searchStateChanged(boolean search, boolean animated) { + if (searchViewPager.emptyView.getVisibility() == View.VISIBLE) { + animated = true; + } + if (searching && searchWas && searchViewPager.emptyView != null) { + if (search || searchViewPager.dialogsSearchAdapter.getItemCount() != 0) { + searchViewPager.emptyView.showProgress(true, animated); + } else { + searchViewPager.emptyView.showProgress(false, animated); + } + } + if (search && searchViewPager.dialogsSearchAdapter.getItemCount() == 0) { + searchViewPager.cancelEnterAnimation(); + } + } + + @Override + public void didPressedBlockedDialog(View view, long did) { + showPremiumBlockedToast(view, did); + } + + @Override + public void didPressedOnSubDialog(long did) { + if (onlySelect) { + if (!validateSlowModeDialog(did)) { + return; + } + if (!selectedDialogs.isEmpty()) { + boolean checked = addOrRemoveSelectedDialog(did, null); + findAndUpdateCheckBox(did, checked); + updateSelectedCount(); + actionBar.closeSearchField(); + } else { + didSelectResult(did, 0, true, false); + } + } else { + Bundle args = new Bundle(); + if (DialogObject.isUserDialog(did)) { + args.putLong("user_id", did); + } else { + args.putLong("chat_id", -did); + } + closeSearch(); + if (AndroidUtilities.isTablet() && viewPages != null) { + for (int a = 0; a < viewPages.length; a++) { + viewPages[a].dialogsAdapter.setOpenedDialogId(openedDialogId.dialogId = did); + } + updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG); + } + if (searchString != null) { + if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) { + getNotificationCenter().postNotificationName(NotificationCenter.closeChats); + presentFragment(new ChatActivity(args)); + } + } else { + if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) { + presentFragment(new ChatActivity(args)); + } + } + } + } + + @Override + public void needRemoveHint(long did) { + if (getParentActivity() == null) { + return; + } + TLRPC.User user = getMessagesController().getUser(did); + if (user == null) { + return; + } + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + builder.setTitle(LocaleController.getString("ChatHintsDeleteAlertTitle", R.string.ChatHintsDeleteAlertTitle)); + builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("ChatHintsDeleteAlert", R.string.ChatHintsDeleteAlert, ContactsController.formatName(user.first_name, user.last_name)))); + builder.setPositiveButton(LocaleController.getString("StickersRemove", R.string.StickersRemove), (dialogInterface, i) -> getMediaDataController().removePeer(did)); + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + AlertDialog dialog = builder.create(); + showDialog(dialog); + TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); + if (button != null) { + button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); + } + } + + @Override + public void needClearList() { + AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); + if (searchViewPager.dialogsSearchAdapter.isSearchWas() && searchViewPager.dialogsSearchAdapter.isRecentSearchDisplayed()) { + builder.setTitle(LocaleController.getString("ClearSearchAlertPartialTitle", R.string.ClearSearchAlertPartialTitle)); + builder.setMessage(LocaleController.formatPluralString("ClearSearchAlertPartial", searchViewPager.dialogsSearchAdapter.getRecentResultsCount())); + builder.setPositiveButton(LocaleController.getString("Clear", R.string.Clear), (dialogInterface, i) -> { + searchViewPager.dialogsSearchAdapter.clearRecentSearch(); + }); + } else { + builder.setTitle(LocaleController.getString("ClearSearchAlertTitle", R.string.ClearSearchAlertTitle)); + builder.setMessage(LocaleController.getString("ClearSearchAlert", R.string.ClearSearchAlert)); + builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton), (dialogInterface, i) -> { + if (searchViewPager.dialogsSearchAdapter.isRecentSearchDisplayed()) { + searchViewPager.dialogsSearchAdapter.clearRecentSearch(); + } else { + searchViewPager.dialogsSearchAdapter.clearRecentHashtags(); + } + }); + } + builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); + AlertDialog dialog = builder.create(); + showDialog(dialog); + TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE); + if (button != null) { + button.setTextColor(Theme.getColor(Theme.key_text_RedBold)); + } + } + + @Override + public void runResultsEnterAnimation() { + if (searchViewPager != null) { + searchViewPager.runResultsEnterAnimation(); + } + } + + @Override + public boolean isSelected(long dialogId) { + return selectedDialogs.contains(dialogId); + } + + @Override + public long getSearchForumDialogId() { + if (rightSlidingDialogContainer != null && rightSlidingDialogContainer.getFragment() instanceof TopicsFragment) { + return ((TopicsFragment) rightSlidingDialogContainer.getFragment()).getDialogId(); + } + return 0; + } + }); + searchViewPager.channelsSearchListView.setOnItemClickListener((view, position, x, y) -> { + Object obj = searchViewPager.channelsSearchAdapter.getObject(position); + if (obj instanceof TLRPC.Chat) { + Bundle args = new Bundle(); + args.putLong("chat_id", ((TLRPC.Chat) obj).id); + ChatActivity chatActivity = new ChatActivity(args); + chatActivity.setNextChannels(searchViewPager.channelsSearchAdapter.getNextChannels(position)); + presentFragment(chatActivity); + } else if (obj instanceof MessageObject) { + MessageObject msg = (MessageObject) obj; + Bundle args = new Bundle(); + if (msg.getDialogId() >= 0) { + args.putLong("user_id", msg.getDialogId()); + } else { + args.putLong("chat_id", -msg.getDialogId()); + } + args.putInt("message_id", msg.getId()); + ChatActivity chatActivity = new ChatActivity(args); + presentFragment(highlightFoundQuote(chatActivity, msg)); + } + }); + searchViewPager.searchListView.setOnItemClickListener((view, position, x, y) -> { + if (view instanceof ProfileSearchCell && ((ProfileSearchCell) view).isBlocked()) { + showPremiumBlockedToast(view, ((ProfileSearchCell) view).getDialogId()); + return; + } + if (initialDialogsType == DIALOGS_TYPE_WIDGET) { + onItemLongClick(searchViewPager.searchListView, view, position, x, y, -1, searchViewPager.dialogsSearchAdapter); + return; + } + onItemClick(view, position, searchViewPager.dialogsSearchAdapter, x, y); + }); + searchViewPager.searchListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListenerExtended() { + @Override + public boolean onItemClick(View view, int position, float x, float y) { + if (view instanceof ProfileSearchCell && ((ProfileSearchCell) view).isBlocked()) { + showPremiumBlockedToast(view, ((ProfileSearchCell) view).getDialogId()); + return true; + } + return onItemLongClick(searchViewPager.searchListView, view, position, x, y, -1, searchViewPager.dialogsSearchAdapter); + } + + @Override + public void onMove(float dx, float dy) { + if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { + movePreviewFragment(dy); + } + } + + @Override + public void onLongClickRelease() { + if (AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y) { + finishPreviewFragment(); + } + } + }); + searchViewPager.setFilteredSearchViewDelegate((showMediaFilters, users, dates, archive) -> DialogsActivity.this.updateFiltersView(showMediaFilters, users, dates, archive, true)); + searchViewPager.setVisibility(View.GONE); + } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java index b2e797b88e..f0625674ba 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/GroupCallActivity.java @@ -5146,12 +5146,12 @@ public void requestLayout() { int year = calendar.get(Calendar.YEAR); if (year == currentYear) { return ( - LocaleController.getInstance().formatterWeek.format(date) + + LocaleController.getInstance().getFormatterWeek().format(date) + " " + - LocaleController.getInstance().formatterScheduleDay.format(date) + LocaleController.getInstance().getFormatterScheduleDay().format(date) ); } else { - return LocaleController.getInstance().formatterScheduleYear.format(date); + return LocaleController.getInstance().getFormatterScheduleYear().format(date); } } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index ef873fcb89..707d1ff905 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -40,6 +40,8 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Debug; +import android.os.Environment; import android.os.Parcelable; import android.os.StatFs; import android.os.StrictMode; @@ -52,6 +54,7 @@ import android.text.TextUtils; import android.text.style.ClickableSpan; import android.util.Base64; +import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.ActionMode; @@ -985,7 +988,7 @@ public void onPreviewOpenAnimationEnd() { } checkLayout(); checkSystemBarColors(); - handleIntent(getIntent(), false, savedInstanceState != null, false); + handleIntent(getIntent(), false, savedInstanceState != null, false, null, true, true); try { String os1 = Build.DISPLAY; String os2 = Build.USER; @@ -1777,7 +1780,7 @@ public void showPasscodeActivity(boolean fingerprint, boolean animated, int x, i PasscodeView.PasscodeViewDelegate delegate = view -> { SharedConfig.isWaitingForPasscodeEnter = false; if (passcodeSaveIntent != null) { - handleIntent(passcodeSaveIntent, passcodeSaveIntentIsNew, passcodeSaveIntentIsRestore, true, null, false); + handleIntent(passcodeSaveIntent, passcodeSaveIntentIsNew, passcodeSaveIntentIsRestore, true, null, false, true); passcodeSaveIntent = null; } drawerLayoutContainer.setAllowOpenDrawer(true, false); @@ -1815,15 +1818,11 @@ public boolean allowShowFingerprintDialog(PasscodeView passcodeView) { } private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword) { - return handleIntent(intent, isNew, restore, fromPassword, null); - } - - private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword, Browser.Progress progress) { - return handleIntent(intent, isNew, restore, fromPassword, progress, true); + return handleIntent(intent, isNew, restore, fromPassword, null, true, false); } @SuppressLint("Range") - private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword, Browser.Progress progress, boolean rebuildFragments) { + private boolean handleIntent(Intent intent, boolean isNew, boolean restore, boolean fromPassword, Browser.Progress progress, boolean rebuildFragments, boolean openedTelegram) { if (GiftInfoBottomSheet.handleIntent(intent, progress)) { return true; } @@ -2980,7 +2979,7 @@ private boolean handleIntent(Intent intent, boolean isNew, boolean restore, bool if (message != null && message.startsWith("@")) { message = " " + message; } - runLinkRequest(intentAccount[0], username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, login, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 0, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, startApp, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact); + runLinkRequest(intentAccount[0], username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, login, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 0, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, startApp, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact, openedTelegram); } else { try (Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null)) { if (cursor != null) { @@ -3939,9 +3938,9 @@ private void runLinkRequest(final int intentAccount, final boolean forceNotInternalForApps, final int storyId, final boolean isBoost, - final String chatLinkSlug, boolean botCompact) { + final String chatLinkSlug, boolean botCompact, boolean openedTelegram) { if (state == 0 && ChatActivity.SCROLL_DEBUG_DELAY && progress != null) { - Runnable runnable = () -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 1, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact); + Runnable runnable = () -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 1, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact, openedTelegram); progress.init(); progress.onCancel(() -> AndroidUtilities.cancelRunOnUIThread(runnable)); AndroidUtilities.runOnUIThread(runnable, 7500); @@ -3951,7 +3950,7 @@ private void runLinkRequest(final int intentAccount, if (account != intentAccount) { switchToAccount(account, true); } - runLinkRequest(account, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 1, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact); + runLinkRequest(account, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, 1, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact, openedTelegram); }).show(); return; } else if (code != null) { @@ -4108,7 +4107,7 @@ private void runLinkRequest(final int intentAccount, getAttachMenuBot.bot = MessagesController.getInstance(intentAccount).getInputUser(peerId); ConnectionsManager.getInstance(intentAccount).sendRequest(getAttachMenuBot, (response1, error1) -> AndroidUtilities.runOnUIThread(() -> { if (error1 != null) { - AndroidUtilities.runOnUIThread(() -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, null, null, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact)); + AndroidUtilities.runOnUIThread(() -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, null, null, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact, openedTelegram)); } else if (response1 instanceof TLRPC.TL_attachMenuBotsBot) { TLRPC.TL_attachMenuBotsBot bot = (TLRPC.TL_attachMenuBotsBot) response1; TLRPC.TL_attachMenuBot attachBot = bot.bot; @@ -4129,7 +4128,7 @@ private void runLinkRequest(final int intentAccount, } }), ConnectionsManager.RequestFlagInvokeAfter | ConnectionsManager.RequestFlagFailOnServerErrors); - processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, botAttachable, true, botCompact); + processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, botAttachable, true, botCompact, openedTelegram); }, null); } else if (attachBot.request_write_access || forceNotInternalForApps) { AtomicBoolean allowWrite = new AtomicBoolean(true); @@ -4147,15 +4146,15 @@ private void runLinkRequest(final int intentAccount, } }), ConnectionsManager.RequestFlagInvokeAfter | ConnectionsManager.RequestFlagFailOnServerErrors); - processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact); + processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact, openedTelegram); }); } else { - processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact); + processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact, openedTelegram); } } })); } else { - processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact); + processWebAppBot(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, botAppMaybe, botAppStartParam, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, user, dismissLoading, false, false, botCompact, openedTelegram); } return; } @@ -5181,7 +5180,7 @@ private void processWebAppBot(final int intentAccount, final boolean isBoost, final String chatLinkSlug, TLRPC.User user, - Runnable dismissLoading, boolean botAttachable, boolean ignoreInactive, boolean botCompact) { + Runnable dismissLoading, boolean botAttachable, boolean ignoreInactive, boolean botCompact, boolean openedTelegram) { TLRPC.TL_messages_getBotApp getBotApp = new TLRPC.TL_messages_getBotApp(); TLRPC.TL_inputBotAppShortName app = new TLRPC.TL_inputBotAppShortName(); @@ -5193,7 +5192,7 @@ private void processWebAppBot(final int intentAccount, progress.end(); } if (error1 != null) { - AndroidUtilities.runOnUIThread(() -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, null, null, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact)); + AndroidUtilities.runOnUIThread(() -> runLinkRequest(intentAccount, username, group, sticker, emoji, botUser, botChat, botChannel, botChatAdminParams, message, contactToken, folderSlug, text, hasUrl, messageId, channelId, threadId, commentId, game, auth, lang, unsupportedUrl, code, loginToken, wallPaper, inputInvoiceSlug, theme, voicechat, videochat, livestream, state, videoTimestamp, setAsAttachBot, attachMenuBotToOpen, attachMenuBotChoose, null, null, progress, forceNotInternalForApps, storyId, isBoost, chatLinkSlug, botCompact, openedTelegram)); } else { TLRPC.TL_messages_botApp botApp = (TLRPC.TL_messages_botApp) response1; AndroidUtilities.runOnUIThread(() -> { @@ -5209,6 +5208,7 @@ private void processWebAppBot(final int intentAccount, } if (AndroidUtilities.isTablet()) { BotWebViewSheet sheet = new BotWebViewSheet(LaunchActivity.this, lastFragment != null ? lastFragment.getResourceProvider() : null); + sheet.setWasOpenedByLinkIntent(openedTelegram); sheet.setDefaultFullsize(!botCompact); sheet.setNeedsContext(false); sheet.setParentActivity(LaunchActivity.this); @@ -5219,6 +5219,7 @@ private void processWebAppBot(final int intentAccount, } } else { BotWebViewAttachedSheet sheet = lastFragment.createBotViewer(); + sheet.setWasOpenedByLinkIntent(openedTelegram); sheet.setDefaultFullsize(!botCompact); sheet.setNeedsContext(false); sheet.setParentActivity(LaunchActivity.this); @@ -5752,12 +5753,12 @@ public void setNavigateToPremiumGiftCallback(Runnable val) { @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); - handleIntent(intent, true, false, false); + handleIntent(intent, true, false, false, null, true, true); } public void onNewIntent(Intent intent, Browser.Progress progress) { super.onNewIntent(intent); - handleIntent(intent, true, false, false, progress); + handleIntent(intent, true, false, false, progress, true, false); } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java index f297a30b63..2fd89f6ce1 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LinkEditActivity.java @@ -731,9 +731,9 @@ private void chooseDate(int selectedDate) { if (selectedDate < 86400L) { options[i] = LocaleController.getString("MessageScheduleToday", R.string.MessageScheduleToday); } else if (selectedDate < 364 * 86400L) { - options[i] = LocaleController.getInstance().formatterScheduleDay.format(originDate * 1000L); + options[i] = LocaleController.getInstance().getFormatterScheduleDay().format(originDate * 1000L); } else { - options[i] = LocaleController.getInstance().formatterYear.format(originDate * 1000L); + options[i] = LocaleController.getInstance().getFormatterYear().format(originDate * 1000L); } } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java index 8ef1a6e0cb..234673407e 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LocationActivity.java @@ -50,6 +50,7 @@ import android.text.TextUtils; import android.text.Html; import android.text.method.LinkMovementMethod; +import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -2719,7 +2720,6 @@ public void didReceivedNotification(int id, int account, Object... args) { } else if (id == NotificationCenter.liveLocationsChanged) { if (adapter != null) { adapter.notifyDataSetChanged(); - adapter.updateLiveLocationCell(); } } else if (id == NotificationCenter.didReceiveNewMessages) { boolean scheduled = (Boolean) args[2]; @@ -2794,7 +2794,7 @@ public void didReceivedNotification(int id, int account, Object... args) { } } if (updated && adapter != null) { - adapter.updateLiveLocations(); + adapter.notifyDataSetChanged(); if (proximitySheet != null) { proximitySheet.updateText(true, true); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsController.java b/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsController.java index f83bf25b3f..ce998233a2 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsController.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsController.java @@ -36,6 +36,7 @@ import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.BulletinFactory; +import org.telegram.ui.Components.FireworksOverlay; import org.telegram.ui.LaunchActivity; //import org.telegram.ui.PaymentFormActivity; import org.telegram.ui.bots.BotWebViewSheet; @@ -532,7 +533,11 @@ public void openPaymentForm(MessageObject messageObject, TLRPC.InputInvoice inpu _stars += price.amount; } final long stars = _stars; - final long dialogId = form.bot_id; + final long dialogId = messageObject != null && messageObject.type == MessageObject.TYPE_PAID_MEDIA ? ( + (messageObject.messageOwner.fwd_from != null && messageObject.messageOwner.fwd_from.from_id != null) ? + DialogObject.getPeerDialogId(messageObject.messageOwner.fwd_from.from_id) : + messageObject.getDialogId() + ) : form.bot_id; final String bot; if (dialogId >= 0) { bot = UserObject.getUserName(MessagesController.getInstance(currentAccount).getUser(dialogId)); @@ -671,6 +676,9 @@ private void payAfterConfirmed(MessageObject messageObject, TLRPC.InputInvoice i } else { b.createSimpleBulletin(starDrawable, getString(R.string.StarsPurchaseCompleted), AndroidUtilities.replaceTags(formatPluralString("StarsPurchaseCompletedInfo", (int) stars, product, bot))).show(); } + if (LaunchActivity.instance != null && LaunchActivity.instance.getFireworksOverlay() != null) { + LaunchActivity.instance.getFireworksOverlay().start(); + } invalidateTransactions(true); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsIntroActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsIntroActivity.java index 6cbd62ffc9..7513676bc9 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsIntroActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Stars/StarsIntroActivity.java @@ -1518,11 +1518,11 @@ protected void onDetachedFromWindow() { String c; if (videosCount == 0) { - c = formatString(R.string.StarsConfirmPurchaseMedia1, photosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SinglePhoto) : formatPluralString("StarsConfirmPurchaseMedia_Photos", photosCount), chatTitle, formatPluralString("Stars", (int) stars)); + c = formatPluralString("StarsConfirmPurchaseMediaOne2", (int) stars, photosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SinglePhoto) : formatPluralString("StarsConfirmPurchaseMedia_Photos", photosCount), chatTitle); } else if (photosCount == 0) { - c = formatString(R.string.StarsConfirmPurchaseMedia1, videosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SingleVideo) : formatPluralString("StarsConfirmPurchaseMedia_Videos", videosCount), chatTitle, formatPluralString("Stars", (int) stars)); + c = formatPluralString("StarsConfirmPurchaseMediaOne2", (int) stars, videosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SingleVideo) : formatPluralString("StarsConfirmPurchaseMedia_Videos", videosCount), chatTitle); } else { - c = formatString(R.string.StarsConfirmPurchaseMedia2, photosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SinglePhoto) : formatPluralString("StarsConfirmPurchaseMedia_Photos", photosCount), videosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SingleVideo) : formatPluralString("StarsConfirmPurchaseMedia_Videos", videosCount), chatTitle, formatPluralString("Stars", (int) stars)); + c = formatPluralString("StarsConfirmPurchaseMediaTwo2", (int) stars, photosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SinglePhoto) : formatPluralString("StarsConfirmPurchaseMedia_Photos", photosCount), videosCount == 1 ? getString(R.string.StarsConfirmPurchaseMedia_SingleVideo) : formatPluralString("StarsConfirmPurchaseMedia_Videos", videosCount), chatTitle); } subtitleView.setText(AndroidUtilities.replaceTags(c)); } else { @@ -2249,11 +2249,11 @@ public void updateDrawState(@NonNull TextPaint ds) { tableView.addRowUnpadded(getString(R.string.StarsTransactionID), idLayout); } - tableView.addRow(getString(R.string.StarsTransactionDate), LocaleController.formatString(R.string.formatDateAtTime, LocaleController.getInstance().formatterGiveawayCard.format(new Date(transaction.date * 1000L)), LocaleController.getInstance().formatterDay.format(new Date(transaction.date * 1000L)))); + tableView.addRow(getString(R.string.StarsTransactionDate), LocaleController.formatString(R.string.formatDateAtTime, LocaleController.getInstance().getFormatterGiveawayCard().format(new Date(transaction.date * 1000L)), LocaleController.getInstance().getFormatterDay().format(new Date(transaction.date * 1000L)))); linearLayout.addView(tableView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 0, 17, 0, 0)); if ((transaction.flags & 32) != 0) { - tableView.addRow(getString(R.string.StarsTransactionTONDate), LocaleController.formatString(R.string.formatDateAtTime, LocaleController.getInstance().formatterGiveawayCard.format(new Date(transaction.transaction_date * 1000L)), LocaleController.getInstance().formatterDay.format(new Date(transaction.transaction_date * 1000L)))); + tableView.addRow(getString(R.string.StarsTransactionTONDate), LocaleController.formatString(R.string.formatDateAtTime, LocaleController.getInstance().getFormatterGiveawayCard().format(new Date(transaction.transaction_date * 1000L)), LocaleController.getInstance().getFormatterDay().format(new Date(transaction.transaction_date * 1000L)))); } textView = new LinkSpanDrawable.LinksTextView(context, resourcesProvider); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java index 3055346b46..e8106ecae0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/StatisticActivity.java @@ -572,7 +572,7 @@ public View createView(Context context) { TLRPC.Chat currentChat = MessagesController.getInstance(currentAccount).getChat(chatId); TLRPC.ChatFull chatFull = MessagesController.getInstance(currentAccount).getChatFull(chatId); boolean isBoostSupported = ChatObject.isBoostSupported(currentChat); - final boolean hasMonetization = ChatObject.isChannelAndNotMegaGroup(currentChat) && chatFull != null && chatFull.can_view_revenue; + final boolean hasMonetization = ChatObject.isChannelAndNotMegaGroup(currentChat) && chatFull != null && (chatFull.can_view_revenue || chatFull.can_view_stars_revenue); BottomPagerTabs storiesTabsView = new BottomPagerTabs(context, getResourceProvider()) { @Override public Tab[] createTabs() { @@ -608,7 +608,7 @@ protected void onTabAnimationUpdate(boolean manual) { boostLayout = new ChannelBoostLayout(StatisticActivity.this, -chatId, getResourceProvider()); } if (hasMonetization) { - monetizationLayout = new ChannelMonetizationLayout(getContext(), StatisticActivity.this, currentAccount, -chatId, getResourceProvider()); + monetizationLayout = new ChannelMonetizationLayout(getContext(), StatisticActivity.this, currentAccount, -chatId, getResourceProvider(), chatFull.can_view_revenue, chatFull.can_view_stars_revenue); monetizationLayout.setActionBar(actionBar); } boolean showTabs = isBoostSupported && !onlyBoostsStat; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/UserInfoActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/UserInfoActivity.java index 2484a5c842..aa8e24daf3 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/UserInfoActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/UserInfoActivity.java @@ -208,12 +208,12 @@ public static String birthdayString(TLRPC.TL_birthday birthday) { calendar.set(Calendar.YEAR, birthday.year); calendar.set(Calendar.MONTH, birthday.month - 1); calendar.set(Calendar.DAY_OF_MONTH, birthday.day); - return LocaleController.getInstance().formatterBoostExpired.format(calendar.getTimeInMillis()); + return LocaleController.getInstance().getFormatterBoostExpired().format(calendar.getTimeInMillis()); } else { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, birthday.month - 1); calendar.set(Calendar.DAY_OF_MONTH, birthday.day); - return LocaleController.getInstance().formatterDayMonth.format(calendar.getTimeInMillis()); + return LocaleController.getInstance().getFormatterDayMonth().format(calendar.getTimeInMillis()); } } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewAttachedSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewAttachedSheet.java index bd02b24d9f..0d7246366b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewAttachedSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewAttachedSheet.java @@ -1,6 +1,7 @@ package org.telegram.ui.bots; import static org.telegram.messenger.AndroidUtilities.dp; +import static org.telegram.messenger.AndroidUtilities.lerp; import static org.telegram.ui.Components.Bulletin.DURATION_PROLONG; import android.animation.Animator; @@ -345,14 +346,16 @@ public boolean restoreState(BaseFragment fragment, BottomSheetTabs.WebTabData ta } }; + private final Context context; private final BaseFragment fragment; public Context getContext() { - return fragment.getContext(); + return context; } public BotWebViewAttachedSheet(@NonNull BaseFragment fragment) { this.fragment = fragment; + this.context = fragment.getContext(); this.resourcesProvider = fragment.getResourceProvider(); lineColor = Theme.getColor(Theme.key_sheet_scrollUp); @@ -454,6 +457,9 @@ public void onSetSettingsButtonVisible(boolean visible) { @Override public void onWebAppOpenInvoice(TLRPC.InputInvoice inputInvoice, String slug, TLObject response) { + if (getContext() == null) { + return; + } Toast.makeText(getContext(), LocaleController.getString("nekoXPaymentRemovedToast", R.string.nekoXPaymentRemovedToast), Toast.LENGTH_LONG).show(); // NekoX: The payment function has been removed. } @@ -688,8 +694,8 @@ public void onAnimationEnd(Animator animation) { public float getContainerTop() { float transitionProgress = AndroidUtilities.isTablet() ? 0 : actionBarTransitionProgress; - return AndroidUtilities.isTablet() ? AndroidUtilities.lerp(swipeContainer.getTranslationY() + dp(12), AndroidUtilities.statusBarHeight / 2f, actionBarTransitionProgress) : - (AndroidUtilities.lerp(swipeContainer.getTranslationY(), AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() / 2f, transitionProgress) + dp(12)); + return AndroidUtilities.isTablet() ? lerp(swipeContainer.getTranslationY() + dp(12), AndroidUtilities.statusBarHeight / 2f, actionBarTransitionProgress) : + (lerp(swipeContainer.getTranslationY(), AndroidUtilities.statusBarHeight + ActionBar.getCurrentActionBarHeight() / 2f, transitionProgress) + dp(12)); } public void attachInternal() { @@ -821,6 +827,12 @@ public void setDefaultFullsize(boolean fullsize) { } } + public void setWasOpenedByLinkIntent(boolean value) { + if (webViewContainer != null) { + webViewContainer.setWasOpenedByLinkIntent(value); + } + } + public void setNeedsContext(boolean needsContext) { this.needsContext = needsContext; } @@ -1227,6 +1239,9 @@ public void show() { show(false); } public void show(boolean lowBounce) { + show(lowBounce, false); + } + public void show(boolean lowBounce, boolean instant) { if (!AndroidUtilities.isSafeToShow(getContext())) return; windowView.setAlpha(0f); @@ -1249,15 +1264,25 @@ public void onLayoutChange(View v, int left, int top, int right, int bottom, int } if (showExpanded || getFullSize()) { - swipeContainer.stickTo(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY(), locker::unlock); + if (instant) { + swipeContainer.setSwipeOffsetY(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY()); + locker.unlock(); + } else { + swipeContainer.stickTo(-swipeContainer.getOffsetY() + swipeContainer.getTopActionBarOffsetY(), locker::unlock); + } } else { - new SpringAnimation(swipeContainer, ChatAttachAlertBotWebViewLayout.WebViewSwipeContainer.SWIPE_OFFSET_Y, 0) - .setSpring(new SpringForce(0) - .setDampingRatio(lowBounce ? SpringForce.DAMPING_RATIO_NO_BOUNCY : SpringForce.DAMPING_RATIO_LOW_BOUNCY) - .setStiffness(lowBounce ? 800 : 500.0f) - ).addEndListener((animation, canceled, value, velocity) -> { + if (instant) { + swipeContainer.setSwipeOffsetY(0); locker.unlock(); - }).start(); + } else { + new SpringAnimation(swipeContainer, ChatAttachAlertBotWebViewLayout.WebViewSwipeContainer.SWIPE_OFFSET_Y, 0) + .setSpring(new SpringForce(0) + .setDampingRatio(lowBounce ? SpringForce.DAMPING_RATIO_NO_BOUNCY : SpringForce.DAMPING_RATIO_LOW_BOUNCY) + .setStiffness(lowBounce ? 800 : 500.0f) + ).addEndListener((animation, canceled, value, velocity) -> { + locker.unlock(); + }).start(); + } } swipeContainer.opened = true; } @@ -1330,6 +1355,10 @@ public void dismiss() { dismiss(false, null); } + public void dismiss(boolean intoTabs) { + dismiss(intoTabs, null); + } + public boolean onCheckDismissByUser() { if (needCloseConfirmation) { String botName = null; @@ -1433,7 +1462,7 @@ public boolean isFullyVisible() { return false; } - public class WindowView extends SizeNotifierFrameLayout { + public class WindowView extends SizeNotifierFrameLayout implements BaseFragment.AttachedSheetWindow { public WindowView(Context context) { super(context); setWillNotDraw(false); @@ -1469,7 +1498,7 @@ protected void onDraw(Canvas canvas) { actionBarPaint.setColor(actionBarColor); float radius = dp(16) * (AndroidUtilities.isTablet() ? 1f : 1f - actionBarTransitionProgress); - AndroidUtilities.rectTmp.set(swipeContainer.getLeft(), AndroidUtilities.lerp(swipeContainer.getTranslationY(), 0, actionBarTransitionProgress), swipeContainer.getRight(), swipeContainer.getTranslationY() + dp(24) + radius); + AndroidUtilities.rectTmp.set(swipeContainer.getLeft(), lerp(swipeContainer.getTranslationY(), 0, actionBarTransitionProgress), swipeContainer.getRight(), swipeContainer.getTranslationY() + dp(24) + radius); canvas.drawRoundRect(AndroidUtilities.rectTmp, radius, radius, actionBarPaint); AndroidUtilities.rectTmp.set(swipeContainer.getLeft(), swipeContainer.getTranslationY() + dp(24), swipeContainer.getRight(), getHeight()); @@ -1503,7 +1532,7 @@ public void draw(Canvas canvas) { @Override public boolean onTouchEvent(MotionEvent event) { if (drawingFromOverlay) return false; - if (event.getAction() == MotionEvent.ACTION_DOWN && (event.getY() <= AndroidUtilities.lerp(swipeContainer.getTranslationY() + dp(24), 0, actionBarTransitionProgress) || + if (event.getAction() == MotionEvent.ACTION_DOWN && (event.getY() <= lerp(swipeContainer.getTranslationY() + dp(24), 0, actionBarTransitionProgress) || event.getX() > swipeContainer.getRight() || event.getX() < swipeContainer.getLeft())) { // if (can_minimize) { dismiss(true, null); @@ -1543,27 +1572,62 @@ public void setDrawingFromOverlay(boolean drawingFromOverlay) { private final RectF rect = new RectF(); private final Path clipPath = new Path(); + public RectF getRect() { + rect.set(swipeContainer.getLeft(), lerp(swipeContainer.getTranslationY() + dp(24), 0, actionBarTransitionProgress), swipeContainer.getRight(), getHeight()); + return rect; + } + - public float drawInto(Canvas canvas, RectF finalRect, float progress, RectF clipRect) { - rect.set(swipeContainer.getLeft(), swipeContainer.getTranslationY() + dp(24), swipeContainer.getRight(), getHeight()); + public float drawInto(Canvas canvas, RectF finalRect, float progress, RectF clipRect, float alpha, boolean opening) { + rect.set(swipeContainer.getLeft(), lerp(swipeContainer.getTranslationY() + dp(24), 0, actionBarTransitionProgress), swipeContainer.getRight(), getHeight()); AndroidUtilities.lerpCentered(rect, finalRect, progress, clipRect); canvas.save(); clipPath.rewind(); float radius = dp(16) * (AndroidUtilities.isTablet() ? 1f : 1f - actionBarTransitionProgress); - final float r = AndroidUtilities.lerp(radius, dp(10), progress); - clipPath.addRoundRect(clipRect, r, r, Path.Direction.CW); + final float r = lerp(radius, dp(10), progress); + rect.set(clipRect); + if (opening) { + rect.top -= dp(16) * (1f - actionBarTransitionProgress); + } + clipPath.addRoundRect(rect, r, r, Path.Direction.CW); canvas.clipPath(clipPath); + + if (!overrideBackgroundColor) { + backgroundPaint.setColor(getColor(Theme.key_windowBackgroundWhite)); + } + int wasAlpha = backgroundPaint.getAlpha(); + backgroundPaint.setAlpha((int) (wasAlpha * alpha)); canvas.drawPaint(backgroundPaint); + backgroundPaint.setAlpha(wasAlpha); if (swipeContainer != null) { canvas.save(); - canvas.translate(swipeContainer.getX(), Math.max(swipeContainer.getY(), clipRect.top) + progress * dp(51)); + canvas.translate(swipeContainer.getX(), Math.max(swipeContainer.getY(), clipRect.top) + (opening ? lerp(dp(16), actionBar.getHeight(), actionBarTransitionProgress) * (1f - alpha) : progress * dp(51))); + if (opening) { + canvas.scale(1f, lerp(1f, 1.25f, 1f - alpha)); + swipeContainer.setAlpha(alpha); + } swipeContainer.draw(canvas); + if (opening) { + swipeContainer.setAlpha(1f); + } canvas.restore(); } + if (opening) { + if (actionBar != null && actionBarTransitionProgress > 0) { + canvas.saveLayerAlpha(actionBar.getX(), actionBar.getY() + clipRect.top, actionBar.getX() + actionBar.getWidth(), actionBar.getY() + clipRect.top + actionBar.getHeight() + actionBarShadow.getIntrinsicHeight(), (int) (0xFF * alpha * actionBarTransitionProgress), Canvas.ALL_SAVE_FLAG); + canvas.translate(actionBar.getX(), actionBar.getY() + clipRect.top); + actionBar.draw(canvas); + actionBarShadow.setAlpha(0xff);//(int) (actionBar.getAlpha() * progress * 0xFF)); + actionBarShadow.setBounds(0, actionBar.getHeight(), actionBar.getWidth(), (int) (actionBar.getHeight() + actionBarShadow.getIntrinsicHeight())); + actionBarShadow.draw(canvas); + canvas.restore(); + } + } + canvas.restore(); return r; diff --git a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewContainer.java b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewContainer.java index b49f189a06..4cf055d8d8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewContainer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewContainer.java @@ -27,7 +27,6 @@ import android.os.Message; import android.text.SpannableStringBuilder; import android.text.TextUtils; -import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; @@ -97,7 +96,6 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; @@ -302,10 +300,10 @@ private void setupWebView(MyWebView replaceWith, WebViewProxy proxy) { } private void onOpenUri(Uri uri) { - onOpenUri(uri, false, false); + onOpenUri(uri, null, false, false); } - private void onOpenUri(Uri uri, boolean tryInstantView, boolean suppressPopup) { + private void onOpenUri(Uri uri, String browser, boolean tryInstantView, boolean suppressPopup) { if (isRequestingPageOpen || System.currentTimeMillis() - lastClickMs > 1000 && suppressPopup) { return; } @@ -314,23 +312,17 @@ private void onOpenUri(Uri uri, boolean tryInstantView, boolean suppressPopup) { boolean[] forceBrowser = {false}; boolean internal = Browser.isInternalUri(uri, forceBrowser); - if (internal && !forceBrowser[0]) { - if (delegate != null) { - setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); - BotWebViewContainer.this.setFocusable(false); - webView.setFocusable(false); - webView.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); - webView.clearFocus(); - InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); - imm.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); - - Browser.openUrl(getContext(), uri, true, tryInstantView); - } else { - Browser.openUrl(getContext(), uri, true, tryInstantView); - } - } else { - Browser.openUrl(getContext(), uri, true, tryInstantView); + if (internal && !forceBrowser[0] && delegate != null) { + setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); + BotWebViewContainer.this.setFocusable(false); + webView.setFocusable(false); + webView.setDescendantFocusability(FOCUS_BLOCK_DESCENDANTS); + webView.clearFocus(); + InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.hideSoftInputFromWindow(getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } + + Browser.openUrl(getContext(), uri, true, tryInstantView, false, null, browser); } public static int getMainButtonRippleColor(int buttonColor) { @@ -809,6 +801,11 @@ public void setWebViewScrollListener(WebViewScrollListener webViewScrollListener } } + private boolean wasOpenedByLinkIntent; + public void setWasOpenedByLinkIntent(boolean value) { + wasOpenedByLinkIntent = value; + } + public void setDelegate(Delegate delegate) { this.delegate = delegate; } @@ -821,7 +818,22 @@ private void onEventReceived(String eventType, String eventData) { d("onEventReceived " + eventType); switch (eventType) { case "web_app_close": { + boolean return_back = false; + try { + JSONObject jsonObject = new JSONObject(eventData); + return_back = jsonObject.optBoolean("return_back"); + } catch (Exception e) { + FileLog.e(e); + } + delegate.onCloseRequested(null); + if (wasOpenedByLinkIntent && return_back && LaunchActivity.instance != null) { + Activity activity = AndroidUtilities.findActivity(getContext()); + if (activity == null) activity = LaunchActivity.instance; + if (activity != null && !activity.isFinishing()) { + activity.moveTaskToBack(true); + } + } break; } case "web_app_switch_inline_query": { @@ -1142,9 +1154,10 @@ public void didReceivedNotification(int id, int account, Object... args) { try { JSONObject jsonData = new JSONObject(eventData); Uri uri = Uri.parse(jsonData.optString("url")); + String browser = jsonData.optString("try_browser"); if (MessagesController.getInstance(currentAccount).webAppAllowedProtocols != null && MessagesController.getInstance(currentAccount).webAppAllowedProtocols.contains(uri.getScheme())) { - onOpenUri(uri, jsonData.optBoolean("try_instant_view"), true); + onOpenUri(uri, browser, jsonData.optBoolean("try_instant_view"), true); } } catch (Exception e) { FileLog.e(e); @@ -1158,7 +1171,7 @@ public void didReceivedNotification(int id, int account, Object... args) { if (pathFull.startsWith("/")) { pathFull = pathFull.substring(1); } - onOpenUri(Uri.parse("https://t.me/" + pathFull), false, true); + onOpenUri(Uri.parse("https://t.me/" + pathFull), null, false, true); } catch (JSONException e) { FileLog.e(e); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewMenuContainer.java b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewMenuContainer.java index 2da908ee51..a117c8281a 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewMenuContainer.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewMenuContainer.java @@ -187,6 +187,7 @@ public BottomSheetTabs.WebTabData saveState() { tab.main = mainButtonSettings; tab.confirmDismiss = needCloseConfirmation; tab.expanded = swipeContainer != null && ((1f - Math.min(swipeContainer.getTopActionBarOffsetY(), swipeContainer.getTranslationY() - swipeContainer.getTopActionBarOffsetY()) / swipeContainer.getTopActionBarOffsetY()) > .5f); + tab.expandedOffset = swipeContainer != null ? swipeContainer.getOffsetY() : Float.MAX_VALUE; tab.needsContext = true; BotWebViewContainer.MyWebView webView = webViewContainer == null ? null : webViewContainer.getWebView(); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewSheet.java b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewSheet.java index 749355811d..a468f3df86 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewSheet.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/bots/BotWebViewSheet.java @@ -836,6 +836,12 @@ public void setDefaultFullsize(boolean fullsize) { } } + public void setWasOpenedByLinkIntent(boolean value) { + if (webViewContainer != null) { + webViewContainer.setWasOpenedByLinkIntent(value); + } + } + public void setNeedsContext(boolean needsContext) { this.needsContext = needsContext; } diff --git a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/CloudSettingsHelper.java b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/CloudSettingsHelper.java index 1bfd916e50..985bf01c48 100644 --- a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/CloudSettingsHelper.java +++ b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/CloudSettingsHelper.java @@ -281,9 +281,9 @@ private static String formatDateUntil(long date) { int dateYear = rightNow.get(Calendar.YEAR); if (year == dateYear) { - return LocaleController.getInstance().formatterBannedUntilThisYear.format(new Date(date)); + return LocaleController.getInstance().getFormatterBannedUntilThisYear().format(new Date(date)); } else { - return LocaleController.getInstance().formatterBannedUntil.format(new Date(date)); + return LocaleController.getInstance().getFormatterBannedUntil().format(new Date(date)); } } catch (Exception e) { FileLog.e(e); diff --git a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/ProfileDateHelper.java b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/ProfileDateHelper.java index c6b23196b2..f16c24a5d7 100644 --- a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/ProfileDateHelper.java +++ b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/helpers/ProfileDateHelper.java @@ -41,7 +41,7 @@ private static void loadData() { } public static String getUserTime(String prefix, long date) { - String st = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))); + String st = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))); return prefix + " " + st; } diff --git a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/ui/MessageDetailsActivity.java b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/ui/MessageDetailsActivity.java index e1fc1add74..74add9a3a9 100644 --- a/TMessagesProj/src/main/java/tw/nekomimi/nekogram/ui/MessageDetailsActivity.java +++ b/TMessagesProj/src/main/java/tw/nekomimi/nekogram/ui/MessageDetailsActivity.java @@ -436,10 +436,10 @@ public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { textCell.setTextAndValue("Bot", "Yes", divider); } else if (position == dateRow) { long date = (long) messageObject.messageOwner.date * 1000; - textCell.setTextAndValue(messageObject.scheduled ? "Scheduled date" : "Date", messageObject.messageOwner.date == 0x7ffffffe ? "When online" : LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))), divider); + textCell.setTextAndValue(messageObject.scheduled ? "Scheduled date" : "Date", messageObject.messageOwner.date == 0x7ffffffe ? "When online" : LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))), divider); } else if (position == editedRow) { long date = (long) messageObject.messageOwner.edit_date * 1000; - textCell.setTextAndValue("Edited", LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))), divider); + textCell.setTextAndValue("Edited", LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().getFormatterYear().format(new Date(date)), LocaleController.getInstance().getFormatterDay().format(new Date(date))), divider); } else if (position == forwardRow) { StringBuilder builder = new StringBuilder(); if (messageObject.messageOwner.fwd_from.from_id == null) { diff --git a/TMessagesProj/src/main/res/values/strings.xml b/TMessagesProj/src/main/res/values/strings.xml index b13c245846..5ca34bfe2b 100644 --- a/TMessagesProj/src/main/res/values/strings.xml +++ b/TMessagesProj/src/main/res/values/strings.xml @@ -8691,6 +8691,10 @@ Telegram shares %1$d%% of the revenue from ads displayed in your channel. **Learn more >** Available balance You can collect your reward using Fragment, a third-party platform used by advertisers to pay for ads. **Learn more >** + Funds from your total balance become available for spending on ads and rewards 21 days after they are earned. + https://telegram.org/tos/content-creator-rewards + TON from your total balance become available for spending on ads and rewards 21 days after they are earned. + https://telegram.org/tos/content-creator-rewards https://telegram.org/tos/content-creator-rewards In the coming weeks you will be able to collect your reward using Fragment, a third-party platform used by advertisers to pay ads. **Learn more >** Transaction history @@ -9063,7 +9067,9 @@ **%d photos** **%s video** **%s videos** - Do you want to unlock %1$s in **%2$s** for **%3$s**? - Do you want to unlock %1$s and %2$s in **%3$s** for **%4$s**? + Do you want to unlock %2$s in **%3$s** for **%1$d star**? + Do you want to unlock %2$s in **%3$s** for **%1$d stars**? + Do you want to unlock %2$s and %3$s in **%4$s** for **%1$d star**? + Do you want to unlock %2$s and %3$s in **%4$s** for **%1$d stars**? ⭐️ %s \ No newline at end of file diff --git a/TMessagesProj_AppStandalone/src/main/java/org/telegram/ui/SMSStatsActivity.java b/TMessagesProj_AppStandalone/src/main/java/org/telegram/ui/SMSStatsActivity.java index f48944b0ca..2e1fa022b6 100644 --- a/TMessagesProj_AppStandalone/src/main/java/org/telegram/ui/SMSStatsActivity.java +++ b/TMessagesProj_AppStandalone/src/main/java/org/telegram/ui/SMSStatsActivity.java @@ -1006,7 +1006,7 @@ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { public void setEntry(SMSJobController.JobEntry entry, boolean last) { if (entry == null) return; - dateTextView.setText(LocaleController.getInstance().formatterGiveawayCard.format(new Date(entry.date * 1000L)) + ", " + LocaleController.getInstance().formatterDay.format(new Date(entry.date * 1000L))); + dateTextView.setText(LocaleController.getInstance().getFormatterGiveawayCard().format(new Date(entry.date * 1000L)) + ", " + LocaleController.getInstance().getFormatterDay().format(new Date(entry.date * 1000L))); if (!TextUtils.isEmpty(entry.country)) { countryTextView.setText(Emoji.replaceEmoji(LocationController.countryCodeToEmoji(entry.country) + " " + new Locale("", entry.country).getDisplayCountry(), countryTextView.getPaint().getFontMetricsInt(), false)); } else {