正在查看: Plus 12 v10.13.1.1 应用的 AndroidUtilities.java JAVA 源代码文件
本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。
正在查看: Plus 12 v10.13.1.1 应用的 AndroidUtilities.java JAVA 源代码文件
本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。
package org.telegram.messenger;
import android.R;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.Vibrator;
import android.provider.CallLog;
import android.provider.Settings;
import android.system.ErrnoException;
import android.system.OsConstants;
import android.telephony.TelephonyManager;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.util.StateSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.PixelCopy;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.view.inspector.WindowInspector;
import android.webkit.MimeTypeMap;
import android.widget.AbsListView;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
import androidx.core.widget.NestedScrollView;
import androidx.dynamicanimation.animation.DynamicAnimation;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import androidx.exifinterface.media.ExifInterface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.android.internal.telephony.ITelephony;
import com.google.android.exoplayer2.util.Consumer;
import com.google.android.gms.auth.api.phone.SmsRetriever;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.AndroidUtilities$;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.SharedConfig;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.browser.Browser;
import org.telegram.messenger.utils.CustomHtml;
import org.telegram.plus.AnalyticsHelper;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.tgnet.TLRPC$Document;
import org.telegram.tgnet.TLRPC$User;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.BottomSheet;
import org.telegram.ui.ActionBar.INavigationLayout;
import org.telegram.ui.ActionBar.PlusSettings;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.TextDetailSettingsCell;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.ChatBackgroundDrawable;
import org.telegram.ui.Components.BackgroundGradientDrawable;
import org.telegram.ui.Components.ColoredImageSpan;
import org.telegram.ui.Components.CubicBezierInterpolator;
import org.telegram.ui.Components.EllipsizeSpanAnimator;
import org.telegram.ui.Components.ForegroundColorSpanThemable;
import org.telegram.ui.Components.ForegroundDetector;
import org.telegram.ui.Components.HideViewAfterAnimation;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.MotionBackgroundDrawable;
import org.telegram.ui.Components.PickerBottomLayout;
import org.telegram.ui.Components.PipRoundVideoView;
import org.telegram.ui.Components.RecyclerListView;
import org.telegram.ui.Components.ShareAlert;
import org.telegram.ui.Components.TypefaceSpan;
import org.telegram.ui.Components.URLSpanReplacement;
import org.telegram.ui.Components.UndoView;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.Stories.PeerStoriesView;
import org.telegram.ui.Stories.StoryMediaAreasView;
import org.telegram.ui.ThemePreviewActivity;
import org.telegram.ui.WallpapersListActivity;
public class AndroidUtilities {
public static Pattern BAD_CHARS_MESSAGE_LONG_PATTERN = null;
public static Pattern BAD_CHARS_MESSAGE_PATTERN = null;
public static Pattern BAD_CHARS_PATTERN = null;
public static final int DARK_STATUS_BAR_OVERLAY = 855638016;
public static final int FLAG_TAG_ALL = 11;
public static final int FLAG_TAG_BOLD = 2;
public static final int FLAG_TAG_BR = 1;
public static final int FLAG_TAG_COLOR = 4;
public static final int FLAG_TAG_URL = 8;
public static final int LIGHT_STATUS_BAR_OVERLAY = 251658240;
public static Pattern LONG_BAD_CHARS_PATTERN = null;
public static final int REPLACING_TAG_TYPE_BOLD = 1;
public static final int REPLACING_TAG_TYPE_LINK = 0;
public static final int REPLACING_TAG_TYPE_LINKBOLD = 2;
public static final int REPLACING_TAG_TYPE_LINK_NBSP = 3;
public static final String STICKERS_PLACEHOLDER_PACK_NAME = "tg_placeholders_android";
public static final String STICKERS_PLACEHOLDER_PACK_NAME_2 = "tg_superplaceholders_android_2";
public static final String THEME_PREFS = "theme";
public static final int THEME_PREFS_MODE = 0;
public static final String TYPEFACE_COURIER_NEW_BOLD = "fonts/courier_new_bold.ttf";
public static final String TYPEFACE_MERRIWEATHER_BOLD = "fonts/mw_bold.ttf";
public static final String TYPEFACE_ROBOTO_MEDIUM = "fonts/rmedium.ttf";
public static final String TYPEFACE_ROBOTO_MEDIUM_ITALIC = "fonts/rmediumitalic.ttf";
public static final String TYPEFACE_ROBOTO_MONO = "fonts/rmono.ttf";
public static Pattern WEB_URL = null;
private static AccessibilityManager accessibilityManager = null;
private static CallReceiver callReceiver = null;
private static char[] characters = null;
private static HashSet<Character> charactersMap = null;
public static final int defColor = -16738680;
private static int[] documentIcons;
private static int[] documentMediaIcons;
public static boolean firstConfigurationWas;
private static SimpleDateFormat generatingVideoPathFormat;
private static boolean hasCallPermissions;
public static boolean incorrectDisplaySizeFix;
private static Boolean isHonor;
public static boolean isInMultiwindow;
public static int leftBaseline;
private static Pattern linksPattern;
private static Field mAttachInfoField;
private static Field mStableInsetsField;
public static boolean makingGlobalBlurBitmap;
private static HashMap<String, String> map;
private static Typeface mediumTypeface;
private static HashMap<Window, ValueAnimator> navigationBarColorAnimators;
public static final String[] numbersSignatureArray;
public static int roundMessageInset;
public static int roundMessageSize;
public static int roundPlayingMessageSize;
public static final Linkify.MatchFilter sUrlMatchFilter;
public static float touchSlop;
private static Runnable unregisterRunnable;
private static Pattern uriParse;
public static boolean usingHardwareInput;
private static Vibrator vibrator;
public static int themeColor = getIntColor("themeColor");
public static boolean needRestart = false;
public static boolean playingAGame = false;
public static boolean themeUpdated = false;
public static long lastCheck = -1;
private static final Hashtable<String, Typeface> typefaceCache = new Hashtable<>();
private static int prevOrientation = -10;
private static boolean waitingForSms = false;
private static boolean waitingForCall = false;
private static final Object smsLock = new Object();
private static final Object callLock = new Object();
public static int statusBarHeight = 0;
public static int navigationBarHeight = 0;
public static float density = 1.0f;
public static Point displaySize = new Point();
public static float screenRefreshRate = 60.0f;
public static float screenRefreshTime = 1000.0f / 60.0f;
public static Integer photoSize = null;
public static DisplayMetrics displayMetrics = new DisplayMetrics();
public static DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
public static AccelerateInterpolator accelerateInterpolator = new AccelerateInterpolator();
public static OvershootInterpolator overshootInterpolator = new OvershootInterpolator();
private static Boolean isTablet = null;
private static Boolean wasTablet = null;
private static Boolean isSmallScreen = null;
private static int adjustOwnerClassGuid = 0;
private static int altFocusableClassGuid = 0;
public static final RectF rectTmp = new RectF();
public static final Rect rectTmp2 = new Rect();
public static final int[] pointTmp2 = new int[2];
private static Pattern singleTagPatter = null;
public static int compare(int lhs, int rhs) {
if (lhs == rhs) {
return 0;
}
return lhs > rhs ? 1 : -1;
}
public static int compare(long lhs, long rhs) {
if (lhs == rhs) {
return 0;
}
return lhs > rhs ? 1 : -1;
}
public static int getMyLayerVersion(int layer) {
return layer & 65535;
}
public static int getWallpaperRotation(int angle, boolean iOS) {
int i = iOS ? angle + 180 : angle - 180;
while (i >= 360) {
i -= 360;
}
while (i < 0) {
i += 360;
}
return i;
}
public static boolean isValidWallChar(char ch) {
return ch == '-' || ch == '~';
}
public static String lambda$formatSpannableSimple$13(Integer num) {
return "%s";
}
public static float lerp(float a, float b, float f) {
return a + (f * (b - a));
}
public static int lerp(int a, int b, float f) {
return (int) (a + (f * (b - a)));
}
public static float lerpAngle(float a, float b, float f) {
return ((a + ((((((b - a) + 360.0f) + 180.0f) % 360.0f) - 180.0f) * f)) + 360.0f) % 360.0f;
}
public static int setMyLayerVersion(int layer, int version) {
return (layer & (-65536)) | version;
}
public static int setPeerLayerVersion(int layer, int version) {
return (layer & 65535) | (version << 16);
}
static {
WEB_URL = null;
BAD_CHARS_PATTERN = null;
LONG_BAD_CHARS_PATTERN = null;
BAD_CHARS_MESSAGE_PATTERN = null;
BAD_CHARS_MESSAGE_LONG_PATTERN = null;
try {
BAD_CHARS_PATTERN = Pattern.compile("[─-◿]");
LONG_BAD_CHARS_PATTERN = Pattern.compile("[一-\u9fff]");
BAD_CHARS_MESSAGE_LONG_PATTERN = Pattern.compile("[̀-ͯ\u2066-\u2067]+");
BAD_CHARS_MESSAGE_PATTERN = Pattern.compile("[\u2066-\u2067]+");
WEB_URL = Pattern.compile("((?:(http|https|Http|Https|ton|tg):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:" + Pattern.compile("(([a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef]([a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef\\-]{0,61}[a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef]){0,1}\\.)+[a-zA-Z -\ud7ff豈-\ufdcfﷰ-\uffef]{2,63}|" + Pattern.compile("((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))") + ")") + ")(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
} catch (Exception e) {
FileLog.e(e);
}
leftBaseline = isTablet() ? 80 : 72;
checkDisplaySize(ApplicationLoader.applicationContext, null);
documentIcons = new int[]{R.drawable.media_doc_blue, R.drawable.media_doc_green, R.drawable.media_doc_red, R.drawable.media_doc_yellow};
documentMediaIcons = new int[]{R.drawable.media_doc_blue_b, R.drawable.media_doc_green_b, R.drawable.media_doc_red_b, R.drawable.media_doc_yellow_b};
sUrlMatchFilter = AndroidUtilities$.ExternalSyntheticLambda4.INSTANCE;
hasCallPermissions = Build.VERSION.SDK_INT >= 23;
numbersSignatureArray = new String[]{"", "K", "M", "B", "T", "P"};
characters = new char[]{160, ' ', '!', '\"', '#', '%', '&', '\'', '(', ')', '*', ',', '-', '.', '/', ':', ';', '?', '@', '[', '\\', ']', '_', '{', '}', 161, 167, 171, 182, 183, 187, 191, 894, 903, 1370, 1371, 1372, 1373, 1374, 1375, 1417, 1418, 1470, 1472, 1475, 1478, 1523, 1524, 1545, 1546, 1548, 1549, 1563, 1566, 1567, 1642, 1643, 1644, 1645, 1748, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 2039, 2040, 2041, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2142, 2404, 2405, 2416, 2557, 2678, 2800, 3191, 3204, 3572, 3663, 3674, 3675, 3844, 3845, 3846, 3847, 3848, 3849, 3850, 3851, 3852, 3853, 3854, 3855, 3856, 3857, 3858, 3860, 3898, 3899, 3900, 3901, 3973, 4048, 4049, 4050, 4051, 4052, 4057, 4058, 4170, 4171, 4172, 4173, 4174, 4175, 4347, 4960, 4961, 4962, 4963, 4964, 4965, 4966, 4967, 4968, 5120, 5742, 5787, 5788, 5867, 5868, 5869, 5941, 5942, 6100, 6101, 6102, 6104, 6105, 6106, 6144, 6145, 6146, 6147, 6148, 6149, 6150, 6151, 6152, 6153, 6154, 6468, 6469, 6686, 6687, 6816, 6817, 6818, 6819, 6820, 6821, 6822, 6824, 6825, 6826, 6827, 6828, 6829, 7002, 7003, 7004, 7005, 7006, 7007, 7008, 7164, 7165, 7166, 7167, 7227, 7228, 7229, 7230, 7231, 7294, 7295, 7360, 7361, 7362, 7363, 7364, 7365, 7366, 7367, 7379, 8208, 8209, 8210, 8211, 8212, 8213, 8214, 8215, 8216, 8217, 8218, 8219, 8220, 8221, 8222, 8223, 8224, 8225, 8226, 8227, 8228, 8229, 8230, 8231, 8240, 8241, 8242, 8243, 8244, 8245, 8246, 8247, 8248, 8249, 8250, 8251, 8252, 8253, 8254, 8255, 8256, 8257, 8258, 8259, 8261, 8262, 8263, 8264, 8265, 8266, 8267, 8268, 8269, 8270, 8271, 8272, 8273, 8275, 8276, 8277, 8278, 8279, 8280, 8281, 8282, 8283, 8284, 8285, 8286, 8317, 8318, 8333, 8334, 8968, 8969, 8970, 8971, 9001, 9002, 10088, 10089, 10090, 10091, 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, 10181, 10182, 10214, 10215, 10216, 10217, 10218, 10219, 10220, 10221, 10222, 10223, 10627, 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637, 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647, 10648, 10712, 10713, 10714, 10715, 10748, 10749, 11513, 11514, 11515, 11516, 11518, 11519, 11632, 11776, 11777, 11778, 11779, 11780, 11781, 11782, 11783, 11784, 11785, 11786, 11787, 11788, 11789, 11790, 11791, 11792, 11793, 11794, 11795, 11796, 11797, 11798, 11799, 11800, 11801, 11802, 11803, 11804, 11805, 11806, 11807, 11808, 11809, 11810, 11811, 11812, 11813, 11814, 11815, 11816, 11817, 11818, 11819, 11820, 11821, 11822, 11824, 11825, 11826, 11827, 11828, 11829, 11830, 11831, 11832, 11833, 11834, 11835, 11836, 11837, 11838, 11839, 11840, 11841, 11842, 11843, 11844, 11845, 11846, 11847, 11848, 11849, 11850, 11851, 11852, 11853, 11854, 11855, 12289, 12290, 12291, 12296, 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317, 12318, 12319, 12336, 12349, 12448, 12539, 42238, 42239, 42509, 42510, 42511, 42611, 42622, 42738, 42739, 42740, 42741, 42742, 42743, 43124, 43125, 43126, 43127, 43214, 43215, 43256, 43257, 43258, 43260, 43310, 43311, 43359, 43457, 43458, 43459, 43460, 43461, 43462, 43463, 43464, 43465, 43466, 43467, 43468, 43469, 43486, 43487, 43612, 43613, 43614, 43615, 43742, 43743, 43760, 43761, 44011, 64830, 64831, 65040, 65041, 65042, 65043, 65044, 65045, 65046, 65047, 65048, 65049, 65072, 65073, 65074, 65075, 65076, 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086, 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65094, 65095, 65096, 65097, 65098, 65099, 65100, 65101, 65102, 65103, 65104, 65105, 65106, 65108, 65109, 65110, 65111, 65112, 65113, 65114, 65115, 65116, 65117, 65118, 65119, 65120, 65121, 65123, 65128, 65130, 65131, 65281, 65282, 65283, 65285, 65286, 65287, 65288, 65289, 65290, 65292, 65293, 65294, 65295, 65306, 65307, 65311, 65312, 65339, 65340, 65341, 65343, 65371, 65373, 65375, 65376, 65377, 65378, 65379, 65380, 65381};
map = new HashMap<>();
}
public static Typeface bold() {
Typeface typeface = mediumTypeface;
if (typeface == null && typeface == null) {
mediumTypeface = getTypeface(TYPEFACE_ROBOTO_MEDIUM);
}
return mediumTypeface;
}
private static boolean containsUnsupportedCharacters(String text) {
if (text.contains("\u202c") || text.contains("\u202d") || text.contains("\u202e")) {
return true;
}
try {
return BAD_CHARS_PATTERN.matcher(text).find();
} catch (Throwable unused) {
return true;
}
}
public static String getSafeString(String str) {
try {
return BAD_CHARS_MESSAGE_PATTERN.matcher(str).replaceAll("\u200c");
} catch (Throwable unused) {
return str;
}
}
public static CharSequence ellipsizeCenterEnd(CharSequence str, String query, int availableWidth, TextPaint textPaint, int maxSymbols) {
int indexOf;
StaticLayout staticLayout;
float lineWidth;
float f;
CharSequence subSequence;
try {
int length = str.length();
indexOf = str.toString().toLowerCase().indexOf(query);
if (length > maxSymbols) {
str = str.subSequence(Math.max(0, indexOf - (maxSymbols / 2)), Math.min(length, (maxSymbols / 2) + indexOf));
indexOf -= Math.max(0, indexOf - (maxSymbols / 2));
str.length();
}
staticLayout = new StaticLayout(str, textPaint, ConnectionsManager.DEFAULT_DATACENTER_ID, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
lineWidth = staticLayout.getLineWidth(0);
f = availableWidth;
} catch (Exception e) {
FileLog.e(e);
}
if (textPaint.measureText("...") + lineWidth < f) {
return str;
}
int i = indexOf + 1;
int i2 = i;
while (i2 < str.length() - 1 && !Character.isWhitespace(str.charAt(i2))) {
i2++;
}
float primaryHorizontal = staticLayout.getPrimaryHorizontal(i2);
if (staticLayout.isRtlCharAt(i2)) {
primaryHorizontal = lineWidth - primaryHorizontal;
}
if (primaryHorizontal < f) {
return str;
}
float measureText = (primaryHorizontal - f) + (textPaint.measureText("...") * 2.0f);
float f2 = 0.1f * f;
float f3 = measureText + f2;
if (str.length() - i2 > 20) {
f3 += f2;
}
if (f3 > 0.0f) {
int offsetForHorizontal = staticLayout.getOffsetForHorizontal(0, f3);
if (offsetForHorizontal > str.length() - 1) {
offsetForHorizontal = str.length() - 1;
}
int i3 = 0;
while (true) {
if (Character.isWhitespace(str.charAt(offsetForHorizontal)) || i3 >= 10) {
break;
}
i3++;
offsetForHorizontal++;
if (offsetForHorizontal > str.length() - 1) {
offsetForHorizontal = staticLayout.getOffsetForHorizontal(0, f3);
break;
}
}
if (i3 >= 10) {
subSequence = str.subSequence(staticLayout.getOffsetForHorizontal(0, staticLayout.getPrimaryHorizontal(i) - (f * 0.3f)), str.length());
} else {
if (offsetForHorizontal > 0 && offsetForHorizontal < str.length() - 2 && Character.isWhitespace(str.charAt(offsetForHorizontal))) {
offsetForHorizontal++;
}
subSequence = str.subSequence(offsetForHorizontal, str.length());
}
return SpannableStringBuilder.valueOf("...").append(subSequence);
}
return str;
}
public static CharSequence highlightText(CharSequence str, ArrayList<String> query, Theme.ResourcesProvider resourcesProvider) {
if (query == null) {
return null;
}
int i = 0;
for (int i2 = 0; i2 < query.size(); i2++) {
CharSequence highlightText = highlightText(str, query.get(i2), resourcesProvider);
if (highlightText != null) {
str = highlightText;
} else {
i++;
}
}
if (i == query.size()) {
return null;
}
return str;
}
public static CharSequence highlightText(CharSequence str, String query, Theme.ResourcesProvider resourcesProvider) {
if (TextUtils.isEmpty(query) || TextUtils.isEmpty(str)) {
return null;
}
String lowerCase = str.toString().toLowerCase();
SpannableStringBuilder valueOf = SpannableStringBuilder.valueOf(str);
int indexOf = lowerCase.indexOf(query);
while (indexOf >= 0) {
try {
valueOf.setSpan(new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4, resourcesProvider), indexOf, Math.min(query.length() + indexOf, str.length()), 0);
} catch (Exception e) {
FileLog.e(e);
}
indexOf = lowerCase.indexOf(query, indexOf + 1);
}
return valueOf;
}
public static Activity findActivity(Context context) {
if (context instanceof Activity) {
return (Activity) context;
}
if (context instanceof ContextWrapper) {
return findActivity(((ContextWrapper) context).getBaseContext());
}
return null;
}
public static SpannableStringBuilder premiumText(String str, Runnable runnable) {
return replaceSingleTag(str, -1, 2, runnable);
}
public static SpannableStringBuilder replaceSingleTag(String str, Runnable runnable) {
return replaceSingleTag(str, -1, 0, runnable);
}
public static SpannableStringBuilder replaceSingleTag(String str, int colorKey, int type, Runnable runnable) {
return replaceSingleTag(str, colorKey, type, runnable, null);
}
public static SpannableStringBuilder replaceSingleTag(String str, int colorKey, int type, Runnable runnable, Theme.ResourcesProvider resourcesProvider) {
int i;
int i2;
int indexOf = str.indexOf("**");
int indexOf2 = str.indexOf("**", indexOf + 1);
String replace = str.replace("**", "");
if (indexOf < 0 || indexOf2 < 0 || (i2 = indexOf2 - indexOf) <= 2) {
indexOf = -1;
i = 0;
} else {
i = i2 - 2;
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(replace);
if (indexOf >= 0) {
if (type == 3) {
int i3 = indexOf + i;
spannableStringBuilder.replace(indexOf, i3, replaceMultipleCharSequence(" ", spannableStringBuilder.subSequence(indexOf, i3), " "));
}
if (type == 0 || type == 3 || type == 2) {
spannableStringBuilder.setSpan(new 1(colorKey, resourcesProvider, type, runnable), indexOf, i + indexOf, 0);
} else {
spannableStringBuilder.setSpan(new 2(resourcesProvider), indexOf, i + indexOf, 0);
}
}
return spannableStringBuilder;
}
public static SpannableStringBuilder replaceSingleLink(String str, int color) {
return replaceSingleLink(str, color, null);
}
public static SpannableStringBuilder replaceSingleLink(String str, int color, Runnable onClick) {
int i;
int i2;
int indexOf = str.indexOf("**");
int indexOf2 = str.indexOf("**", indexOf + 1);
String replace = str.replace("**", "");
if (indexOf < 0 || indexOf2 < 0 || (i2 = indexOf2 - indexOf) <= 2) {
indexOf = -1;
i = 0;
} else {
i = i2 - 2;
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(replace);
if (indexOf >= 0) {
spannableStringBuilder.setSpan(new 3(color, onClick), indexOf, i + indexOf, 0);
}
return spannableStringBuilder;
}
public static CharSequence replaceArrows(CharSequence text, boolean link) {
return replaceArrows(text, link, dp(2.6666667f), 0.0f);
}
public static CharSequence replaceArrows(CharSequence text, boolean link, float translateX, float translateY) {
int i = R.drawable.msg_mini_forumarrow;
ColoredImageSpan coloredImageSpan = new ColoredImageSpan(i, 0);
coloredImageSpan.setScale(0.88f, 0.88f);
coloredImageSpan.translate(-translateX, translateY);
coloredImageSpan.spaceScaleX = 0.8f;
if (link) {
coloredImageSpan.useLinkPaintColor = link;
}
SpannableString spannableString = new SpannableString(" >");
spannableString.setSpan(coloredImageSpan, spannableString.length() - 1, spannableString.length(), 33);
CharSequence replaceMultipleCharSequence = replaceMultipleCharSequence(" >", text, spannableString);
SpannableString spannableString2 = new SpannableString(">");
spannableString2.setSpan(coloredImageSpan, 0, 1, 33);
CharSequence replaceMultipleCharSequence2 = replaceMultipleCharSequence(">", replaceMultipleCharSequence, spannableString2);
ColoredImageSpan coloredImageSpan2 = new ColoredImageSpan(i, 0);
coloredImageSpan2.setScale(0.88f, 0.88f);
coloredImageSpan2.translate(translateX, translateY);
coloredImageSpan2.rotate(180.0f);
coloredImageSpan2.spaceScaleX = 0.8f;
if (link) {
coloredImageSpan2.useLinkPaintColor = link;
}
SpannableString spannableString3 = new SpannableString("<");
spannableString3.setSpan(coloredImageSpan2, 0, 1, 33);
return replaceMultipleCharSequence("<", replaceMultipleCharSequence2, spannableString3);
}
public static void recycleBitmaps(List<Bitmap> bitmapToRecycle) {
if (Build.VERSION.SDK_INT <= 23 || bitmapToRecycle == null || bitmapToRecycle.isEmpty()) {
return;
}
ArrayList arrayList = new ArrayList();
for (int i = 0; i < bitmapToRecycle.size(); i++) {
Bitmap bitmap = bitmapToRecycle.get(i);
if (bitmap != null && !bitmap.isRecycled()) {
arrayList.add(new WeakReference(bitmap));
}
}
runOnUIThread(new AndroidUtilities$.ExternalSyntheticLambda15(arrayList), 36L);
}
public static void lambda$recycleBitmaps$1(ArrayList arrayList) {
Utilities.globalQueue.postRunnable(new AndroidUtilities$.ExternalSyntheticLambda14(arrayList));
}
public static void lambda$recycleBitmaps$0(ArrayList arrayList) {
for (int i = 0; i < arrayList.size(); i++) {
Bitmap bitmap = (Bitmap) ((WeakReference) arrayList.get(i)).get();
((WeakReference) arrayList.get(i)).clear();
if (bitmap != null && !bitmap.isRecycled()) {
try {
bitmap.recycle();
} catch (Exception e) {
FileLog.e(e);
}
}
}
}
public static void googleVoiceClientService_performAction(Intent intent, boolean isVerified, Bundle options) {
if (isVerified) {
runOnUIThread(new AndroidUtilities$.ExternalSyntheticLambda13(intent));
}
}
public static void lambda$googleVoiceClientService_performAction$2(Intent intent) {
try {
int i = UserConfig.selectedAccount;
ApplicationLoader.postInitApplication();
if (!needShowPasscode() && !SharedConfig.isWaitingForPasscodeEnter) {
String stringExtra = intent.getStringExtra("android.intent.extra.TEXT");
if (TextUtils.isEmpty(stringExtra)) {
return;
}
String stringExtra2 = intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_URI");
long parseLong = Long.parseLong(intent.getStringExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID"));
TLRPC$User user = MessagesController.getInstance(i).getUser(Long.valueOf(parseLong));
if (user == null && (user = MessagesStorage.getInstance(i).getUserSync(parseLong)) != null) {
MessagesController.getInstance(i).putUser(user, true);
}
if (user != null) {
ContactsController.getInstance(i).markAsContacted(stringExtra2);
SendMessagesHelper.getInstance(i).sendMessage(SendMessagesHelper.SendMessageParams.of(stringExtra, user.id, (MessageObject) null, (MessageObject) null, (TLRPC.WebPage) null, true, (ArrayList) null, (TLRPC.ReplyMarkup) null, (HashMap) null, true, 0, (MessageObject.SendAnimationData) null, false));
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
public static void recycleBitmap(Bitmap image) {
recycleBitmaps(Collections.singletonList(image));
}
public static boolean findClickableView(ViewGroup container, float x, float y) {
return findClickableView(container, x, y, null);
}
public static boolean findClickableView(ViewGroup container, float x, float y, View onlyThisView) {
if (container == null) {
return false;
}
for (int i = 0; i < container.getChildCount(); i++) {
View childAt = container.getChildAt(i);
if (childAt.getVisibility() == 0 && (!(childAt instanceof PeerStoriesView) || childAt == onlyThisView)) {
if (childAt instanceof StoryMediaAreasView.AreaView) {
StoryMediaAreasView storyMediaAreasView = (StoryMediaAreasView) container;
if ((!storyMediaAreasView.hasSelected() || (x >= dp(60.0f) && x <= container.getWidth() - dp(60.0f))) && !storyMediaAreasView.hasAreaAboveAt(x, y)) {
}
}
Rect rect = rectTmp2;
childAt.getHitRect(rect);
if (rect.contains((int) x, (int) y) && childAt.isClickable()) {
return true;
}
if ((childAt instanceof ViewGroup) && findClickableView((ViewGroup) childAt, x - childAt.getX(), y - childAt.getY(), onlyThisView)) {
return true;
}
}
}
return false;
}
public static void removeFromParent(View child) {
if (child == null || child.getParent() == null) {
return;
}
((ViewGroup) child.getParent()).removeView(child);
}
public static boolean isFilNotFoundException(Throwable e) {
return (e instanceof FileNotFoundException) || (e instanceof EOFException);
}
public static File getLogsDir() {
try {
if ("mounted".equals(Environment.getExternalStorageState())) {
File file = new File(ApplicationLoader.applicationContext.getExternalFilesDir(null).getAbsolutePath() + "/logs");
file.mkdirs();
return file;
}
} catch (Exception unused) {
}
try {
try {
File file2 = new File(ApplicationLoader.applicationContext.getCacheDir() + "/logs");
file2.mkdirs();
return file2;
} catch (Exception unused2) {
File file3 = new File(ApplicationLoader.applicationContext.getFilesDir() + "/logs");
file3.mkdirs();
return file3;
}
} catch (Exception unused3) {
ApplicationLoader.appCenterLog(new RuntimeException("can't create logs directory"));
return null;
}
}
public static String formatVideoDurationFast(int minutes, int seconds) {
StringBuilder sb = new StringBuilder();
if (minutes >= 60) {
normalizeTimePart(sb, minutes / 60);
sb.append(":");
normalizeTimePart(sb, minutes % 60);
sb.append(":");
normalizeTimePart(sb, seconds);
} else {
normalizeTimePart(sb, minutes);
sb.append(":");
normalizeTimePart(sb, seconds);
}
return sb.toString();
}
public static String formatTimerDurationFast(long seconds, int ms) {
StringBuilder sb = new StringBuilder();
long j = seconds / 60;
if (j >= 60) {
sb.append(j / 60);
sb.append(":");
normalizeTimePart(sb, j % 60);
sb.append(":");
normalizeTimePart(sb, seconds % 60);
sb.append(",");
sb.append(ms / 10);
} else {
sb.append(j);
sb.append(":");
normalizeTimePart(sb, seconds % 60);
sb.append(",");
sb.append(ms / 10);
}
return sb.toString();
}
public static void normalizeTimePart(StringBuilder stringBuilder, int time) {
if (time < 10) {
stringBuilder.append("0");
stringBuilder.append(time);
} else {
stringBuilder.append(time);
}
}
public static void normalizeTimePart(StringBuilder stringBuilder, long time) {
if (time < 10) {
stringBuilder.append("0");
stringBuilder.append(time);
} else {
stringBuilder.append(time);
}
}
public static void getViewPositionInParent(View view, ViewGroup parent, float[] pointPosition) {
pointPosition[0] = 0.0f;
pointPosition[1] = 0.0f;
if (view == null || parent == null) {
return;
}
while (view != parent) {
if (!(view.getParent() instanceof ViewPager)) {
pointPosition[0] = pointPosition[0] + view.getX();
pointPosition[1] = pointPosition[1] + view.getY();
}
view = (View) view.getParent();
}
}
public static MotionEvent emptyMotionEvent() {
return MotionEvent.obtain(0L, 0L, 3, 0.0f, 0.0f, 0);
}
public static boolean isDarkColor(int color) {
return computePerceivedBrightness(color) < 0.721f;
}
public static void getBitmapFromSurface(SurfaceView surfaceView, Bitmap surfaceBitmap) {
if (surfaceView == null || !surfaceView.getHolder().getSurface().isValid()) {
return;
}
CountDownLatch countDownLatch = new CountDownLatch(1);
PixelCopy.request(surfaceView, surfaceBitmap, (PixelCopy.OnPixelCopyFinishedListener) new AndroidUtilities$.ExternalSyntheticLambda6(countDownLatch), Utilities.searchQueue.getHandler());
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void getBitmapFromSurface(Surface surface, Bitmap surfaceBitmap) {
if (surface == null || !surface.isValid()) {
return;
}
CountDownLatch countDownLatch = new CountDownLatch(1);
PixelCopy.request(surface, surfaceBitmap, (PixelCopy.OnPixelCopyFinishedListener) new AndroidUtilities$.ExternalSyntheticLambda5(countDownLatch), Utilities.searchQueue.getHandler());
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static float[] getCoordinateInParent(ViewGroup parentView, View view) {
float f;
float f2 = 0.0f;
if (view != null && parentView != null) {
f = 0.0f;
float f3 = 0.0f;
while (view != parentView) {
if (view != null) {
f += view.getY();
f3 += view.getX();
if (view instanceof NestedScrollView) {
f -= view.getScrollY();
f3 -= view.getScrollX();
}
if (view.getParent() instanceof View) {
view = (View) view.getParent();
}
}
}
f2 = f3;
return new float[]{f2, f};
}
f = 0.0f;
return new float[]{f2, f};
}
public static void doOnLayout(View view, Runnable runnable) {
view.addOnLayoutChangeListener(new 4(view, runnable));
}
private static String makeUrl(String url, String[] prefixes, Matcher matcher) {
boolean z;
int i = 0;
while (true) {
z = true;
if (i >= prefixes.length) {
z = false;
break;
}
if (!url.regionMatches(true, 0, prefixes[i], 0, prefixes[i].length())) {
i++;
} else if (!url.regionMatches(false, 0, prefixes[i], 0, prefixes[i].length())) {
url = prefixes[i] + url.substring(prefixes[i].length());
}
}
if (z || prefixes.length <= 0) {
return url;
}
return prefixes[0] + url;
}
private static void gatherLinks(ArrayList<LinkSpec> links, Spannable s, Pattern pattern, String[] schemes, Linkify.MatchFilter matchFilter, boolean internalOnly) {
if (TextUtils.indexOf((CharSequence) s, (char) 9472) >= 0) {
s = new SpannableStringBuilder(s.toString().replace((char) 9472, ' '));
}
if (!TextUtils.isEmpty(s) && TextUtils.lastIndexOf(s, '_') == s.length() - 1) {
s = new SpannableStringBuilder(s.toString()).replace(s.length() - 1, s.length(), (CharSequence) "a");
}
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
if (matchFilter == null || matchFilter.acceptMatch(s, start, end)) {
LinkSpec linkSpec = new LinkSpec((LinkSpec-IA) null);
String makeUrl = makeUrl(matcher.group(0), schemes, matcher);
if (!internalOnly || Browser.isInternalUrl(makeUrl, true, (boolean[]) null)) {
linkSpec.url = makeUrl;
linkSpec.start = start;
linkSpec.end = end;
links.add(linkSpec);
}
}
}
}
public static boolean lambda$static$5(CharSequence charSequence, int i, int i2) {
return i == 0 || charSequence.charAt(i - 1) != '@';
}
@Deprecated
public static boolean addLinks(Spannable text, int mask) {
return addLinks(text, mask, false);
}
@Deprecated
public static boolean addLinks(Spannable text, int mask, boolean internalOnly) {
return addLinks(text, mask, internalOnly, true);
}
public static boolean addLinksSafe(Spannable text, int mask, boolean internalOnly, boolean removeOldReplacements) {
if (text == null) {
return false;
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
boolean doSafe = doSafe(new AndroidUtilities$.ExternalSyntheticLambda20(spannableStringBuilder, mask, internalOnly, removeOldReplacements));
if (doSafe) {
for (URLSpan uRLSpan : (URLSpan[]) text.getSpans(0, text.length(), URLSpan.class)) {
text.removeSpan(uRLSpan);
}
URLSpan[] uRLSpanArr = (URLSpan[]) spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), URLSpan.class);
for (int i = 0; i < uRLSpanArr.length; i++) {
text.setSpan(uRLSpanArr[i], spannableStringBuilder.getSpanStart(uRLSpanArr[i]), spannableStringBuilder.getSpanEnd(uRLSpanArr[i]), 33);
}
}
return doSafe;
}
public static Boolean lambda$addLinksSafe$6(SpannableStringBuilder spannableStringBuilder, int i, boolean z, boolean z2) {
return Boolean.valueOf(addLinks(spannableStringBuilder, i, z, z2));
}
public static boolean doSafe(Utilities.Callback0Return<Boolean> runnable) {
return doSafe(runnable, 200);
}
public static boolean doSafe(Utilities.Callback0Return<Boolean> runnable, int timeout) {
Future future;
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
try {
try {
try {
future = newSingleThreadExecutor.submit((Callable) new AndroidUtilities$.ExternalSyntheticLambda17(runnable));
} finally {
newSingleThreadExecutor.shutdownNow();
}
} catch (TimeoutException unused) {
future = null;
}
try {
return ((Boolean) future.get(timeout, TimeUnit.MILLISECONDS)).booleanValue();
} catch (TimeoutException unused2) {
if (future != null) {
future.cancel(true);
}
newSingleThreadExecutor.shutdownNow();
return false;
}
} catch (Exception e) {
FileLog.e(e);
newSingleThreadExecutor.shutdownNow();
return false;
}
}
public static Boolean lambda$doSafe$7(Utilities.Callback0Return callback0Return) throws Exception {
try {
return (Boolean) callback0Return.run();
} catch (Exception e) {
FileLog.e(e);
return Boolean.FALSE;
}
}
@Deprecated
public static boolean addLinks(Spannable text, int mask, boolean internalOnly, boolean removeOldReplacements) {
if (text == null || containsUnsupportedCharacters(text.toString()) || mask == 0) {
return false;
}
URLSpan[] uRLSpanArr = (URLSpan[]) text.getSpans(0, text.length(), URLSpan.class);
for (int length = uRLSpanArr.length - 1; length >= 0; length--) {
URLSpan uRLSpan = uRLSpanArr[length];
if (!(uRLSpan instanceof URLSpanReplacement) || removeOldReplacements) {
text.removeSpan(uRLSpan);
}
}
ArrayList arrayList = new ArrayList();
if (!internalOnly && (mask & 4) != 0) {
Linkify.addLinks(text, 4);
}
if ((mask & 1) != 0) {
gatherLinks(arrayList, text, LinkifyPort.WEB_URL, new String[]{"http://", "https://", "tg://"}, sUrlMatchFilter, internalOnly);
}
pruneOverlaps(arrayList);
if (arrayList.size() == 0) {
return false;
}
int size = arrayList.size();
for (int i = 0; i < size; i++) {
LinkSpec linkSpec = (LinkSpec) arrayList.get(i);
URLSpan[] uRLSpanArr2 = (URLSpan[]) text.getSpans(linkSpec.start, linkSpec.end, URLSpan.class);
if (uRLSpanArr2 != null && uRLSpanArr2.length > 0) {
for (URLSpan uRLSpan2 : uRLSpanArr2) {
text.removeSpan(uRLSpan2);
if (!(uRLSpan2 instanceof URLSpanReplacement) || removeOldReplacements) {
text.removeSpan(uRLSpan2);
}
}
}
String str = linkSpec.url;
if (str != null) {
str = str.replaceAll("∕|⁄|%E2%81%84|%E2%88%95", "/");
}
text.setSpan(new URLSpan(str), linkSpec.start, linkSpec.end, 33);
}
return true;
}
private static void pruneOverlaps(ArrayList<LinkSpec> links) {
int i;
Collections.sort(links, AndroidUtilities$.ExternalSyntheticLambda16.INSTANCE);
int size = links.size();
int i2 = 0;
while (i2 < size - 1) {
LinkSpec linkSpec = links.get(i2);
int i3 = i2 + 1;
LinkSpec linkSpec2 = links.get(i3);
int i4 = linkSpec.start;
int i5 = linkSpec2.start;
if (i4 <= i5 && (i = linkSpec.end) > i5) {
int i6 = linkSpec2.end;
int i7 = (i6 > i && i - i4 <= i6 - i5) ? i - i4 < i6 - i5 ? i2 : -1 : i3;
if (i7 != -1) {
links.remove(i7);
size--;
}
}
i2 = i3;
}
}
public static int lambda$pruneOverlaps$8(LinkSpec linkSpec, LinkSpec linkSpec2) {
int i;
int i2;
int i3 = linkSpec.start;
int i4 = linkSpec2.start;
if (i3 < i4) {
return -1;
}
if (i3 <= i4 && (i = linkSpec.end) >= (i2 = linkSpec2.end)) {
return i > i2 ? -1 : 0;
}
return 1;
}
public static void fillStatusBarHeight(Context context, boolean force) {
if (context != null) {
if (statusBarHeight <= 0 || force) {
statusBarHeight = getStatusBarHeight(context);
navigationBarHeight = getNavigationBarHeight(context);
}
}
}
public static int getStatusBarHeight(Context context) {
int identifier = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (identifier > 0) {
return context.getResources().getDimensionPixelSize(identifier);
}
return 0;
}
private static int getNavigationBarHeight(Context context) {
int identifier = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (identifier > 0) {
return context.getResources().getDimensionPixelSize(identifier);
}
return 0;
}
public static int getThumbForNameOrMime(String name, String mime, boolean media) {
int i;
if (name == null || name.length() == 0) {
return media ? documentMediaIcons[0] : documentIcons[0];
}
if (name.contains(".doc") || name.contains(".txt") || name.contains(".psd")) {
i = 0;
} else if (name.contains(".xls") || name.contains(".csv")) {
i = 1;
} else if (name.contains(".pdf") || name.contains(".ppt") || name.contains(".key")) {
i = 2;
} else {
i = (name.contains(".zip") || name.contains(".rar") || name.contains(".ai") || name.contains(".mp3") || name.contains(".mov") || name.contains(".avi")) ? 3 : -1;
}
if (i == -1) {
int lastIndexOf = name.lastIndexOf(46);
String substring = lastIndexOf == -1 ? "" : name.substring(lastIndexOf + 1);
if (substring.length() != 0) {
i = substring.charAt(0) % documentIcons.length;
} else {
i = name.charAt(0) % documentIcons.length;
}
}
return media ? documentMediaIcons[i] : documentIcons[i];
}
public static int calcBitmapColor(Bitmap bitmap) {
if (bitmap == null) {
return 0;
}
try {
Bitmap createScaledBitmap = Bitmaps.createScaledBitmap(bitmap, 1, 1, true);
if (createScaledBitmap != null) {
int pixel = createScaledBitmap.getPixel(0, 0);
if (bitmap != createScaledBitmap) {
createScaledBitmap.recycle();
}
return pixel;
}
} catch (Exception e) {
FileLog.e(e);
}
return 0;
}
public static int[] calcDrawableColor(Drawable drawable) {
int i;
if (drawable instanceof ChatBackgroundDrawable) {
return calcDrawableColor(((ChatBackgroundDrawable) drawable).getDrawable(true));
}
int i2 = -16777216;
int[] iArr = new int[4];
try {
if (drawable instanceof BitmapDrawable) {
i2 = calcBitmapColor(((BitmapDrawable) drawable).getBitmap());
} else if (drawable instanceof ColorDrawable) {
i2 = ((ColorDrawable) drawable).getColor();
} else if (drawable instanceof BackgroundGradientDrawable) {
int[] colorsList = ((BackgroundGradientDrawable) drawable).getColorsList();
if (colorsList != null) {
if (colorsList.length > 1) {
i = getAverageColor(colorsList[0], colorsList[1]);
} else if (colorsList.length > 0) {
i = colorsList[0];
}
i2 = i;
}
} else if (drawable instanceof MotionBackgroundDrawable) {
int argb = Color.argb(45, 0, 0, 0);
iArr[2] = argb;
iArr[0] = argb;
int argb2 = Color.argb(61, 0, 0, 0);
iArr[3] = argb2;
iArr[1] = argb2;
return iArr;
}
} catch (Exception e) {
FileLog.e(e);
}
double[] rgbToHsv = rgbToHsv((i2 >> 16) & 255, (i2 >> 8) & 255, i2 & 255);
rgbToHsv[1] = Math.min(1.0d, rgbToHsv[1] + 0.05d + ((1.0d - rgbToHsv[1]) * 0.1d));
int[] hsvToRgb = hsvToRgb(rgbToHsv[0], rgbToHsv[1], Math.max(0.0d, rgbToHsv[2] * 0.65d));
iArr[0] = Color.argb(102, hsvToRgb[0], hsvToRgb[1], hsvToRgb[2]);
iArr[1] = Color.argb(136, hsvToRgb[0], hsvToRgb[1], hsvToRgb[2]);
int[] hsvToRgb2 = hsvToRgb(rgbToHsv[0], rgbToHsv[1], Math.max(0.0d, rgbToHsv[2] * 0.72d));
iArr[2] = Color.argb(102, hsvToRgb2[0], hsvToRgb2[1], hsvToRgb2[2]);
iArr[3] = Color.argb(136, hsvToRgb2[0], hsvToRgb2[1], hsvToRgb2[2]);
return iArr;
}
public static double[] rgbToHsv(int color) {
return rgbToHsv(Color.red(color), Color.green(color), Color.blue(color));
}
public static double[] rgbToHsv(int r, int g, int b) {
double d;
double d2;
double d3;
double d4 = r;
Double.isNaN(d4);
double d5 = d4 / 255.0d;
double d6 = g;
Double.isNaN(d6);
double d7 = d6 / 255.0d;
double d8 = b;
Double.isNaN(d8);
double d9 = d8 / 255.0d;
double max = (d5 <= d7 || d5 <= d9) ? Math.max(d7, d9) : d5;
double min = (d5 >= d7 || d5 >= d9) ? Math.min(d7, d9) : d5;
double d10 = max - min;
double d11 = 0.0d;
double d12 = max == 0.0d ? 0.0d : d10 / max;
if (max != min) {
if (d5 > d7 && d5 > d9) {
d = (d7 - d9) / d10;
d2 = d7 < d9 ? 6 : 0;
Double.isNaN(d2);
} else if (d7 > d9) {
d3 = 2.0d + ((d9 - d5) / d10);
d11 = d3 / 6.0d;
} else {
d = (d5 - d7) / d10;
d2 = 4.0d;
}
d3 = d + d2;
d11 = d3 / 6.0d;
}
return new double[]{d11, d12, max};
}
public static int hsvToColor(double h, double s, double v) {
int[] hsvToRgb = hsvToRgb(h, s, v);
return Color.argb(255, hsvToRgb[0], hsvToRgb[1], hsvToRgb[2]);
}
public static int[] hsvToRgb(double h, double s, double v) {
double d = 6.0d * h;
double floor = (int) Math.floor(d);
Double.isNaN(floor);
double d2 = d - floor;
double d3 = (1.0d - s) * v;
double d4 = (1.0d - (d2 * s)) * v;
double d5 = v * (1.0d - ((1.0d - d2) * s));
int i = ((int) floor) % 6;
double d6 = 0.0d;
if (i != 0) {
if (i == 1) {
d6 = v;
d5 = d3;
d3 = d4;
} else if (i == 2) {
d6 = v;
} else if (i == 3) {
d5 = v;
d6 = d4;
} else if (i == 4) {
d6 = d3;
d3 = d5;
d5 = v;
} else if (i != 5) {
d5 = 0.0d;
d3 = 0.0d;
} else {
d6 = d3;
d5 = d4;
}
return new int[]{(int) (d3 * 255.0d), (int) (d6 * 255.0d), (int) (d5 * 255.0d)};
}
d6 = d5;
d5 = d3;
d3 = v;
return new int[]{(int) (d3 * 255.0d), (int) (d6 * 255.0d), (int) (d5 * 255.0d)};
}
public static void adjustSaturationColorMatrix(ColorMatrix colorMatrix, float saturation) {
if (colorMatrix == null) {
return;
}
float f = saturation + 1.0f;
float f2 = 1.0f - f;
float f3 = 0.3086f * f2;
float f4 = 0.6094f * f2;
float f5 = f2 * 0.082f;
colorMatrix.postConcat(new ColorMatrix(new float[]{f3 + f, f4, f5, 0.0f, 0.0f, f3, f4 + f, f5, 0.0f, 0.0f, f3, f4, f5 + f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}));
}
public static void adjustBrightnessColorMatrix(ColorMatrix colorMatrix, float brightness) {
if (colorMatrix == null) {
return;
}
float f = brightness * 255.0f;
colorMatrix.postConcat(new ColorMatrix(new float[]{1.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 1.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 1.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}));
}
public static void adjustHueColorMatrix(ColorMatrix cm, float value) {
float cleanValue = (cleanValue(value, 180.0f) / 180.0f) * 3.1415927f;
if (cleanValue == 0.0f) {
return;
}
double d = cleanValue;
float cos = (float) Math.cos(d);
float sin = (float) Math.sin(d);
float f = (cos * (-0.715f)) + 0.715f;
float f2 = ((-0.072f) * cos) + 0.072f;
float f3 = ((-0.213f) * cos) + 0.213f;
cm.postConcat(new ColorMatrix(new float[]{(0.787f * cos) + 0.213f + (sin * (-0.213f)), ((-0.715f) * sin) + f, (sin * 0.928f) + f2, 0.0f, 0.0f, (0.143f * sin) + f3, (0.28500003f * cos) + 0.715f + (0.14f * sin), f2 + ((-0.283f) * sin), 0.0f, 0.0f, f3 + ((-0.787f) * sin), f + (0.715f * sin), (cos * 0.928f) + 0.072f + (sin * 0.072f), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}));
}
public static float cleanValue(float p_val, float p_limit) {
return Math.min(p_limit, Math.max(-p_limit, p_val));
}
public static void multiplyBrightnessColorMatrix(ColorMatrix colorMatrix, float v) {
if (colorMatrix == null) {
return;
}
colorMatrix.postConcat(new ColorMatrix(new float[]{v, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, v, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, v, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}));
}
public static Bitmap snapshotView(View v) {
Bitmap createBitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(createBitmap);
v.draw(canvas);
int[] iArr = new int[2];
v.getLocationInWindow(iArr);
snapshotTextureViews(iArr[0], iArr[1], iArr, canvas, v);
return createBitmap;
}
private static void snapshotTextureViews(int rootX, int rootY, int[] loc, Canvas canvas, View v) {
if (v instanceof TextureView) {
TextureView textureView = (TextureView) v;
textureView.getLocationInWindow(loc);
Bitmap bitmap = textureView.getBitmap();
if (bitmap != null) {
canvas.save();
canvas.drawBitmap(bitmap, loc[0] - rootX, loc[1] - rootY, (Paint) null);
canvas.restore();
bitmap.recycle();
}
}
if (v instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) v;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
snapshotTextureViews(rootX, rootY, loc, canvas, viewGroup.getChildAt(i));
}
}
}
public static void requestAltFocusable(Activity activity, int classGuid) {
if (activity == null) {
return;
}
activity.getWindow().setFlags(131072, 131072);
altFocusableClassGuid = classGuid;
}
public static void removeAltFocusable(Activity activity, int classGuid) {
if (activity != null && altFocusableClassGuid == classGuid) {
activity.getWindow().clearFlags(131072);
}
}
public static void requestAdjustResize(Activity activity, int classGuid) {
if (activity == null) {
return;
}
requestAdjustResize(activity.getWindow(), classGuid);
}
public static void requestAdjustResize(Window window, int classGuid) {
if (window == null || isTablet()) {
return;
}
window.setSoftInputMode(16);
adjustOwnerClassGuid = classGuid;
}
public static void requestAdjustNothing(Activity activity, int classGuid) {
if (activity == null || isTablet()) {
return;
}
activity.getWindow().setSoftInputMode(48);
adjustOwnerClassGuid = classGuid;
}
public static void setAdjustResizeToNothing(Activity activity, int classGuid) {
if (activity == null || isTablet()) {
return;
}
int i = adjustOwnerClassGuid;
if (i == 0 || i == classGuid) {
activity.getWindow().setSoftInputMode(48);
}
}
public static void removeAdjustResize(Activity activity, int classGuid) {
if (activity == null || isTablet() || adjustOwnerClassGuid != classGuid) {
return;
}
activity.getWindow().setSoftInputMode(32);
}
public static void createEmptyFile(File f) {
try {
if (f.exists()) {
return;
}
FileWriter fileWriter = new FileWriter(f);
fileWriter.flush();
fileWriter.close();
} catch (Throwable th) {
FileLog.e(th, false);
}
}
public static boolean isMapsInstalled(BaseFragment fragment) {
String mapsAppPackageName = ApplicationLoader.getMapsProvider().getMapsAppPackageName();
try {
ApplicationLoader.applicationContext.getPackageManager().getApplicationInfo(mapsAppPackageName, 0);
return true;
} catch (PackageManager.NameNotFoundException unused) {
if (fragment.getParentActivity() == null) {
return false;
}
AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
builder.setMessage(LocaleController.getString(ApplicationLoader.getMapsProvider().getInstallMapsString()));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new AndroidUtilities$.ExternalSyntheticLambda3(mapsAppPackageName, fragment));
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
fragment.showDialog(builder.create());
return false;
}
}
public static void lambda$isMapsInstalled$9(String str, BaseFragment baseFragment, DialogInterface dialogInterface, int i) {
try {
baseFragment.getParentActivity().startActivityForResult(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=" + str)), 500);
} catch (Exception e) {
FileLog.e(e);
}
}
public static int[] toIntArray(List<Integer> integers) {
int size = integers.size();
int[] iArr = new int[size];
for (int i = 0; i < size; i++) {
iArr[i] = integers.get(i).intValue();
}
return iArr;
}
public static boolean isInternalUri(Uri uri) {
return isInternalUri(uri, 0);
}
public static boolean isInternalUri(int fd) {
return isInternalUri(null, fd);
}
private static boolean isInternalUri(Uri uri, int fd) {
String str;
if (uri != null) {
str = uri.getPath();
if (str == null) {
return false;
}
if (str.matches(Pattern.quote(new File(ApplicationLoader.applicationContext.getCacheDir(), "voip_logs").getAbsolutePath()) + "/\\d+\\.log")) {
return false;
}
int i = 0;
while (str.length() <= 4096) {
try {
String readlink = Utilities.readlink(str);
if (readlink != null && !readlink.equals(str)) {
i++;
if (i >= 10) {
return true;
}
str = readlink;
}
} catch (Throwable unused) {
return true;
}
}
return true;
}
str = "";
int i2 = 0;
while (str.length() <= 4096) {
try {
String readlinkFd = Utilities.readlinkFd(fd);
if (readlinkFd != null && !readlinkFd.equals(str)) {
i2++;
if (i2 >= 10) {
return true;
}
str = readlinkFd;
}
} catch (Throwable unused2) {
return true;
}
}
return true;
try {
String canonicalPath = new File(str).getCanonicalPath();
if (canonicalPath != null) {
str = canonicalPath;
}
} catch (Exception unused3) {
str.replace("/./", "/");
}
if (str.endsWith(".attheme")) {
return false;
}
String lowerCase = str.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append("/data/data/");
sb.append(ApplicationLoader.applicationContext.getPackageName());
return lowerCase.contains(sb.toString());
}
@SuppressLint({"WrongConstant"})
public static void lockOrientation(Activity activity) {
if (activity == null || prevOrientation != -10) {
return;
}
try {
prevOrientation = activity.getRequestedOrientation();
WindowManager windowManager = (WindowManager) activity.getSystemService("window");
if (windowManager != null && windowManager.getDefaultDisplay() != null) {
int rotation = windowManager.getDefaultDisplay().getRotation();
int i = activity.getResources().getConfiguration().orientation;
if (rotation == 3) {
if (i == 1) {
activity.setRequestedOrientation(1);
} else {
activity.setRequestedOrientation(8);
}
} else if (rotation == 1) {
if (i == 1) {
activity.setRequestedOrientation(9);
} else {
activity.setRequestedOrientation(0);
}
} else if (rotation == 0) {
if (i == 2) {
activity.setRequestedOrientation(0);
} else {
activity.setRequestedOrientation(1);
}
} else if (i == 2) {
activity.setRequestedOrientation(8);
} else {
activity.setRequestedOrientation(9);
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
@SuppressLint({"WrongConstant"})
public static void lockOrientation(Activity activity, int orientation) {
if (activity == null) {
return;
}
try {
prevOrientation = activity.getRequestedOrientation();
activity.setRequestedOrientation(orientation);
} catch (Exception e) {
FileLog.e(e);
}
}
@SuppressLint({"WrongConstant"})
public static void unlockOrientation(Activity activity) {
if (activity == null) {
return;
}
try {
int i = prevOrientation;
if (i != -10) {
activity.setRequestedOrientation(i);
prevOrientation = -10;
}
} catch (Exception e) {
FileLog.e(e);
}
}
public static byte[] getStringBytes(String src) {
try {
return src.getBytes("UTF-8");
} catch (Exception unused) {
return new byte[0];
}
}
public static ArrayList<TLRPC$User> loadVCardFromStream(Uri uri, int currentAccount, boolean asset, ArrayList<VcardItem> items, String name) {
InputStream createInputStream;
char c;
String[] strArr;
String str;
byte[] decodeQuotedPrintable;
VcardItem vcardItem;
ArrayList<VcardItem> arrayList = items;
VcardItem vcardItem2 = null;
if (asset) {
try {
createInputStream = ApplicationLoader.applicationContext.getContentResolver().openAssetFileDescriptor(uri, "r").createInputStream();
} catch (Throwable th) {
th = th;
FileLog.e(th);
return vcardItem2;
}
} else {
try {
createInputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri);
} catch (Throwable th2) {
th = th2;
vcardItem2 = null;
FileLog.e(th);
return vcardItem2;
}
}
ArrayList arrayList2 = new ArrayList();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(createInputStream, "UTF-8"));
int i = 0;
VcardData vcardData = null;
String str2 = null;
VcardItem vcardItem3 = null;
boolean z = false;
while (true) {
String readLine = bufferedReader.readLine();
if (readLine != null) {
if (readLine.startsWith("PHOTO")) {
z = true;
} else {
if (readLine.indexOf(58) >= 0) {
if (readLine.startsWith("BEGIN:VCARD")) {
vcardData = new VcardData(vcardItem2);
arrayList2.add(vcardData);
vcardData.name = name;
} else if (!readLine.startsWith("END:VCARD") && arrayList != null) {
if (readLine.startsWith("TEL")) {
vcardItem = new VcardItem();
vcardItem.type = i;
} else if (readLine.startsWith("EMAIL")) {
vcardItem = new VcardItem();
vcardItem.type = 1;
} else {
if (!readLine.startsWith("ADR") && !readLine.startsWith("LABEL") && !readLine.startsWith("GEO")) {
if (readLine.startsWith("URL")) {
vcardItem = new VcardItem();
vcardItem.type = 3;
} else if (readLine.startsWith("NOTE")) {
vcardItem = new VcardItem();
vcardItem.type = 4;
} else if (readLine.startsWith("BDAY")) {
vcardItem = new VcardItem();
vcardItem.type = 5;
} else {
if (!readLine.startsWith("ORG") && !readLine.startsWith("TITLE") && !readLine.startsWith("ROLE")) {
if (readLine.startsWith("X-ANDROID")) {
vcardItem = new VcardItem();
vcardItem.type = -1;
} else {
if (!readLine.startsWith("X-PHONETIC") && readLine.startsWith("X-")) {
vcardItem = new VcardItem();
vcardItem.type = 20;
}
vcardItem3 = vcardItem2;
if (vcardItem3 != null && vcardItem3.type >= 0) {
arrayList.add(vcardItem3);
}
z = false;
}
}
vcardItem = new VcardItem();
vcardItem.type = 6;
}
}
vcardItem = new VcardItem();
vcardItem.type = 2;
}
vcardItem3 = vcardItem;
if (vcardItem3 != null) {
arrayList.add(vcardItem3);
}
z = false;
}
vcardItem3 = vcardItem2;
z = false;
}
if (!z && vcardData != null) {
if (vcardItem3 == null) {
if (vcardData.vcard.length() > 0) {
vcardData.vcard.append('\n');
}
vcardData.vcard.append(readLine);
} else {
vcardItem3.vcardData.add(readLine);
}
}
if (str2 != null) {
readLine = str2 + readLine;
str2 = null;
}
String str3 = "=";
if (readLine.contains("=QUOTED-PRINTABLE") && readLine.endsWith("=")) {
str2 = readLine.substring(i, readLine.length() - 1);
vcardItem2 = null;
} else {
if (!z && vcardData != null && vcardItem3 != null) {
vcardItem3.fullData = readLine;
}
int indexOf = readLine.indexOf(":");
if (indexOf >= 0) {
strArr = new String[]{readLine.substring(0, indexOf), readLine.substring(indexOf + 1).trim()};
c = 0;
} else {
c = 0;
strArr = new String[]{readLine.trim()};
}
if (strArr.length >= 2 && vcardData != null) {
if (!strArr[c].startsWith("FN") && !strArr[c].startsWith("N") && (!strArr[c].startsWith("ORG") || !TextUtils.isEmpty(vcardData.name))) {
if (strArr[0].startsWith("TEL")) {
vcardData.phones.add(strArr[1]);
}
}
String[] split = strArr[0].split(";");
int length = split.length;
str = str2;
String str4 = null;
int i2 = 0;
String str5 = null;
while (i2 < length) {
int i3 = length;
String[] split2 = split[i2].split(str3);
String[] strArr2 = split;
String str6 = str3;
if (split2.length == 2) {
if (split2[0].equals("CHARSET")) {
str4 = split2[1];
} else if (split2[0].equals("ENCODING")) {
str5 = split2[1];
}
}
i2++;
length = i3;
split = strArr2;
str3 = str6;
}
if (strArr[0].startsWith("N")) {
vcardData.name = strArr[1].replace(';', ' ').trim();
} else {
vcardData.name = strArr[1];
}
if (str5 != null && str5.equalsIgnoreCase("QUOTED-PRINTABLE") && (decodeQuotedPrintable = decodeQuotedPrintable(getStringBytes(vcardData.name))) != null && decodeQuotedPrintable.length != 0) {
vcardData.name = new String(decodeQuotedPrintable, str4);
}
arrayList = items;
str2 = str;
vcardItem2 = null;
i = 0;
}
str = str2;
arrayList = items;
str2 = str;
vcardItem2 = null;
i = 0;
}
}
} else {
try {
break;
} catch (Exception e) {
FileLog.e(e);
}
}
}
bufferedReader.close();
createInputStream.close();
vcardItem2 = null;
for (int i4 = 0; i4 < arrayList2.size(); i4++) {
VcardData vcardData2 = (VcardData) arrayList2.get(i4);
if (vcardData2.name != null && !vcardData2.phones.isEmpty()) {
if (vcardItem2 == null) {
vcardItem2 = new ArrayList();
}
String str7 = (String) vcardData2.phones.get(0);
int i5 = 0;
while (true) {
if (i5 >= vcardData2.phones.size()) {
break;
}
String str8 = (String) vcardData2.phones.get(i5);
if (ContactsController.getInstance(currentAccount).contactsByShortPhone.get(str8.substring(Math.max(0, str8.length() - 7))) != null) {
str7 = str8;
break;
}
i5++;
}
TLRPC.TL_userContact_old2 tL_userContact_old2 = new TLRPC.TL_userContact_old2();
tL_userContact_old2.phone = str7;
tL_userContact_old2.first_name = vcardData2.name;
tL_userContact_old2.last_name = "";
tL_userContact_old2.id = 0L;
TLRPC.TL_restrictionReason tL_restrictionReason = new TLRPC.TL_restrictionReason();
tL_restrictionReason.text = vcardData2.vcard.toString();
tL_restrictionReason.platform = "";
tL_restrictionReason.reason = "";
tL_userContact_old2.restriction_reason.add(tL_restrictionReason);
vcardItem2.add(tL_userContact_old2);
}
}
return vcardItem2;
}
public static Typeface getTypeface(String assetPath) {
Typeface typeface;
Typeface createFromAsset;
Hashtable<String, Typeface> hashtable = typefaceCache;
synchronized (hashtable) {
if (!hashtable.containsKey(assetPath)) {
try {
if (Theme.getDeviceFont() && Build.VERSION.SDK_INT >= 21) {
Typeface create = (assetPath.contains("medium") && assetPath.contains("italic")) ? Typeface.create("sans-serif-medium", 2) : null;
if (assetPath.contains("medium")) {
create = Typeface.create("sans-serif-medium", 0);
}
if (assetPath.contains("italic")) {
create = Typeface.create("sans-serif-medium", 2);
}
if (assetPath.contains("mono")) {
create = Typeface.MONOSPACE;
}
if (assetPath.contains("mw_bold")) {
create = Typeface.create("serif", 1);
}
hashtable.put(assetPath, create);
} else {
if (Build.VERSION.SDK_INT >= 26) {
Typeface.Builder builder = new Typeface.Builder(ApplicationLoader.applicationContext.getAssets(), assetPath);
if (assetPath.contains("medium")) {
builder.setWeight(700);
}
if (assetPath.contains("italic")) {
builder.setItalic(true);
}
createFromAsset = builder.build();
} else {
createFromAsset = Typeface.createFromAsset(ApplicationLoader.applicationContext.getAssets(), assetPath);
}
hashtable.put(assetPath, createFromAsset);
}
} catch (Exception e) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("Could not get typeface '" + assetPath + "' because " + e.getMessage());
}
return null;
}
}
typeface = hashtable.get(assetPath);
}
return typeface;
}
public static boolean isWaitingForSms() {
boolean z;
synchronized (smsLock) {
z = waitingForSms;
}
return z;
}
public static void setWaitingForSms(boolean value) {
synchronized (smsLock) {
waitingForSms = value;
if (value) {
try {
SmsRetriever.getClient(ApplicationLoader.applicationContext).startSmsRetriever().addOnSuccessListener(AndroidUtilities$.ExternalSyntheticLambda11.INSTANCE);
} catch (Throwable th) {
FileLog.e(th);
}
}
}
}
public static void lambda$setWaitingForSms$10(Void r0) {
if (BuildVars.DEBUG_VERSION) {
FileLog.d("sms listener registered");
}
}
public static int getShadowHeight() {
float f = density;
if (f >= 4.0f) {
return 3;
}
return f >= 2.0f ? 2 : 1;
}
public static boolean isWaitingForCall() {
boolean z;
synchronized (callLock) {
z = waitingForCall;
}
return z;
}
public static void setWaitingForCall(boolean value) {
synchronized (callLock) {
try {
if (value) {
if (callReceiver == null) {
IntentFilter intentFilter = new IntentFilter("android.intent.action.PHONE_STATE");
Context context = ApplicationLoader.applicationContext;
CallReceiver callReceiver2 = new CallReceiver();
callReceiver = callReceiver2;
context.registerReceiver(callReceiver2, intentFilter);
}
} else if (callReceiver != null) {
ApplicationLoader.applicationContext.unregisterReceiver(callReceiver);
callReceiver = null;
}
} catch (Exception unused) {
}
waitingForCall = value;
}
}
public static boolean showKeyboard(View view) {
if (view == null) {
return false;
}
try {
return ((InputMethodManager) view.getContext().getSystemService("input_method")).showSoftInput(view, 1);
} catch (Exception e) {
FileLog.e(e);
return false;
}
}
public static java.lang.String[] getCurrentKeyboardLanguage() {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.getCurrentKeyboardLanguage():java.lang.String[]");
}
public static void hideKeyboard(View view) {
if (view == null) {
return;
}
try {
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService("input_method");
if (inputMethodManager.isActive()) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception e) {
FileLog.e(e);
}
}
public static ArrayList<File> getDataDirs() {
File[] externalFilesDirs;
ArrayList<File> arrayList = null;
if (Build.VERSION.SDK_INT >= 19 && (externalFilesDirs = ApplicationLoader.applicationContext.getExternalFilesDirs(null)) != null) {
for (int i = 0; i < externalFilesDirs.length; i++) {
if (externalFilesDirs[i] != null) {
String absolutePath = externalFilesDirs[i].getAbsolutePath();
try {
if (Build.VERSION.SDK_INT >= 30 && Environment.isExternalStorageManager() && !PlusSettings.useExternalStorage() && PlusSettings.useTelegramDataPath()) {
externalFilesDirs[i] = new File(absolutePath.replace(ApplicationLoader.applicationContext.getPackageName(), "org.telegram.messenger"));
}
} catch (Exception e) {
FileLog.e(e);
}
if (arrayList == null) {
arrayList = new ArrayList<>();
}
arrayList.add(externalFilesDirs[i]);
}
}
}
if (arrayList == null) {
arrayList = new ArrayList<>();
}
if (arrayList.isEmpty()) {
arrayList.add(Environment.getExternalStorageDirectory());
}
return arrayList;
}
public static ArrayList<File> getRootDirs() {
File externalStorageDirectory;
File[] externalFilesDirs;
String absolutePath;
int indexOf;
HashSet hashSet = new HashSet();
ArrayList<File> arrayList = null;
if (Build.VERSION.SDK_INT >= 19 && (externalFilesDirs = ApplicationLoader.applicationContext.getExternalFilesDirs(null)) != null) {
for (int i = 0; i < externalFilesDirs.length; i++) {
if (externalFilesDirs[i] != null && (indexOf = (absolutePath = externalFilesDirs[i].getAbsolutePath()).indexOf("/Android")) >= 0) {
if (arrayList == null) {
arrayList = new ArrayList<>();
}
try {
if (Build.VERSION.SDK_INT >= 30 && Environment.isExternalStorageManager() && !PlusSettings.useExternalStorage() && PlusSettings.useTelegramDataPath()) {
absolutePath = absolutePath.replace(ApplicationLoader.applicationContext.getPackageName(), "org.telegram.messenger");
}
} catch (Exception e) {
FileLog.e(e);
}
File file = new File(absolutePath.substring(0, indexOf));
for (int i2 = 0; i2 < arrayList.size(); i2++) {
arrayList.get(i2).getPath().equals(file.getPath());
}
if (!hashSet.contains(file.getAbsolutePath())) {
hashSet.add(file.getAbsolutePath());
arrayList.add(file);
}
}
}
}
if (arrayList == null) {
arrayList = new ArrayList<>();
}
if (arrayList.isEmpty() && (externalStorageDirectory = Environment.getExternalStorageDirectory()) != null && !hashSet.contains(externalStorageDirectory.getAbsolutePath())) {
arrayList.add(externalStorageDirectory);
}
return arrayList;
}
public static File getCacheDir() {
String str;
String str2 = null;
try {
str = Environment.getExternalStorageState();
} catch (Exception e) {
FileLog.e(e);
str = null;
}
if (str == null || str.startsWith("mounted")) {
FileLog.d("external dir mounted");
try {
File[] externalCacheDirs = ApplicationLoader.applicationContext.getExternalCacheDirs();
int i = 0;
File file = externalCacheDirs[0];
if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
while (true) {
if (i < externalCacheDirs.length) {
if (externalCacheDirs[i] != null && externalCacheDirs[i].getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
file = externalCacheDirs[i];
break;
}
i++;
} else {
break;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("check dir ");
if (file != null) {
str2 = file.getPath();
}
sb.append(str2);
sb.append(" ");
FileLog.d(sb.toString());
if (file != null && ((file.exists() || file.mkdirs()) && file.canWrite())) {
return file;
}
if (file != null) {
FileLog.d("check dir file exist " + file.exists() + " can write " + file.canWrite());
}
} catch (Exception e2) {
FileLog.e(e2);
}
}
try {
File cacheDir = ApplicationLoader.applicationContext.getCacheDir();
if (cacheDir != null) {
return cacheDir;
}
} catch (Exception e3) {
FileLog.e(e3);
}
try {
File filesDir = ApplicationLoader.applicationContext.getFilesDir();
if (filesDir != null) {
File file2 = new File(filesDir, "cache/");
file2.mkdirs();
if (filesDir.exists() || filesDir.mkdirs()) {
if (filesDir.canWrite()) {
return file2;
}
}
}
} catch (Exception unused) {
}
return new File("");
}
public static int dp(float value) {
if (value == 0.0f) {
return 0;
}
return (int) Math.ceil(density * value);
}
public static int dpr(float value) {
if (value == 0.0f) {
return 0;
}
return Math.round(density * value);
}
public static int dp2(float value) {
if (value == 0.0f) {
return 0;
}
return (int) Math.floor(density * value);
}
public static float dpf2(float value) {
if (value == 0.0f) {
return 0.0f;
}
return density * value;
}
public static void checkDisplaySize(Context context, Configuration newConfiguration) {
Display defaultDisplay;
try {
float f = density;
density = context.getResources().getDisplayMetrics().density;
if (firstConfigurationWas && Math.abs(f - r2) > 0.001d) {
Theme.reloadAllResources(context);
}
firstConfigurationWas = true;
if (newConfiguration == null) {
newConfiguration = context.getResources().getConfiguration();
}
usingHardwareInput = newConfiguration.keyboard != 1 && newConfiguration.hardKeyboardHidden == 1;
WindowManager windowManager = (WindowManager) context.getSystemService("window");
if (windowManager != null && (defaultDisplay = windowManager.getDefaultDisplay()) != null) {
defaultDisplay.getMetrics(displayMetrics);
defaultDisplay.getSize(displaySize);
float refreshRate = defaultDisplay.getRefreshRate();
screenRefreshRate = refreshRate;
screenRefreshTime = 1000.0f / refreshRate;
}
if (newConfiguration.screenWidthDp != 0) {
int ceil = (int) Math.ceil(r2 * density);
if (Math.abs(displaySize.x - ceil) > 3) {
displaySize.x = ceil;
}
}
if (newConfiguration.screenHeightDp != 0) {
int ceil2 = (int) Math.ceil(r2 * density);
if (Math.abs(displaySize.y - ceil2) > 3) {
displaySize.y = ceil2;
}
}
if (roundMessageSize == 0) {
if (isTablet()) {
roundMessageSize = (int) (getMinTabletSide() * 0.6f);
roundPlayingMessageSize = getMinTabletSide() - dp(28.0f);
} else {
Point point = displaySize;
roundMessageSize = (int) (Math.min(point.x, point.y) * 0.6f);
Point point2 = displaySize;
roundPlayingMessageSize = Math.min(point2.x, point2.y) - dp(28.0f);
}
roundMessageInset = dp(2.0f);
}
fillStatusBarHeight(context, true);
if (BuildVars.LOGS_ENABLED) {
FileLog.e("density = " + density + " display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x" + displayMetrics.ydpi + ", screen layout: " + newConfiguration.screenLayout + ", statusbar height: " + statusBarHeight + ", navbar height: " + navigationBarHeight);
}
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
} catch (Exception e) {
FileLog.e(e);
}
}
public static double fixLocationCoord(double value) {
double d = (long) (value * 1000000.0d);
Double.isNaN(d);
return d / 1000000.0d;
}
public static String formapMapUrl(int account, double lat, double lon, int width, int height, boolean marker, int zoom, int provider) {
int min = Math.min(2, (int) Math.ceil(density));
int i = provider == -1 ? MessagesController.getInstance(account).mapProvider : provider;
if (marker && i == 0) {
i = 1;
}
if (i == 1 || i == 3) {
String str = null;
String[] strArr = {"ru_RU", "tr_TR"};
LocaleController.LocaleInfo currentLocaleInfo = LocaleController.getInstance().getCurrentLocaleInfo();
for (int i2 = 0; i2 < 2; i2++) {
if (strArr[i2].toLowerCase().contains(currentLocaleInfo.shortName)) {
str = strArr[i2];
}
}
if (str == null) {
str = "en_US";
}
return marker ? String.format(Locale.US, "https://static-maps.yandex.ru/1.x/?ll=%.6f,%.6f&z=%d&size=%d,%d&l=map&scale=%d&pt=%.6f,%.6f,vkbkm&lang=%s", Double.valueOf(lon), Double.valueOf(lat), Integer.valueOf(zoom), Integer.valueOf(width * min), Integer.valueOf(height * min), Integer.valueOf(min), Double.valueOf(lon), Double.valueOf(lat), str) : String.format(Locale.US, "https://static-maps.yandex.ru/1.x/?ll=%.6f,%.6f&z=%d&size=%d,%d&l=map&scale=%d&lang=%s", Double.valueOf(lon), Double.valueOf(lat), Integer.valueOf(zoom), Integer.valueOf(width * min), Integer.valueOf(height * min), Integer.valueOf(min), str);
}
String str2 = MessagesController.getInstance(account).mapKey;
return !TextUtils.isEmpty(str2) ? marker ? String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&maptype=roadmap&scale=%d&markers=color:red%%7Csize:mid%%7C%.6f,%.6f&sensor=false&key=%s", Double.valueOf(lat), Double.valueOf(lon), Integer.valueOf(zoom), Integer.valueOf(width), Integer.valueOf(height), Integer.valueOf(min), Double.valueOf(lat), Double.valueOf(lon), str2) : String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&maptype=roadmap&scale=%d&key=%s", Double.valueOf(lat), Double.valueOf(lon), Integer.valueOf(zoom), Integer.valueOf(width), Integer.valueOf(height), Integer.valueOf(min), str2) : marker ? String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&maptype=roadmap&scale=%d&markers=color:red%%7Csize:mid%%7C%.6f,%.6f&sensor=false", Double.valueOf(lat), Double.valueOf(lon), Integer.valueOf(zoom), Integer.valueOf(width), Integer.valueOf(height), Integer.valueOf(min), Double.valueOf(lat), Double.valueOf(lon)) : String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&maptype=roadmap&scale=%d", Double.valueOf(lat), Double.valueOf(lon), Integer.valueOf(zoom), Integer.valueOf(width), Integer.valueOf(height), Integer.valueOf(min));
}
public static float getPixelsInCM(float cm, boolean isX) {
return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);
}
public static int getPeerLayerVersion(int layer) {
return Math.max(73, (layer >> 16) & 65535);
}
public static void runOnUIThread(Runnable runnable) {
runOnUIThread(runnable, 0L);
}
public static void runOnUIThread(Runnable runnable, long delay) {
if (ApplicationLoader.applicationHandler == null) {
return;
}
if (delay == 0) {
ApplicationLoader.applicationHandler.post(runnable);
} else {
ApplicationLoader.applicationHandler.postDelayed(runnable, delay);
}
}
public static void cancelRunOnUIThread(Runnable runnable) {
if (ApplicationLoader.applicationHandler == null) {
return;
}
ApplicationLoader.applicationHandler.removeCallbacks(runnable);
}
public static boolean isTabletForce() {
return ApplicationLoader.applicationContext != null && ApplicationLoader.applicationContext.getResources().getBoolean(R.bool.isTablet);
}
public static boolean isTabletInternal() {
if (isTablet == null) {
isTablet = Boolean.valueOf(isTabletForce());
}
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("plusconfig", 0);
if (sharedPreferences.getBoolean("forceTabletMode", false)) {
isTablet = Boolean.TRUE;
}
if (sharedPreferences.getBoolean("disableTabletMode", false)) {
isTablet = Boolean.FALSE;
}
if (isTablet == null) {
isTablet = Boolean.FALSE;
}
return isTablet.booleanValue();
}
public static void resetTabletFlag() {
if (wasTablet == null) {
wasTablet = Boolean.valueOf(isTabletInternal());
}
isTablet = null;
SharedConfig.updateTabletConfig();
}
public static void resetWasTabletFlag() {
wasTablet = null;
}
public static Boolean getWasTablet() {
return wasTablet;
}
public static boolean isTablet() {
return isTabletInternal() && !SharedConfig.forceDisableTabletMode;
}
public static boolean isSmallScreen() {
if (isSmallScreen == null) {
Point point = displaySize;
isSmallScreen = Boolean.valueOf(((float) ((Math.max(point.x, point.y) - statusBarHeight) - navigationBarHeight)) / density <= 650.0f);
}
return isSmallScreen.booleanValue();
}
public static boolean isSmallTablet() {
Point point = displaySize;
return ((float) Math.min(point.x, point.y)) / density <= 690.0f;
}
public static int getMinTabletSide() {
if (!isSmallTablet()) {
int i = displaySize.x;
int i2 = (i * 35) / 100;
if (i2 < dp(320.0f)) {
i2 = dp(320.0f);
}
return i - i2;
}
Point point = displaySize;
int min = Math.min(point.x, point.y);
Point point2 = displaySize;
int max = Math.max(point2.x, point2.y);
int i3 = (max * 35) / 100;
if (i3 < dp(320.0f)) {
i3 = dp(320.0f);
}
return Math.min(min, max - i3);
}
public static int getPhotoSize() {
if (photoSize == null) {
photoSize = 1280;
}
return photoSize.intValue();
}
public static void endIncomingCall() {
if (hasCallPermissions) {
try {
TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService("phone");
Method declaredMethod = Class.forName(telephonyManager.getClass().getName()).getDeclaredMethod("getITelephony", new Class[0]);
declaredMethod.setAccessible(true);
ITelephony iTelephony = (ITelephony) declaredMethod.invoke(telephonyManager, new Object[0]);
iTelephony.silenceRinger();
iTelephony.endCall();
} catch (Throwable th) {
FileLog.e(th);
}
}
}
public static String obtainLoginPhoneCall(String pattern) {
if (!hasCallPermissions) {
return null;
}
try {
Cursor query = ApplicationLoader.applicationContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[]{"number", "date"}, "type IN (3,1,5)", null, Build.VERSION.SDK_INT >= 26 ? "date DESC" : "date DESC LIMIT 5");
while (query.moveToNext()) {
try {
String string = query.getString(0);
long j = query.getLong(1);
if (BuildVars.LOGS_ENABLED) {
FileLog.e("number = " + string);
}
if (Math.abs(System.currentTimeMillis() - j) < 3600000 && checkPhonePattern(pattern, string)) {
query.close();
return string;
}
} finally {
}
}
query.close();
} catch (Exception e) {
FileLog.e(e);
}
return null;
}
public static boolean checkPhonePattern(String pattern, String phone) {
if (!TextUtils.isEmpty(pattern) && !pattern.equals("*")) {
String[] split = pattern.split("\\*");
String stripExceptNumbers = PhoneFormat.stripExceptNumbers(phone);
int i = 0;
for (String str : split) {
if (!TextUtils.isEmpty(str)) {
int indexOf = stripExceptNumbers.indexOf(str, i);
if (indexOf == -1) {
return false;
}
i = indexOf + str.length();
}
}
}
return true;
}
public static int getViewInset(View view) {
int i;
if (view != null && (i = Build.VERSION.SDK_INT) >= 21 && view.getHeight() != displaySize.y && view.getHeight() != displaySize.y - statusBarHeight) {
try {
if (i >= 23) {
WindowInsets rootWindowInsets = view.getRootWindowInsets();
if (rootWindowInsets != null) {
return rootWindowInsets.getStableInsetBottom();
}
return 0;
}
if (mAttachInfoField == null) {
Field declaredField = View.class.getDeclaredField("mAttachInfo");
mAttachInfoField = declaredField;
declaredField.setAccessible(true);
}
Object obj = mAttachInfoField.get(view);
if (obj != null) {
if (mStableInsetsField == null) {
Field declaredField2 = obj.getClass().getDeclaredField("mStableInsets");
mStableInsetsField = declaredField2;
declaredField2.setAccessible(true);
}
return ((Rect) mStableInsetsField.get(obj)).bottom;
}
} catch (Exception e) {
FileLog.e(e);
}
}
return 0;
}
public static Point getRealScreenSize() {
Point point = new Point();
try {
WindowManager windowManager = (WindowManager) ApplicationLoader.applicationContext.getSystemService("window");
if (Build.VERSION.SDK_INT >= 17) {
windowManager.getDefaultDisplay().getRealSize(point);
} else {
try {
point.set(((Integer) Display.class.getMethod("getRawWidth", new Class[0]).invoke(windowManager.getDefaultDisplay(), new Object[0])).intValue(), ((Integer) Display.class.getMethod("getRawHeight", new Class[0]).invoke(windowManager.getDefaultDisplay(), new Object[0])).intValue());
} catch (Exception e) {
point.set(windowManager.getDefaultDisplay().getWidth(), windowManager.getDefaultDisplay().getHeight());
FileLog.e(e);
}
}
} catch (Exception e2) {
FileLog.e(e2);
}
return point;
}
public static void setEnabled(View view, boolean enabled) {
if (view == null) {
return;
}
view.setEnabled(enabled);
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
setEnabled(viewGroup.getChildAt(i), enabled);
}
}
}
public static int charSequenceIndexOf(CharSequence cs, CharSequence needle, int fromIndex) {
while (fromIndex < cs.length() - needle.length()) {
boolean z = false;
int i = 0;
while (true) {
if (i >= needle.length()) {
z = true;
break;
}
if (needle.charAt(i) != cs.charAt(fromIndex + i)) {
break;
}
i++;
}
if (z) {
return fromIndex;
}
fromIndex++;
}
return -1;
}
public static int charSequenceIndexOf(CharSequence cs, CharSequence needle) {
return charSequenceIndexOf(cs, needle, 0);
}
public static boolean charSequenceContains(CharSequence cs, CharSequence needle) {
return charSequenceIndexOf(cs, needle) != -1;
}
public static CharSequence getTrimmedString(CharSequence src) {
if (src != null && src.length() != 0) {
while (src.length() > 0 && (src.charAt(0) == '\n' || src.charAt(0) == ' ')) {
src = src.subSequence(1, src.length());
}
while (src.length() > 0 && (src.charAt(src.length() - 1) == '\n' || src.charAt(src.length() - 1) == ' ')) {
src = src.subSequence(0, src.length() - 1);
}
}
return src;
}
public static void setViewPagerEdgeEffectColor(ViewPager viewPager, int color) {
if (Build.VERSION.SDK_INT >= 21) {
try {
Field declaredField = ViewPager.class.getDeclaredField("mLeftEdge");
declaredField.setAccessible(true);
EdgeEffect edgeEffect = (EdgeEffect) declaredField.get(viewPager);
if (edgeEffect != null) {
edgeEffect.setColor(color);
}
Field declaredField2 = ViewPager.class.getDeclaredField("mRightEdge");
declaredField2.setAccessible(true);
EdgeEffect edgeEffect2 = (EdgeEffect) declaredField2.get(viewPager);
if (edgeEffect2 != null) {
edgeEffect2.setColor(color);
}
} catch (Exception unused) {
}
}
}
public static void setScrollViewEdgeEffectColor(HorizontalScrollView scrollView, int color) {
int i = Build.VERSION.SDK_INT;
if (i >= 29) {
scrollView.setEdgeEffectColor(color);
return;
}
if (i >= 21) {
try {
Field declaredField = HorizontalScrollView.class.getDeclaredField("mEdgeGlowLeft");
declaredField.setAccessible(true);
EdgeEffect edgeEffect = (EdgeEffect) declaredField.get(scrollView);
if (edgeEffect != null) {
edgeEffect.setColor(color);
}
Field declaredField2 = HorizontalScrollView.class.getDeclaredField("mEdgeGlowRight");
declaredField2.setAccessible(true);
EdgeEffect edgeEffect2 = (EdgeEffect) declaredField2.get(scrollView);
if (edgeEffect2 != null) {
edgeEffect2.setColor(color);
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
public static void setScrollViewEdgeEffectColor(ScrollView scrollView, int color) {
int i = Build.VERSION.SDK_INT;
if (i >= 29) {
scrollView.setTopEdgeEffectColor(color);
scrollView.setBottomEdgeEffectColor(color);
return;
}
if (i >= 21) {
try {
Field declaredField = ScrollView.class.getDeclaredField("mEdgeGlowTop");
declaredField.setAccessible(true);
EdgeEffect edgeEffect = (EdgeEffect) declaredField.get(scrollView);
if (edgeEffect != null) {
edgeEffect.setColor(color);
}
Field declaredField2 = ScrollView.class.getDeclaredField("mEdgeGlowBottom");
declaredField2.setAccessible(true);
EdgeEffect edgeEffect2 = (EdgeEffect) declaredField2.get(scrollView);
if (edgeEffect2 != null) {
edgeEffect2.setColor(color);
}
} catch (Exception unused) {
}
}
}
@SuppressLint({"NewApi"})
public static void clearDrawableAnimation(View view) {
if (Build.VERSION.SDK_INT < 21 || view == null) {
return;
}
if (view instanceof ListView) {
Drawable selector = ((ListView) view).getSelector();
if (selector != null) {
selector.setState(StateSet.NOTHING);
return;
}
return;
}
Drawable background = view.getBackground();
if (background != null) {
background.setState(StateSet.NOTHING);
background.jumpToCurrentState();
}
}
public static SpannableStringBuilder replaceTags(String str) {
return replaceTags(str, 11, new Object[0]);
}
public static SpannableStringBuilder replaceTags(String str, int flag, Object... args) {
try {
StringBuilder sb = new StringBuilder(str);
if ((flag & 1) != 0) {
while (true) {
int indexOf = sb.indexOf("<br>");
if (indexOf == -1) {
break;
}
sb.replace(indexOf, indexOf + 4, "\n");
}
while (true) {
int indexOf2 = sb.indexOf("<br/>");
if (indexOf2 == -1) {
break;
}
sb.replace(indexOf2, indexOf2 + 5, "\n");
}
}
ArrayList arrayList = new ArrayList();
if ((flag & 2) != 0) {
while (true) {
int indexOf3 = sb.indexOf("<b>");
if (indexOf3 == -1) {
break;
}
sb.replace(indexOf3, indexOf3 + 3, "");
int indexOf4 = sb.indexOf("</b>");
if (indexOf4 == -1) {
indexOf4 = sb.indexOf("<b>");
}
sb.replace(indexOf4, indexOf4 + 4, "");
arrayList.add(Integer.valueOf(indexOf3));
arrayList.add(Integer.valueOf(indexOf4));
}
while (true) {
int indexOf5 = sb.indexOf("**");
if (indexOf5 == -1) {
break;
}
sb.replace(indexOf5, indexOf5 + 2, "");
int indexOf6 = sb.indexOf("**");
if (indexOf6 >= 0) {
sb.replace(indexOf6, indexOf6 + 2, "");
arrayList.add(Integer.valueOf(indexOf5));
arrayList.add(Integer.valueOf(indexOf6));
}
}
}
if ((flag & 8) != 0) {
while (true) {
int indexOf7 = sb.indexOf("**");
if (indexOf7 == -1) {
break;
}
sb.replace(indexOf7, indexOf7 + 2, "");
int indexOf8 = sb.indexOf("**");
if (indexOf8 >= 0) {
sb.replace(indexOf8, indexOf8 + 2, "");
arrayList.add(Integer.valueOf(indexOf7));
arrayList.add(Integer.valueOf(indexOf8));
}
}
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(sb);
for (int i = 0; i < arrayList.size() / 2; i++) {
int i2 = i * 2;
spannableStringBuilder.setSpan(new TypefaceSpan(bold()), ((Integer) arrayList.get(i2)).intValue(), ((Integer) arrayList.get(i2 + 1)).intValue(), 33);
}
return spannableStringBuilder;
} catch (Exception e) {
FileLog.e(e);
return new SpannableStringBuilder(str);
}
}
public static SpannableStringBuilder replaceLinks(String str, Theme.ResourcesProvider resourcesProvider) {
if (linksPattern == null) {
linksPattern = Pattern.compile("\\[(.+?)\\]\\((.+?)\\)");
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
Matcher matcher = linksPattern.matcher(str);
int i = 0;
while (matcher.find()) {
spannableStringBuilder.append((CharSequence) str, i, matcher.start());
String group = matcher.group(1);
String group2 = matcher.group(2);
spannableStringBuilder.append((CharSequence) group);
spannableStringBuilder.setSpan(new 5(group2, resourcesProvider), spannableStringBuilder.length() - group.length(), spannableStringBuilder.length(), 33);
i = matcher.end();
}
spannableStringBuilder.append((CharSequence) str, i, str.length());
return spannableStringBuilder;
}
public static boolean needShowPasscode() {
return needShowPasscode(false);
}
public static boolean needShowPasscode(boolean reset) {
boolean isWasInBackground = ForegroundDetector.getInstance().isWasInBackground(reset);
if (reset) {
ForegroundDetector.getInstance().resetBackgroundVar();
}
int elapsedRealtime = (int) (SystemClock.elapsedRealtime() / 1000);
if (BuildVars.LOGS_ENABLED && reset && SharedConfig.passcodeHash.length() > 0) {
FileLog.d("wasInBackground = " + isWasInBackground + " appLocked = " + SharedConfig.appLocked + " autoLockIn = " + SharedConfig.autoLockIn + " lastPauseTime = " + SharedConfig.lastPauseTime + " uptime = " + elapsedRealtime);
}
return SharedConfig.passcodeHash.length() > 0 && isWasInBackground && (SharedConfig.appLocked || (!(SharedConfig.autoLockIn == 0 || SharedConfig.lastPauseTime == 0 || SharedConfig.appLocked || SharedConfig.lastPauseTime + SharedConfig.autoLockIn > elapsedRealtime) || elapsedRealtime + 5 < SharedConfig.lastPauseTime));
}
public static void shakeView(final View view) {
if (view == null) {
return;
}
int i = R.id.shake_animation;
Object tag = view.getTag(i);
if (tag instanceof ValueAnimator) {
((ValueAnimator) tag).cancel();
}
ValueAnimator ofFloat = ValueAnimator.ofFloat(0.0f, 1.0f);
ofFloat.addUpdateListener(new AndroidUtilities$.ExternalSyntheticLambda0(view));
ofFloat.addListener(new 6(view));
ofFloat.setDuration(300L);
ofFloat.start();
view.setTag(i, ofFloat);
}
public static void lambda$shakeView$11(View view, ValueAnimator valueAnimator) {
float floatValue = ((Float) valueAnimator.getAnimatedValue()).floatValue();
double d = floatValue * 4.0f * (1.0f - floatValue);
double d2 = floatValue;
Double.isNaN(d2);
double sin = Math.sin(d2 * 3.141592653589793d * 4.0d);
Double.isNaN(d);
double d3 = d * sin;
double dp = dp(4.0f);
Double.isNaN(dp);
view.setTranslationX((float) (d3 * dp));
}
public static void shakeViewSpring(View view) {
shakeViewSpring(view, 10.0f, null);
}
public static void shakeViewSpring(View view, float shiftDp) {
shakeViewSpring(view, shiftDp, null);
}
public static void shakeViewSpring(View view, Runnable endCallback) {
shakeViewSpring(view, 10.0f, endCallback);
}
public static void shakeViewSpring(View view, float shiftDp, Runnable endCallback) {
if (view == null) {
return;
}
int dp = dp(shiftDp);
int i = R.id.spring_tag;
if (view.getTag(i) != null) {
((SpringAnimation) view.getTag(i)).cancel();
}
int i2 = R.id.spring_was_translation_x_tag;
Float f = (Float) view.getTag(i2);
if (f != null) {
view.setTranslationX(f.floatValue());
}
view.setTag(i2, Float.valueOf(view.getTranslationX()));
float translationX = view.getTranslationX();
SpringAnimation addEndListener = new SpringAnimation(view, DynamicAnimation.TRANSLATION_X, translationX).setSpring(new SpringForce(translationX).setStiffness(600.0f)).setStartVelocity((-dp) * 100).addEndListener(new AndroidUtilities$.ExternalSyntheticLambda10(endCallback, view, translationX));
view.setTag(i, addEndListener);
addEndListener.start();
}
public static void lambda$shakeViewSpring$12(Runnable runnable, View view, float f, DynamicAnimation dynamicAnimation, boolean z, float f2, float f3) {
if (runnable != null) {
runnable.run();
}
view.setTranslationX(f);
view.setTag(R.id.spring_tag, null);
view.setTag(R.id.spring_was_translation_x_tag, null);
}
public static void appCenterLog(Throwable e) {
ApplicationLoader.appCenterLog(e);
}
public static boolean shouldShowClipboardToast() {
int i = Build.VERSION.SDK_INT;
return (i < 31 || !OneUIUtilities.hasBuiltInClipboardToasts()) && i < 32;
}
public static boolean addToClipboard(CharSequence str) {
try {
ClipboardManager clipboardManager = (ClipboardManager) ApplicationLoader.applicationContext.getSystemService("clipboard");
if (str instanceof Spanned) {
clipboardManager.setPrimaryClip(ClipData.newHtmlText("label", str, CustomHtml.toHtml((Spanned) str)));
return true;
}
clipboardManager.setPrimaryClip(ClipData.newPlainText("label", str));
return true;
} catch (Exception e) {
FileLog.e(e);
return false;
}
}
public static void addMediaToGallery(String fromPath) {
if (fromPath == null) {
return;
}
addMediaToGallery(new File(fromPath));
}
public static void addMediaToGallery(File file) {
Uri fromFile = Uri.fromFile(file);
if (fromFile == null) {
return;
}
try {
Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
intent.setData(fromFile);
ApplicationLoader.applicationContext.sendBroadcast(intent);
} catch (Exception e) {
FileLog.e(e);
}
}
private static File getAlbumDir(boolean secretChat) {
int i;
if (secretChat || !BuildVars.NO_SCOPED_STORAGE || (((i = Build.VERSION.SDK_INT) >= 33 && ApplicationLoader.applicationContext.checkSelfPermission("android.permission.READ_MEDIA_IMAGES") != 0) || (i >= 23 && i <= 33 && ApplicationLoader.applicationContext.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") != 0))) {
return FileLoader.getDirectory(0);
}
if ("mounted".equals(Environment.getExternalStorageState())) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), PlusSettings.usePlusFolder() ? "Plus" : "Telegram");
if (file.mkdirs() || file.exists()) {
return file;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("failed to create directory");
}
return null;
}
if (!BuildVars.LOGS_ENABLED) {
return null;
}
FileLog.d("External storage is not mounted READ/WRITE.");
return null;
}
@android.annotation.SuppressLint({"NewApi"})
public static java.lang.String getPath(final android.net.Uri r8) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.getPath(android.net.Uri):java.lang.String");
}
public static java.lang.String getDataColumn(android.content.Context r8, android.net.Uri r9, java.lang.String r10, java.lang.String[] r11) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.getDataColumn(android.content.Context, android.net.Uri, java.lang.String, java.lang.String[]):java.lang.String");
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static File generatePicturePath() {
return generatePicturePath(false, null);
}
public static File generatePicturePath(boolean secretChat, String ext) {
try {
File directory = FileLoader.getDirectory(100);
if (!secretChat && directory != null) {
return new File(directory, generateFileName(0, ext));
}
return new File(ApplicationLoader.applicationContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES), generateFileName(0, ext));
} catch (Exception e) {
FileLog.e(e);
return null;
}
}
public static String generateFileName(int type, String ext) {
Date date = new Date();
date.setTime(System.currentTimeMillis() + Utilities.random.nextInt(1000) + 1);
String format = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US).format(date);
if (type == 0) {
StringBuilder sb = new StringBuilder();
sb.append("IMG_");
sb.append(format);
sb.append(".");
if (TextUtils.isEmpty(ext)) {
ext = "jpg";
}
sb.append(ext);
return sb.toString();
}
return "VID_" + format + ".mp4";
}
public static CharSequence generateSearchName(String name, String name2, String q) {
if ((name == null && name2 == null) || TextUtils.isEmpty(q)) {
return "";
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
if (name == null || name.length() == 0) {
name = name2;
} else if (name2 != null && name2.length() != 0) {
name = name + " " + name2;
}
String trim = name.trim();
String str = " " + trim.toLowerCase();
int i = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getInt("chatsHighlightSearchColor", Theme.lightColor);
int i2 = 0;
while (true) {
int indexOf = str.indexOf(" " + q, i2);
if (indexOf == -1) {
break;
}
int i3 = indexOf - (indexOf == 0 ? 0 : 1);
int length = q.length() + (indexOf == 0 ? 0 : 1) + i3;
if (i2 != 0 && i2 != i3 + 1) {
spannableStringBuilder.append((CharSequence) trim.substring(i2, i3));
} else if (i2 == 0 && i3 != 0) {
spannableStringBuilder.append((CharSequence) trim.substring(0, i3));
}
String substring = trim.substring(i3, Math.min(trim.length(), length));
if (substring.startsWith(" ")) {
spannableStringBuilder.append((CharSequence) " ");
}
String trim2 = substring.trim();
int length2 = spannableStringBuilder.length();
spannableStringBuilder.append((CharSequence) trim2);
spannableStringBuilder.setSpan(Theme.usePlusTheme ? new ForegroundColorSpan(i) : new ForegroundColorSpanThemable(Theme.key_windowBackgroundWhiteBlueText4), length2, trim2.length() + length2, 33);
i2 = length;
}
if (i2 != -1 && i2 < trim.length()) {
spannableStringBuilder.append((CharSequence) trim.substring(i2));
}
return spannableStringBuilder;
}
public static boolean isKeyguardSecure() {
return ((KeyguardManager) ApplicationLoader.applicationContext.getSystemService("keyguard")).isKeyguardSecure();
}
public static boolean isSimAvailable() {
TelephonyManager telephonyManager = (TelephonyManager) ApplicationLoader.applicationContext.getSystemService("phone");
int simState = telephonyManager.getSimState();
return (simState == 1 || simState == 0 || telephonyManager.getPhoneType() == 0 || isAirplaneModeOn()) ? false : true;
}
public static boolean isAirplaneModeOn() {
return Build.VERSION.SDK_INT < 17 ? Settings.System.getInt(ApplicationLoader.applicationContext.getContentResolver(), "airplane_mode_on", 0) != 0 : Settings.Global.getInt(ApplicationLoader.applicationContext.getContentResolver(), "airplane_mode_on", 0) != 0;
}
public static File generateVideoPath() {
return generateVideoPath(false);
}
public static File generateVideoPath(boolean secretChat) {
try {
File albumDir = getAlbumDir(secretChat);
Date date = new Date();
date.setTime(System.currentTimeMillis() + Utilities.random.nextInt(1000) + 1);
if (generatingVideoPathFormat == null) {
generatingVideoPathFormat = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US);
}
return new File(albumDir, "VID_" + generatingVideoPathFormat.format(date) + ".mp4");
} catch (Exception e) {
FileLog.e(e);
return null;
}
}
public static String formatFileSize(long size) {
return formatFileSize(size, false, false);
}
public static String formatFileSize(long size, boolean removeZero, boolean makeShort) {
if (size == 0) {
return String.format("%d KB", 0);
}
if (size < 1024) {
return String.format("%d B", Long.valueOf(size));
}
if (size < 1048576) {
float f = size / 1024.0f;
if (removeZero) {
int i = (int) f;
if ((f - i) * 10.0f == 0.0f) {
return String.format("%d KB", Integer.valueOf(i));
}
}
return String.format("%.1f KB", Float.valueOf(f));
}
if (size < 1048576000) {
float f2 = (size / 1024.0f) / 1024.0f;
if (removeZero) {
int i2 = (int) f2;
if ((f2 - i2) * 10.0f == 0.0f) {
return String.format("%d MB", Integer.valueOf(i2));
}
}
return String.format("%.1f MB", Float.valueOf(f2));
}
float f3 = ((int) ((size / 1024) / 1024)) / 1000.0f;
if (removeZero) {
int i3 = (int) f3;
if ((f3 - i3) * 10.0f == 0.0f) {
return String.format("%d GB", Integer.valueOf(i3));
}
}
return makeShort ? String.format("%.1f GB", Float.valueOf(f3)) : String.format("%.2f GB", Float.valueOf(f3));
}
public static String formatShortDuration(int duration) {
return formatDuration(duration, false);
}
public static String formatLongDuration(int duration) {
return formatDuration(duration, true);
}
public static String formatDuration(int duration, boolean isLong) {
int i = duration / 3600;
int i2 = (duration / 60) % 60;
int i3 = duration % 60;
return i == 0 ? isLong ? String.format(Locale.US, "%02d:%02d", Integer.valueOf(i2), Integer.valueOf(i3)) : String.format(Locale.US, "%d:%02d", Integer.valueOf(i2), Integer.valueOf(i3)) : String.format(Locale.US, "%d:%02d:%02d", Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3));
}
public static String formatFullDuration(int duration) {
int i = duration / 3600;
int i2 = (duration / 60) % 60;
int i3 = duration % 60;
return duration < 0 ? String.format(Locale.US, "-%02d:%02d:%02d", Integer.valueOf(Math.abs(i)), Integer.valueOf(Math.abs(i2)), Integer.valueOf(Math.abs(i3))) : String.format(Locale.US, "%02d:%02d:%02d", Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3));
}
public static String formatDurationNoHours(int duration, boolean isLong) {
int i = duration / 60;
int i2 = duration % 60;
return isLong ? String.format(Locale.US, "%02d:%02d", Integer.valueOf(i), Integer.valueOf(i2)) : String.format(Locale.US, "%d:%02d", Integer.valueOf(i), Integer.valueOf(i2));
}
public static String formatShortDuration(int progress, int duration) {
return formatDuration(progress, duration, false);
}
public static String formatLongDuration(int progress, int duration) {
return formatDuration(progress, duration, true);
}
public static String formatDuration(int progress, int duration, boolean isLong) {
int i = duration / 3600;
int i2 = (duration / 60) % 60;
int i3 = duration % 60;
int i4 = progress / 3600;
int i5 = (progress / 60) % 60;
int i6 = progress % 60;
return duration == 0 ? i4 == 0 ? isLong ? String.format(Locale.US, "%02d:%02d / -:--", Integer.valueOf(i5), Integer.valueOf(i6)) : String.format(Locale.US, "%d:%02d / -:--", Integer.valueOf(i5), Integer.valueOf(i6)) : String.format(Locale.US, "%d:%02d:%02d / -:--", Integer.valueOf(i4), Integer.valueOf(i5), Integer.valueOf(i6)) : (i4 == 0 && i == 0) ? isLong ? String.format(Locale.US, "%02d:%02d / %02d:%02d", Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i2), Integer.valueOf(i3)) : String.format(Locale.US, "%d:%02d / %d:%02d", Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i2), Integer.valueOf(i3)) : String.format(Locale.US, "%d:%02d:%02d / %d:%02d:%02d", Integer.valueOf(i4), Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3));
}
public static String formatVideoDuration(int progress, int duration) {
int i = duration / 3600;
int i2 = (duration / 60) % 60;
int i3 = duration % 60;
int i4 = progress / 3600;
int i5 = (progress / 60) % 60;
int i6 = progress % 60;
return (i4 == 0 && i == 0) ? String.format(Locale.US, "%02d:%02d / %02d:%02d", Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i2), Integer.valueOf(i3)) : i == 0 ? String.format(Locale.US, "%d:%02d:%02d / %02d:%02d", Integer.valueOf(i4), Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i2), Integer.valueOf(i3)) : i4 == 0 ? String.format(Locale.US, "%02d:%02d / %d:%02d:%02d", Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)) : String.format(Locale.US, "%d:%02d:%02d / %d:%02d:%02d", Integer.valueOf(i4), Integer.valueOf(i5), Integer.valueOf(i6), Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3));
}
public static String getTempFilePath(Uri uri) {
try {
InputStream openInputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri);
File file = new File(getCacheDir(), "temp_" + System.currentTimeMillis());
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
try {
byte[] bArr = new byte[4096];
while (true) {
int read = openInputStream.read(bArr);
if (read != -1) {
fileOutputStream.write(bArr, 0, read);
} else {
fileOutputStream.flush();
openInputStream.close();
return file.getAbsolutePath();
}
}
} finally {
fileOutputStream.close();
}
} catch (Throwable th) {
openInputStream.close();
throw th;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e2) {
e2.printStackTrace();
return null;
}
}
public static String formatCount(int count) {
if (count < 1000) {
return Integer.toString(count);
}
ArrayList arrayList = new ArrayList();
while (count != 0) {
int i = count % 1000;
count /= 1000;
if (count > 0) {
arrayList.add(String.format(Locale.ENGLISH, "%03d", Integer.valueOf(i)));
} else {
arrayList.add(Integer.toString(i));
}
}
StringBuilder sb = new StringBuilder();
for (int size = arrayList.size() - 1; size >= 0; size--) {
sb.append((String) arrayList.get(size));
if (size != 0) {
sb.append(",");
}
}
return sb.toString();
}
public static String formatWholeNumber(int v, int dif) {
if (v == 0) {
return "0";
}
float f = v;
if (dif == 0) {
dif = v;
}
if (dif < 1000) {
return formatCount(v);
}
int i = 0;
while (dif >= 1000 && i < numbersSignatureArray.length - 1) {
dif /= 1000;
f /= 1000.0f;
i++;
}
if (f < 0.1d) {
return "0";
}
float f2 = f * 10.0f;
float f3 = (int) f2;
return f2 == f3 ? String.format(Locale.ENGLISH, "%s%s", formatCount((int) f), numbersSignatureArray[i]) : String.format(Locale.ENGLISH, "%.1f%s", Float.valueOf(f3 / 10.0f), numbersSignatureArray[i]);
}
public static byte[] decodeQuotedPrintable(final byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i = 0;
while (i < bytes.length) {
byte b = bytes[i];
if (b == 61) {
int i2 = i + 1;
try {
int digit = Character.digit((char) bytes[i2], 16);
i = i2 + 1;
byteArrayOutputStream.write((char) ((digit << 4) + Character.digit((char) bytes[i], 16)));
} catch (Exception e) {
FileLog.e(e);
return null;
}
} else {
byteArrayOutputStream.write(b);
}
i++;
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
try {
byteArrayOutputStream.close();
} catch (Exception e2) {
FileLog.e(e2);
}
return byteArray;
}
public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException {
return copyFile(sourceFile, new FileOutputStream(destFile));
}
public static boolean copyFile(InputStream sourceFile, OutputStream out) throws IOException {
byte[] bArr = new byte[4096];
while (true) {
int read = sourceFile.read(bArr);
if (read > 0) {
Thread.yield();
out.write(bArr, 0, read);
} else {
out.close();
return true;
}
}
}
public static boolean copyFile(File sourceFile, File destFile) throws IOException {
if (sourceFile.equals(destFile)) {
return true;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
try {
FileOutputStream fileOutputStream = new FileOutputStream(destFile);
try {
fileOutputStream.getChannel().transferFrom(fileInputStream.getChannel(), 0L, fileInputStream.getChannel().size());
fileOutputStream.close();
fileInputStream.close();
return true;
} finally {
}
} finally {
}
} catch (Exception e) {
FileLog.e(e);
return false;
}
}
public static boolean moveFile(File sourceFile, File destFile, boolean delete) {
try {
if (!destFile.exists()) {
destFile.createNewFile();
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
try {
FileOutputStream fileOutputStream = new FileOutputStream(destFile);
try {
fileOutputStream.getChannel().transferFrom(fileInputStream.getChannel(), 0L, fileInputStream.getChannel().size());
fileOutputStream.close();
fileInputStream.close();
if (delete) {
return sourceFile.delete();
}
return true;
} finally {
}
} finally {
}
} catch (Exception e) {
FileLog.e(e);
return false;
}
} catch (IOException e2) {
FileLog.e(e2);
return false;
}
}
public static byte[] calcAuthKeyHash(byte[] auth_key) {
byte[] bArr = new byte[16];
System.arraycopy(Utilities.computeSHA1(auth_key), 0, bArr, 0, 16);
return bArr;
}
public static void openDocument(MessageObject message, Activity activity, BaseFragment parentFragment) {
TLRPC$Document document;
String str;
if (message == null || (document = message.getDocument()) == null) {
return;
}
String attachFileName = message.messageOwner.media != null ? FileLoader.getAttachFileName(document) : "";
String str2 = message.messageOwner.attachPath;
File file = (str2 == null || str2.length() == 0) ? null : new File(message.messageOwner.attachPath);
if (file == null || !file.exists()) {
file = FileLoader.getInstance(UserConfig.selectedAccount).getPathToMessage(message.messageOwner);
}
if (file == null || !file.exists()) {
return;
}
if (parentFragment != null && file.getName().toLowerCase().endsWith("attheme")) {
Theme.ThemeInfo applyThemeFile = Theme.applyThemeFile(file, message.getDocumentName(), (TLRPC.TL_theme) null, true);
if (applyThemeFile != null) {
parentFragment.presentFragment((BaseFragment) new ThemePreviewActivity(applyThemeFile));
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
HashMap hashMap = new HashMap();
int i = Theme.key_dialogTopBackground;
hashMap.put("info1.**", Integer.valueOf(parentFragment.getThemedColor(i)));
hashMap.put("info2.**", Integer.valueOf(parentFragment.getThemedColor(i)));
builder.setTopAnimation(R.raw.not_available, 52, false, parentFragment.getThemedColor(i), hashMap);
builder.setTopAnimationIsNew(true);
builder.setMessage(LocaleController.getString("IncorrectTheme", R.string.IncorrectTheme));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (DialogInterface.OnClickListener) null);
parentFragment.showDialog(builder.create());
return;
}
try {
Intent intent = new Intent("android.intent.action.VIEW");
intent.setFlags(1);
MimeTypeMap singleton = MimeTypeMap.getSingleton();
int lastIndexOf = attachFileName.lastIndexOf(46);
if (lastIndexOf == -1 || ((str = singleton.getMimeTypeFromExtension(attachFileName.substring(lastIndexOf + 1).toLowerCase())) == null && ((str = document.mime_type) == null || str.length() == 0))) {
str = null;
}
if (Build.VERSION.SDK_INT >= 24) {
intent.setDataAndType(FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file), str != null ? str : "text/plain");
} else {
intent.setDataAndType(Uri.fromFile(file), str != null ? str : "text/plain");
}
if (str != null) {
try {
activity.startActivityForResult(intent, 500);
return;
} catch (Exception unused) {
if (Build.VERSION.SDK_INT >= 24) {
intent.setDataAndType(FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file), "text/plain");
} else {
intent.setDataAndType(Uri.fromFile(file), "text/plain");
}
activity.startActivityForResult(intent, 500);
return;
}
}
activity.startActivityForResult(intent, 500);
} catch (Exception unused2) {
if (activity == null) {
return;
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(activity);
HashMap hashMap2 = new HashMap();
int i2 = Theme.key_dialogTopBackground;
hashMap2.put("info1.**", Integer.valueOf(parentFragment.getThemedColor(i2)));
hashMap2.put("info2.**", Integer.valueOf(parentFragment.getThemedColor(i2)));
builder2.setTopAnimation(R.raw.not_available, 52, false, parentFragment.getThemedColor(i2), hashMap2);
builder2.setTopAnimationIsNew(true);
builder2.setPositiveButton(LocaleController.getString("OK", R.string.OK), (DialogInterface.OnClickListener) null);
builder2.setMessage(LocaleController.formatString("NoHandleAppInstalled", R.string.NoHandleAppInstalled, message.getDocument().mime_type));
parentFragment.showDialog(builder2.create());
}
}
public static boolean openForView(java.io.File r6, java.lang.String r7, java.lang.String r8, final android.app.Activity r9, org.telegram.ui.ActionBar.Theme.ResourcesProvider r10) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.openForView(java.io.File, java.lang.String, java.lang.String, android.app.Activity, org.telegram.ui.ActionBar.Theme$ResourcesProvider):boolean");
}
public static boolean openForView(MessageObject message, Activity activity, Theme.ResourcesProvider resourcesProvider) {
String str = message.messageOwner.attachPath;
File file = (str == null || str.length() == 0) ? null : new File(message.messageOwner.attachPath);
if (file == null || !file.exists()) {
file = FileLoader.getInstance(message.currentAccount).getPathToMessage(message.messageOwner);
}
int i = message.type;
return openForView(file, message.getFileName(), (i == 9 || i == 0) ? message.getMimeType() : null, activity, resourcesProvider);
}
public static boolean openForView(TLRPC$Document document, boolean forceCache, Activity activity) {
return openForView(FileLoader.getInstance(UserConfig.selectedAccount).getPathToAttach(document, true), FileLoader.getAttachFileName(document), document.mime_type, activity, null);
}
public static SpannableStringBuilder formatSpannableSimple(CharSequence format, CharSequence... cs) {
return formatSpannable(format, AndroidUtilities$.ExternalSyntheticLambda18.INSTANCE, cs);
}
public static SpannableStringBuilder formatSpannable(CharSequence format, CharSequence... cs) {
if (format.toString().contains("%s")) {
return formatSpannableSimple(format, cs);
}
return formatSpannable(format, AndroidUtilities$.ExternalSyntheticLambda19.INSTANCE, cs);
}
public static String lambda$formatSpannable$14(Integer num) {
return "%" + (num.intValue() + 1) + "$s";
}
public static SpannableStringBuilder formatSpannable(CharSequence format, GenericProvider<Integer, String> keysProvider, CharSequence... cs) {
String charSequence = format.toString();
SpannableStringBuilder valueOf = SpannableStringBuilder.valueOf(format);
for (int i = 0; i < cs.length; i++) {
String str = (String) keysProvider.provide(Integer.valueOf(i));
int indexOf = charSequence.indexOf(str);
if (indexOf != -1) {
valueOf.replace(indexOf, str.length() + indexOf, cs[i]);
charSequence = charSequence.substring(0, indexOf) + cs[i].toString() + charSequence.substring(indexOf + str.length());
}
}
return valueOf;
}
public static CharSequence replaceTwoNewLinesToOne(CharSequence original) {
char[] cArr = new char[2];
if (original instanceof StringBuilder) {
StringBuilder sb = (StringBuilder) original;
int length = original.length();
int i = 0;
while (i < length - 2) {
int i2 = i + 2;
sb.getChars(i, i2, cArr, 0);
if (cArr[0] == '\n' && cArr[1] == '\n') {
sb = sb.replace(i, i2, "\n");
i--;
length--;
}
i++;
}
return original;
}
if (original instanceof SpannableStringBuilder) {
SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) original;
int length2 = original.length();
int i3 = 0;
while (i3 < length2 - 2) {
int i4 = i3 + 2;
spannableStringBuilder.getChars(i3, i4, cArr, 0);
if (cArr[0] == '\n' && cArr[1] == '\n') {
spannableStringBuilder = spannableStringBuilder.replace(i3, i4, (CharSequence) "\n");
i3--;
length2--;
}
i3++;
}
return original;
}
return original.toString().replace("\n\n", "\n");
}
public static CharSequence replaceNewLines(CharSequence original) {
int i = 0;
if (original instanceof StringBuilder) {
StringBuilder sb = (StringBuilder) original;
int length = original.length();
while (i < length) {
if (original.charAt(i) == '\n') {
sb.setCharAt(i, ' ');
}
i++;
}
return original;
}
if (original instanceof SpannableStringBuilder) {
SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) original;
int length2 = original.length();
while (i < length2) {
if (original.charAt(i) == '\n') {
spannableStringBuilder.replace(i, i + 1, (CharSequence) " ");
}
i++;
}
return original;
}
return original.toString().replace('\n', ' ');
}
public static boolean openForView(org.telegram.tgnet.TLObject r8, android.app.Activity r9) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.openForView(org.telegram.tgnet.TLObject, android.app.Activity):boolean");
}
public static boolean isBannedForever(TLRPC.TL_chatBannedRights rights) {
return rights == null || Math.abs(((long) rights.until_date) - (System.currentTimeMillis() / 1000)) > 157680000;
}
public static void setRectToRect(Matrix matrix, RectF src, RectF dst, int rotation, int invert, boolean translate) {
float height;
float width;
float height2;
boolean z;
float f;
float f2;
float height3;
float height4;
if (rotation == 90 || rotation == 270) {
height = dst.height() / src.width();
width = dst.width();
height2 = src.height();
} else {
height = dst.width() / src.width();
width = dst.height();
height2 = src.height();
}
float f3 = width / height2;
if (height < f3) {
height = f3;
z = true;
} else {
z = false;
}
if (translate) {
matrix.setTranslate(dst.left, dst.top);
}
if (rotation == 90) {
matrix.preRotate(90.0f);
if (invert == 1) {
matrix.preScale(-1.0f, 1.0f);
} else if (invert == 2) {
matrix.preScale(1.0f, -1.0f);
}
matrix.preTranslate(0.0f, -dst.width());
} else if (rotation == 180) {
matrix.preRotate(180.0f);
if (invert == 1) {
matrix.preScale(-1.0f, 1.0f);
} else if (invert == 2) {
matrix.preScale(1.0f, -1.0f);
}
matrix.preTranslate(-dst.width(), -dst.height());
} else if (rotation == 270) {
matrix.preRotate(270.0f);
if (invert == 1) {
matrix.preScale(-1.0f, 1.0f);
} else if (invert == 2) {
matrix.preScale(1.0f, -1.0f);
}
matrix.preTranslate(-dst.height(), 0.0f);
}
if (translate) {
f = (-src.left) * height;
f2 = (-src.top) * height;
} else {
f = dst.left - (src.left * height);
f2 = dst.top - (src.top * height);
}
if (z) {
height3 = dst.width();
height4 = src.width();
} else {
height3 = dst.height();
height4 = src.height();
}
float f4 = (height3 - (height4 * height)) / 2.0f;
if (z) {
f += f4;
} else {
f2 += f4;
}
matrix.preScale(height, height);
if (translate) {
matrix.preTranslate(f, f2);
}
}
public static Vibrator getVibrator() {
if (vibrator == null) {
vibrator = (Vibrator) ApplicationLoader.applicationContext.getSystemService("vibrator");
}
return vibrator;
}
public static boolean isAccessibilityTouchExplorationEnabled() {
if (accessibilityManager == null) {
accessibilityManager = (AccessibilityManager) ApplicationLoader.applicationContext.getSystemService("accessibility");
}
return accessibilityManager.isEnabled() && accessibilityManager.isTouchExplorationEnabled();
}
public static boolean handleProxyIntent(android.app.Activity r16, android.content.Intent r17) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.handleProxyIntent(android.app.Activity, android.content.Intent):boolean");
}
public static boolean shouldEnableAnimation() {
int i = Build.VERSION.SDK_INT;
return i < 26 || i >= 28 || (!((PowerManager) ApplicationLoader.applicationContext.getSystemService("power")).isPowerSaveMode() && Settings.Global.getFloat(ApplicationLoader.applicationContext.getContentResolver(), "animator_duration_scale", 1.0f) > 0.0f);
}
public static void showProxyAlert(Activity activity, final String address, final String port, final String user, final String password, final String secret) {
String str;
BottomSheet.Builder builder = new BottomSheet.Builder(activity);
Runnable dismissRunnable = builder.getDismissRunnable();
builder.setApplyTopPadding(false);
builder.setApplyBottomPadding(false);
LinearLayout linearLayout = new LinearLayout(activity);
builder.setCustomView(linearLayout);
linearLayout.setOrientation(1);
int i = 3;
int i2 = 5;
if (!TextUtils.isEmpty(secret)) {
TextView textView = new TextView(activity);
textView.setText(LocaleController.getString("UseProxyTelegramInfo2", R.string.UseProxyTelegramInfo2));
textView.setTextColor(Theme.getColor(Theme.key_dialogTextGray4));
textView.setTextSize(1, 14.0f);
textView.setGravity(49);
linearLayout.addView(textView, LayoutHelper.createLinear(-2, -2, (LocaleController.isRTL ? 5 : 3) | 48, 17, 8, 17, 8));
View view = new View(activity);
view.setBackgroundColor(Theme.getColor(Theme.key_divider));
linearLayout.addView(view, new LinearLayout.LayoutParams(-1, 1));
}
int i3 = 0;
while (i3 < 6) {
String str2 = null;
if (i3 == 0) {
str = LocaleController.getString("UseProxyAddress", R.string.UseProxyAddress);
str2 = address;
} else if (i3 == 1) {
str2 = "" + port;
str = LocaleController.getString("UseProxyPort", R.string.UseProxyPort);
} else if (i3 == 2) {
str = LocaleController.getString("UseProxySecret", R.string.UseProxySecret);
str2 = secret;
} else if (i3 == i) {
str = LocaleController.getString("UseProxyUsername", R.string.UseProxyUsername);
str2 = user;
} else if (i3 == 4) {
str = LocaleController.getString("UseProxyPassword", R.string.UseProxyPassword);
str2 = password;
} else if (i3 == i2) {
str2 = LocaleController.getString(R.string.ProxyBottomSheetChecking);
str = LocaleController.getString(R.string.ProxyStatus);
} else {
str = null;
}
if (!TextUtils.isEmpty(str2)) {
AtomicReference atomicReference = new AtomicReference();
View view2 = new 7(activity, atomicReference);
if (i3 == i2) {
SpannableStringBuilder valueOf = SpannableStringBuilder.valueOf(str2);
EllipsizeSpanAnimator ellipsizeSpanAnimator = new EllipsizeSpanAnimator(view2);
ellipsizeSpanAnimator.addView(view2);
SpannableString spannableString = new SpannableString("...");
ellipsizeSpanAnimator.wrap(spannableString, 0);
valueOf.append((CharSequence) spannableString);
atomicReference.set(ellipsizeSpanAnimator);
view2.setTextAndValue(valueOf, str, true);
} else {
view2.setTextAndValue(str2, str, true);
}
view2.getTextView().setTextColor(Theme.usePlusTheme ? Theme.dialogTextColor : Theme.getColor(Theme.key_dialogTextBlack));
view2.getValueTextView().setTextColor(Theme.getColor(Theme.key_dialogTextGray3));
linearLayout.addView(view2, LayoutHelper.createLinear(-1, -2));
if (i3 == 5) {
try {
ConnectionsManager.getInstance(UserConfig.selectedAccount).checkProxy(address, Integer.parseInt(port), user, password, secret, new AndroidUtilities$.ExternalSyntheticLambda21(view2));
} catch (NumberFormatException unused) {
view2.getTextView().setText(LocaleController.getString(R.string.Unavailable));
view2.getTextView().setTextColor(Theme.getColor(Theme.key_text_RedRegular));
}
}
}
i3++;
i = 3;
i2 = 5;
}
PickerBottomLayout pickerBottomLayout = new PickerBottomLayout(activity, false);
pickerBottomLayout.setBackgroundColor(Theme.usePlusTheme ? Theme.dialogBGColor : Theme.getColor(Theme.key_dialogBackground));
linearLayout.addView((View) pickerBottomLayout, (ViewGroup.LayoutParams) LayoutHelper.createFrame(-1, 48, 83));
pickerBottomLayout.cancelButton.setPadding(dp(18.0f), 0, dp(18.0f), 0);
TextView textView2 = pickerBottomLayout.cancelButton;
int i4 = Theme.key_dialogTextBlue2;
textView2.setTextColor(Theme.getColor(i4));
pickerBottomLayout.cancelButton.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
pickerBottomLayout.cancelButton.setOnClickListener(new AndroidUtilities$.ExternalSyntheticLambda7(dismissRunnable));
pickerBottomLayout.doneButtonTextView.setTextColor(Theme.getColor(i4));
pickerBottomLayout.doneButton.setPadding(dp(18.0f), 0, dp(18.0f), 0);
pickerBottomLayout.doneButtonBadgeTextView.setVisibility(8);
pickerBottomLayout.doneButtonTextView.setText(LocaleController.getString("ConnectingConnectProxy", R.string.ConnectingConnectProxy).toUpperCase());
pickerBottomLayout.doneButton.setOnClickListener(new AndroidUtilities$.ExternalSyntheticLambda8(address, port, secret, password, user, activity, dismissRunnable));
pickerBottomLayout.linkButton.setVisibility(0);
pickerBottomLayout.linkButton.setTextColor(Theme.getColor(i4));
pickerBottomLayout.linkButton.setText(LocaleController.getString("Save", R.string.Save).toUpperCase());
pickerBottomLayout.linkButton.setOnClickListener(new AndroidUtilities$.ExternalSyntheticLambda9(port, secret, address, user, password, dismissRunnable));
builder.show();
}
public static void lambda$showProxyAlert$16(TextDetailSettingsCell textDetailSettingsCell, long j) {
runOnUIThread(new AndroidUtilities$.ExternalSyntheticLambda12(j, textDetailSettingsCell));
}
public static void lambda$showProxyAlert$15(long j, TextDetailSettingsCell textDetailSettingsCell) {
if (j == -1) {
textDetailSettingsCell.getTextView().setText(LocaleController.getString(R.string.Unavailable));
textDetailSettingsCell.getTextView().setTextColor(Theme.getColor(Theme.key_text_RedRegular));
return;
}
textDetailSettingsCell.getTextView().setText(LocaleController.getString(R.string.Available) + ", " + LocaleController.formatString(R.string.Ping, Long.valueOf(j)));
textDetailSettingsCell.getTextView().setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGreenText));
}
public static void lambda$showProxyAlert$18(String str, String str2, String str3, String str4, String str5, Activity activity, Runnable runnable, View view) {
SharedConfig.ProxyInfo proxyInfo;
boolean z;
UndoView undoView;
SharedPreferences.Editor edit = MessagesController.getGlobalMainSettings().edit();
edit.putBoolean("proxy_enabled", true);
edit.putString("proxy_ip", str);
int intValue = Utilities.parseInt(str2).intValue();
edit.putInt("proxy_port", intValue);
if (TextUtils.isEmpty(str3)) {
edit.remove("proxy_secret");
if (TextUtils.isEmpty(str4)) {
edit.remove("proxy_pass");
} else {
edit.putString("proxy_pass", str4);
}
if (TextUtils.isEmpty(str5)) {
edit.remove("proxy_user");
} else {
edit.putString("proxy_user", str5);
}
proxyInfo = new SharedConfig.ProxyInfo(str, intValue, str5, str4, "");
} else {
edit.remove("proxy_pass");
edit.remove("proxy_user");
edit.putString("proxy_secret", str3);
proxyInfo = new SharedConfig.ProxyInfo(str, intValue, "", "", str3);
}
edit.commit();
SharedConfig.currentProxy = SharedConfig.addProxy(proxyInfo);
ConnectionsManager.setProxySettings(true, str, intValue, str5, str4, str3);
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.proxySettingsChanged, new Object[0]);
if (activity instanceof LaunchActivity) {
ChatActivity lastFragment = ((LaunchActivity) activity).getActionBarLayout().getLastFragment();
if (!(lastFragment instanceof ChatActivity) || (undoView = lastFragment.getUndoView()) == null) {
z = false;
} else {
undoView.showWithAction(0L, 87, (Runnable) null);
z = true;
}
if (!z) {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.showBulletin, new Object[]{6, LocaleController.getString(R.string.ProxyAddedSuccess)});
}
} else {
NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.showBulletin, new Object[]{6, LocaleController.getString(R.string.ProxyAddedSuccess)});
}
runnable.run();
}
public static void lambda$showProxyAlert$19(String str, String str2, String str3, String str4, String str5, Runnable runnable, View view) {
SharedConfig.ProxyInfo proxyInfo;
int intValue = Utilities.parseInt(str).intValue();
if (TextUtils.isEmpty(str2)) {
proxyInfo = new SharedConfig.ProxyInfo(str3, intValue, str4, str5, "");
} else {
proxyInfo = new SharedConfig.ProxyInfo(str3, intValue, "", "", str2);
}
SharedConfig.addProxy(proxyInfo);
runnable.run();
}
@SuppressLint({"PrivateApi"})
public static String getSystemProperty(String key) {
try {
return (String) Class.forName("android.os.SystemProperties").getMethod("get", String.class).invoke(null, key);
} catch (Exception unused) {
return null;
}
}
public static void fixGoogleMapsBug() {
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("google_bug_154855417", 0);
if (sharedPreferences.contains("fixed")) {
return;
}
new File(ApplicationLoader.getFilesDirFixed(), "ZoomTables.data").delete();
sharedPreferences.edit().putBoolean("fixed", true).apply();
}
public static CharSequence concat(CharSequence... text) {
if (text.length == 0) {
return "";
}
int i = 0;
boolean z = true;
if (text.length == 1) {
return text[0];
}
int length = text.length;
int i2 = 0;
while (true) {
if (i2 >= length) {
z = false;
break;
}
if (text[i2] instanceof Spanned) {
break;
}
i2++;
}
if (z) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
int length2 = text.length;
while (i < length2) {
CharSequence charSequence = text[i];
if (charSequence == null) {
charSequence = "null";
}
spannableStringBuilder.append(charSequence);
i++;
}
return new SpannedString(spannableStringBuilder);
}
StringBuilder sb = new StringBuilder();
int length3 = text.length;
while (i < length3) {
sb.append(text[i]);
i++;
}
return sb.toString();
}
public static float[] RGBtoHSB(int r, int g, int b) {
float[] fArr = new float[3];
int max = Math.max(r, g);
if (b > max) {
max = b;
}
int min = Math.min(r, g);
if (b < min) {
min = b;
}
float f = max;
float f2 = f / 255.0f;
float f3 = 0.0f;
float f4 = max != 0 ? (max - min) / f : 0.0f;
if (f4 != 0.0f) {
float f5 = max - min;
float f6 = (max - r) / f5;
float f7 = (max - g) / f5;
float f8 = (max - b) / f5;
float f9 = (r == max ? f8 - f7 : g == max ? (f6 + 2.0f) - f8 : (f7 + 4.0f) - f6) / 6.0f;
f3 = f9 < 0.0f ? f9 + 1.0f : f9;
}
fArr[0] = f3;
fArr[1] = f4;
fArr[2] = f2;
return fArr;
}
public static int HSBtoRGB(float hue, float saturation, float brightness) {
int i;
int i2;
int i3 = 0;
if (saturation == 0.0f) {
i3 = (int) ((brightness * 255.0f) + 0.5f);
i = i3;
i2 = i;
} else {
float floor = (hue - ((float) Math.floor(hue))) * 6.0f;
float floor2 = floor - ((float) Math.floor(floor));
float f = (1.0f - saturation) * brightness;
float f2 = (1.0f - (saturation * floor2)) * brightness;
float f3 = (1.0f - (saturation * (1.0f - floor2))) * brightness;
int i4 = (int) floor;
if (i4 == 0) {
i3 = (int) ((brightness * 255.0f) + 0.5f);
i = (int) ((f3 * 255.0f) + 0.5f);
} else if (i4 == 1) {
i3 = (int) ((f2 * 255.0f) + 0.5f);
i = (int) ((brightness * 255.0f) + 0.5f);
} else if (i4 != 2) {
if (i4 == 3) {
i3 = (int) ((f * 255.0f) + 0.5f);
i = (int) ((f2 * 255.0f) + 0.5f);
} else if (i4 == 4) {
i3 = (int) ((f3 * 255.0f) + 0.5f);
i = (int) ((f * 255.0f) + 0.5f);
} else if (i4 != 5) {
i = 0;
i2 = 0;
} else {
i3 = (int) ((brightness * 255.0f) + 0.5f);
i = (int) ((f * 255.0f) + 0.5f);
i2 = (int) ((f2 * 255.0f) + 0.5f);
}
i2 = (int) ((brightness * 255.0f) + 0.5f);
} else {
i3 = (int) ((f * 255.0f) + 0.5f);
i = (int) ((brightness * 255.0f) + 0.5f);
i2 = (int) ((f3 * 255.0f) + 0.5f);
}
i2 = (int) ((f * 255.0f) + 0.5f);
}
return ((i & 255) << 8) | (-16777216) | ((i3 & 255) << 16) | (i2 & 255);
}
public static float computePerceivedBrightness(int color) {
return (((Color.red(color) * 0.2126f) + (Color.green(color) * 0.7152f)) + (Color.blue(color) * 0.0722f)) / 255.0f;
}
public static int getPatternColor(int color) {
return getPatternColor(color, false);
}
public static int getPatternColor(int color, boolean alwaysDark) {
float[] RGBtoHSB = RGBtoHSB(Color.red(color), Color.green(color), Color.blue(color));
if (RGBtoHSB[1] > 0.0f || (RGBtoHSB[2] < 1.0f && RGBtoHSB[2] > 0.0f)) {
RGBtoHSB[1] = Math.min(1.0f, RGBtoHSB[1] + (alwaysDark ? 0.15f : 0.05f) + ((1.0f - RGBtoHSB[1]) * 0.1f));
}
if (alwaysDark || RGBtoHSB[2] > 0.5f) {
RGBtoHSB[2] = Math.max(0.0f, RGBtoHSB[2] * 0.65f);
} else {
RGBtoHSB[2] = Math.max(0.0f, Math.min(1.0f, 1.0f - (RGBtoHSB[2] * 0.65f)));
}
return HSBtoRGB(RGBtoHSB[0], RGBtoHSB[1], RGBtoHSB[2]) & (alwaysDark ? -1711276033 : 1728053247);
}
public static int getPatternSideColor(int color) {
float[] RGBtoHSB = RGBtoHSB(Color.red(color), Color.green(color), Color.blue(color));
RGBtoHSB[1] = Math.min(1.0f, RGBtoHSB[1] + 0.05f);
if (RGBtoHSB[2] > 0.5f) {
RGBtoHSB[2] = Math.max(0.0f, RGBtoHSB[2] * 0.9f);
} else {
RGBtoHSB[2] = Math.max(0.0f, RGBtoHSB[2] * 0.9f);
}
return HSBtoRGB(RGBtoHSB[0], RGBtoHSB[1], RGBtoHSB[2]) | (-16777216);
}
public static String getWallPaperUrl(Object object) {
if (object instanceof TLRPC.TL_wallPaper) {
TLRPC.TL_wallPaper tL_wallPaper = (TLRPC.TL_wallPaper) object;
String str = "https://" + MessagesController.getInstance(UserConfig.selectedAccount).linkPrefix + "/bg/" + ((TLRPC.WallPaper) tL_wallPaper).slug;
StringBuilder sb = new StringBuilder();
TLRPC.WallPaperSettings wallPaperSettings = ((TLRPC.WallPaper) tL_wallPaper).settings;
if (wallPaperSettings != null) {
if (wallPaperSettings.blur) {
sb.append("blur");
}
if (((TLRPC.WallPaper) tL_wallPaper).settings.motion) {
if (sb.length() > 0) {
sb.append("+");
}
sb.append("motion");
}
}
if (sb.length() <= 0) {
return str;
}
return str + "?mode=" + sb.toString();
}
if (object instanceof WallpapersListActivity.ColorWallpaper) {
return ((WallpapersListActivity.ColorWallpaper) object).getUrl();
}
return null;
}
public static float distanceInfluenceForSnapDuration(float f) {
return (float) Math.sin((f - 0.5f) * 0.47123894f);
}
public static void makeAccessibilityAnnouncement(CharSequence what) {
if (TextUtils.isEmpty(what)) {
return;
}
AccessibilityManager accessibilityManager2 = (AccessibilityManager) ApplicationLoader.applicationContext.getSystemService("accessibility");
if (accessibilityManager2.isEnabled()) {
AccessibilityEvent obtain = AccessibilityEvent.obtain();
obtain.setEventType(16384);
obtain.getText().add(what);
accessibilityManager2.sendAccessibilityEvent(obtain);
}
}
public static int getOffsetColor(int color1, int color2, float offset, float alpha) {
int red = Color.red(color2);
int green = Color.green(color2);
int blue = Color.blue(color2);
int alpha2 = Color.alpha(color2);
int red2 = Color.red(color1);
int green2 = Color.green(color1);
int blue2 = Color.blue(color1);
return Color.argb((int) ((Color.alpha(color1) + ((alpha2 - r7) * offset)) * alpha), (int) (red2 + ((red - red2) * offset)), (int) (green2 + ((green - green2) * offset)), (int) (blue2 + ((blue - blue2) * offset)));
}
public static int indexOfIgnoreCase(final String origin, final String searchStr) {
if (searchStr.isEmpty() || origin.isEmpty()) {
return origin.indexOf(searchStr);
}
for (int i = 0; i < origin.length() && searchStr.length() + i <= origin.length(); i++) {
int i2 = 0;
for (int i3 = i; i3 < origin.length() && i2 < searchStr.length() && Character.toLowerCase(origin.charAt(i3)) == Character.toLowerCase(searchStr.charAt(i2)); i3++) {
i2++;
}
if (i2 == searchStr.length()) {
return i;
}
}
return -1;
}
public static double lerp(double a, double b, float f) {
double d = f;
Double.isNaN(d);
return a + (d * (b - a));
}
public static float lerp(float[] ab, float f) {
return lerp(ab[0], ab[1], f);
}
public static void lerp(RectF a, RectF b, float f, RectF to) {
if (to != null) {
to.set(lerp(a.left, b.left, f), lerp(a.top, b.top, f), lerp(a.right, b.right, f), lerp(a.bottom, b.bottom, f));
}
}
public static void lerp(Rect a, Rect b, float f, Rect to) {
if (to != null) {
to.set(lerp(a.left, b.left, f), lerp(a.top, b.top, f), lerp(a.right, b.right, f), lerp(a.bottom, b.bottom, f));
}
}
public static void lerp(int[] a, int[] b, float f, int[] to) {
if (to == null) {
return;
}
int i = 0;
while (i < to.length) {
to[i] = lerp((a == null || i >= a.length) ? 0 : a[i], (b == null || i >= b.length) ? 0 : b[i], f);
i++;
}
}
public static float cascade(float fullAnimationT, float position, float count, float waveLength) {
if (count <= 0.0f) {
return fullAnimationT;
}
float min = (1.0f / count) * Math.min(waveLength, count);
return MathUtils.clamp((fullAnimationT - ((position / count) * (1.0f - min))) / min, 0.0f, 1.0f);
}
public static int multiplyAlphaComponent(int color, float k) {
return ColorUtils.setAlphaComponent(color, (int) (Color.alpha(color) * k));
}
public static float computeDampingRatio(float tension, float friction, float mass) {
return friction / (((float) Math.sqrt(mass * tension)) * 2.0f);
}
public static void openSharing(BaseFragment fragment, String url) {
if (fragment == null || fragment.getParentActivity() == null) {
return;
}
fragment.showDialog(new ShareAlert(fragment.getParentActivity(), (ArrayList) null, url, false, url, false));
}
public static boolean allowScreenCapture() {
return SharedConfig.passcodeHash.length() == 0 || SharedConfig.allowScreenCapture;
}
public static File getSharingDirectory() {
return new File(FileLoader.getDirectory(4), "sharing/");
}
public static String getCertificateSHA256Fingerprint() {
try {
return Utilities.bytesToHex(Utilities.computeSHA256(((X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 64).signatures[0].toByteArray()))).getEncoded()));
} catch (Throwable unused) {
return "";
}
}
public static boolean isPunctuationCharacter(char ch) {
if (charactersMap == null) {
charactersMap = new HashSet<>();
int i = 0;
while (true) {
char[] cArr = characters;
if (i >= cArr.length) {
break;
}
charactersMap.add(Character.valueOf(cArr[i]));
i++;
}
}
return charactersMap.contains(Character.valueOf(ch));
}
public static int getColorDistance(int color1, int color2) {
int red = Color.red(color1);
int green = Color.green(color1);
int blue = Color.blue(color1);
int red2 = Color.red(color2);
int i = (red + red2) / 2;
int i2 = red - red2;
int green2 = green - Color.green(color2);
int blue2 = blue - Color.blue(color2);
return ((((i + 512) * i2) * i2) >> 8) + (green2 * 4 * green2) + ((((767 - i) * blue2) * blue2) >> 8);
}
public static int getAverageColor(int color1, int color2) {
return Color.argb(255, (Color.red(color1) / 2) + (Color.red(color2) / 2), (Color.green(color1) / 2) + (Color.green(color2) / 2), (Color.blue(color1) / 2) + (Color.blue(color2) / 2));
}
public static void setLightStatusBar(Window window, boolean enable) {
setLightStatusBar(window, enable, false);
}
public static void setLightStatusBar(Window window, boolean enable, boolean forceTransparentStatusbar) {
if (Build.VERSION.SDK_INT >= 23) {
View decorView = window.getDecorView();
int systemUiVisibility = decorView.getSystemUiVisibility();
if (enable) {
if ((systemUiVisibility & 8192) == 0) {
decorView.setSystemUiVisibility(systemUiVisibility | 8192);
}
if (window.getStatusBarColor() != 0) {
window.setStatusBarColor(0);
return;
}
return;
}
if ((systemUiVisibility & 8192) != 0) {
decorView.setSystemUiVisibility(systemUiVisibility & (-8193));
}
if (window.getStatusBarColor() != 0) {
window.setStatusBarColor(0);
}
}
}
public static boolean getLightNavigationBar(Window window) {
return Build.VERSION.SDK_INT >= 26 && (window.getDecorView().getSystemUiVisibility() & 16) > 0;
}
public static void setLightNavigationBar(View view, boolean enable) {
if (view == null || Build.VERSION.SDK_INT < 26) {
return;
}
int systemUiVisibility = view.getSystemUiVisibility();
if (((systemUiVisibility & 16) > 0) != enable) {
view.setSystemUiVisibility(enable ? systemUiVisibility | 16 : systemUiVisibility & (-17));
}
}
public static void setLightStatusBar(View view, boolean enable) {
if (view == null || Build.VERSION.SDK_INT < 26) {
return;
}
int systemUiVisibility = view.getSystemUiVisibility();
if (((systemUiVisibility & 8192) > 0) != enable) {
view.setSystemUiVisibility(enable ? systemUiVisibility | 8192 : systemUiVisibility & (-8193));
}
}
public static void setLightNavigationBar(Window window, boolean enable) {
if (window != null) {
setLightNavigationBar(window.getDecorView(), enable);
}
}
public static void setNavigationBarColor(Window window, int color) {
setNavigationBarColor(window, color, true);
}
public static void setNavigationBarColor(Window window, int color, boolean animated) {
setNavigationBarColor(window, color, animated, null);
}
public static void setNavigationBarColor(Window window, int color, boolean animated, IntColorCallback onUpdate) {
ValueAnimator valueAnimator;
if (window != null && Build.VERSION.SDK_INT >= 21) {
HashMap<Window, ValueAnimator> hashMap = navigationBarColorAnimators;
if (hashMap != null && (valueAnimator = hashMap.get(window)) != null) {
valueAnimator.cancel();
navigationBarColorAnimators.remove(window);
}
if (!animated) {
if (onUpdate != null) {
onUpdate.run(color);
}
try {
window.setNavigationBarColor(color);
return;
} catch (Exception unused) {
return;
}
}
ValueAnimator ofArgb = ValueAnimator.ofArgb(window.getNavigationBarColor(), color);
ofArgb.addUpdateListener(new AndroidUtilities$.ExternalSyntheticLambda2(onUpdate, window));
ofArgb.addListener(new 8(window));
ofArgb.setDuration(200L);
ofArgb.setInterpolator(CubicBezierInterpolator.DEFAULT);
ofArgb.start();
if (navigationBarColorAnimators == null) {
navigationBarColorAnimators = new HashMap<>();
}
navigationBarColorAnimators.put(window, ofArgb);
}
}
public static void lambda$setNavigationBarColor$20(IntColorCallback intColorCallback, Window window, ValueAnimator valueAnimator) {
int intValue = ((Integer) valueAnimator.getAnimatedValue()).intValue();
if (intColorCallback != null) {
intColorCallback.run(intValue);
}
try {
window.setNavigationBarColor(intValue);
} catch (Exception unused) {
}
}
public static boolean checkHostForPunycode(String url) {
boolean z;
boolean z2;
if (url == null) {
return false;
}
try {
int length = url.length();
z = false;
z2 = false;
for (int i = 0; i < length; i++) {
try {
char charAt = url.charAt(i);
if (charAt != '.' && charAt != '-' && charAt != '/' && charAt != '+' && (charAt < '0' || charAt > '9')) {
if ((charAt < 'a' || charAt > 'z') && (charAt < 'A' || charAt > 'Z')) {
z2 = true;
} else {
z = true;
}
if (z && z2) {
break;
}
}
} catch (Exception e) {
e = e;
FileLog.e(e);
return !z ? false : false;
}
}
} catch (Exception e2) {
e = e2;
z = false;
z2 = false;
}
if (!z && z2) {
return true;
}
}
public static boolean shouldShowUrlInAlert(String url) {
try {
return checkHostForPunycode(Uri.parse(url).getHost());
} catch (Exception e) {
FileLog.e(e);
return false;
}
}
public static void scrollToFragmentRow(INavigationLayout parentLayout, String rowName) {
if (parentLayout == null || rowName == null) {
return;
}
BaseFragment baseFragment = (BaseFragment) parentLayout.getFragmentStack().get(parentLayout.getFragmentStack().size() - 1);
try {
Field declaredField = baseFragment.getClass().getDeclaredField("listView");
declaredField.setAccessible(true);
RecyclerListView recyclerListView = (RecyclerListView) declaredField.get(baseFragment);
recyclerListView.highlightRow(new AndroidUtilities$.ExternalSyntheticLambda22(baseFragment, rowName, recyclerListView));
declaredField.setAccessible(false);
} catch (Throwable unused) {
}
}
public static int lambda$scrollToFragmentRow$21(BaseFragment baseFragment, String str, RecyclerListView recyclerListView) {
int i = -1;
try {
Field declaredField = baseFragment.getClass().getDeclaredField(str);
declaredField.setAccessible(true);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerListView.getLayoutManager();
i = declaredField.getInt(baseFragment);
linearLayoutManager.scrollToPositionWithOffset(i, dp(60.0f));
declaredField.setAccessible(false);
return i;
} catch (Throwable unused) {
return i;
}
}
public static boolean checkInlinePermissions(Context context) {
return Build.VERSION.SDK_INT < 23 || Settings.canDrawOverlays(context);
}
public static void updateVisibleRows(RecyclerListView listView) {
RecyclerView.Adapter adapter;
RecyclerView.ViewHolder childViewHolder;
if (listView == null || (adapter = listView.getAdapter()) == null) {
return;
}
for (int i = 0; i < listView.getChildCount(); i++) {
View childAt = listView.getChildAt(i);
int childAdapterPosition = listView.getChildAdapterPosition(childAt);
if (childAdapterPosition >= 0 && (childViewHolder = listView.getChildViewHolder(childAt)) != null && !childViewHolder.shouldIgnore()) {
adapter.onBindViewHolder(childViewHolder, childAdapterPosition);
}
}
}
public static void updateImageViewImageAnimated(ImageView imageView, int newIcon) {
updateImageViewImageAnimated(imageView, ContextCompat.getDrawable(imageView.getContext(), newIcon));
}
public static void updateImageViewImageAnimated(ImageView imageView, Drawable newIcon) {
if (imageView.getDrawable() == newIcon) {
return;
}
ValueAnimator duration = ValueAnimator.ofFloat(0.0f, 1.0f).setDuration(150L);
duration.addUpdateListener(new AndroidUtilities$.ExternalSyntheticLambda1(imageView, new AtomicBoolean(), newIcon));
duration.start();
}
public static void lambda$updateImageViewImageAnimated$22(ImageView imageView, AtomicBoolean atomicBoolean, Drawable drawable, ValueAnimator valueAnimator) {
float floatValue = ((Float) valueAnimator.getAnimatedValue()).floatValue();
float abs = Math.abs(floatValue - 0.5f) + 0.5f;
imageView.setScaleX(abs);
imageView.setScaleY(abs);
if (floatValue < 0.5f || atomicBoolean.get()) {
return;
}
atomicBoolean.set(true);
imageView.setImageDrawable(drawable);
}
public static void updateViewVisibilityAnimated(View view, boolean show) {
updateViewVisibilityAnimated(view, show, 1.0f, true, true);
}
public static void updateViewVisibilityAnimated(View view, boolean show, float scaleFactor, boolean animated) {
updateViewVisibilityAnimated(view, show, scaleFactor, true, animated);
}
public static void updateViewVisibilityAnimated(View view, boolean show, float scaleFactor, boolean goneOnHide, boolean animated) {
updateViewVisibilityAnimated(view, show, scaleFactor, goneOnHide, 1.0f, animated);
}
public static void updateViewVisibilityAnimated(View view, boolean show, float scaleFactor, boolean goneOnHide, float maxAlpha, boolean animated) {
if (view == null) {
return;
}
if (view.getParent() == null) {
animated = false;
}
if (!animated) {
view.animate().setListener(null).cancel();
view.setVisibility(show ? 0 : goneOnHide ? 8 : 4);
view.setTag(show ? 1 : null);
view.setAlpha(maxAlpha);
view.setScaleX(1.0f);
view.setScaleY(1.0f);
return;
}
if (show && view.getTag() == null) {
view.animate().setListener(null).cancel();
if (view.getVisibility() != 0) {
view.setVisibility(0);
view.setAlpha(0.0f);
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
}
view.animate().alpha(maxAlpha).scaleY(1.0f).scaleX(1.0f).setDuration(150L).start();
view.setTag(1);
return;
}
if (show || view.getTag() == null) {
return;
}
view.animate().setListener(null).cancel();
view.animate().alpha(0.0f).scaleY(scaleFactor).scaleX(scaleFactor).setListener(new HideViewAfterAnimation(view, goneOnHide)).setDuration(150L).start();
view.setTag(null);
}
public static void updateViewShow(View view, boolean show) {
updateViewShow(view, show, true, true);
}
public static void updateViewShow(View view, boolean show, boolean scale, boolean animated) {
updateViewShow(view, show, scale, 0.0f, animated, null);
}
public static void updateViewShow(View view, boolean show, boolean scale, boolean animated, Runnable onDone) {
updateViewShow(view, show, scale, 0.0f, animated, onDone);
}
public static void updateViewShow(View view, boolean show, boolean scale, float translate, boolean animated, Runnable onDone) {
if (view == null) {
return;
}
if (view.getParent() == null) {
animated = false;
}
view.animate().setListener(null).cancel();
if (!animated) {
view.setVisibility(show ? 0 : 8);
view.setTag(show ? 1 : null);
view.setAlpha(1.0f);
view.setScaleX((!scale || show) ? 1.0f : 0.0f);
if (scale && !show) {
r3 = 0.0f;
}
view.setScaleY(r3);
if (translate != 0.0f) {
view.setTranslationY(show ? 0.0f : dp(-16.0f) * translate);
}
if (onDone != null) {
onDone.run();
return;
}
return;
}
if (show) {
if (view.getVisibility() != 0) {
view.setVisibility(0);
view.setAlpha(0.0f);
view.setScaleX(scale ? 0.0f : 1.0f);
view.setScaleY(scale ? 0.0f : 1.0f);
if (translate != 0.0f) {
view.setTranslationY(dp(-16.0f) * translate);
}
}
ViewPropertyAnimator withEndAction = view.animate().alpha(1.0f).scaleY(1.0f).scaleX(1.0f).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340L).withEndAction(onDone);
if (translate != 0.0f) {
withEndAction.translationY(0.0f);
}
withEndAction.start();
return;
}
ViewPropertyAnimator withEndAction2 = view.animate().alpha(0.0f).scaleY(scale ? 0.0f : 1.0f).scaleX(scale ? 0.0f : 1.0f).setListener(new HideViewAfterAnimation(view)).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).setDuration(340L).withEndAction(onDone);
if (translate != 0.0f) {
withEndAction2.translationY(dp(-16.0f) * translate);
}
withEndAction2.start();
}
public static long getPrefIntOrLong(SharedPreferences preferences, String key, long defaultValue) {
try {
return preferences.getLong(key, defaultValue);
} catch (Exception unused) {
return preferences.getInt(key, (int) defaultValue);
}
}
public static Bitmap getScaledBitmap(float w, float h, String path, String streamPath, int streamOffset) {
FileInputStream fileInputStream;
BitmapFactory.Options options;
int i;
int i2;
Bitmap decodeStream;
int i3;
try {
try {
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
if (path != null) {
BitmapFactory.decodeFile(path, options);
fileInputStream = null;
} else {
fileInputStream = new FileInputStream(streamPath);
try {
fileInputStream.getChannel().position(streamOffset);
BitmapFactory.decodeStream(fileInputStream, null, options);
} catch (Throwable th) {
th = th;
try {
FileLog.e(th);
if (fileInputStream != null) {
fileInputStream.close();
}
return null;
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (Exception e) {
FileLog.e(e);
}
}
}
}
}
i = options.outWidth;
} catch (Exception e2) {
FileLog.e(e2);
}
} catch (Throwable th2) {
th = th2;
fileInputStream = null;
}
if (i <= 0 || (i2 = options.outHeight) <= 0) {
if (fileInputStream != null) {
fileInputStream.close();
}
return null;
}
if (w > h && i < i2) {
h = w;
w = h;
}
float min = Math.min(i / w, i2 / h);
options.inSampleSize = 1;
if (min > 1.0f) {
do {
i3 = options.inSampleSize * 2;
options.inSampleSize = i3;
} while (i3 < min);
}
options.inJustDecodeBounds = false;
if (path != null) {
decodeStream = BitmapFactory.decodeFile(path, options);
} else {
fileInputStream.getChannel().position(streamOffset);
decodeStream = BitmapFactory.decodeStream(fileInputStream, null, options);
}
return decodeStream;
}
public static Uri getBitmapShareUri(Bitmap bitmap, String fileName, Bitmap.CompressFormat format) {
File cacheDir = getCacheDir();
if (!cacheDir.isDirectory()) {
try {
cacheDir.mkdirs();
} catch (Exception e) {
FileLog.e(e);
return null;
}
}
File file = new File(cacheDir, fileName);
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
try {
bitmap.compress(format, 87, fileOutputStream);
fileOutputStream.close();
Uri uriForFile = FileProvider.getUriForFile(ApplicationLoader.applicationContext, ApplicationLoader.getApplicationId() + ".provider", file);
fileOutputStream.close();
return uriForFile;
} finally {
}
} catch (Exception e2) {
FileLog.e(e2);
return null;
}
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException unused) {
return false;
}
}
public static boolean isAccessibilityScreenReaderEnabled() {
return isAccessibilityTouchExplorationEnabled();
}
public static CharSequence trim(CharSequence text, int[] newStart) {
if (text == null) {
return null;
}
int length = text.length();
int i = 0;
while (i < length && text.charAt(i) <= ' ') {
i++;
}
while (i < length && text.charAt(length - 1) <= ' ') {
length--;
}
if (newStart != null) {
newStart[0] = i;
}
return (i > 0 || length < text.length()) ? text.subSequence(i, length) : text;
}
public static boolean isENOSPC(Exception e) {
return (Build.VERSION.SDK_INT >= 21 && (e instanceof IOException) && (e.getCause() instanceof ErrnoException) && ((ErrnoException) e.getCause()).errno == OsConstants.ENOSPC) || (e.getMessage() != null && e.getMessage().equalsIgnoreCase("no space left on device"));
}
public static boolean isEROFS(Exception e) {
return (Build.VERSION.SDK_INT >= 21 && (e instanceof IOException) && (e.getCause() instanceof ErrnoException) && ((ErrnoException) e.getCause()).errno == OsConstants.EROFS) || (e.getMessage() != null && e.getMessage().toLowerCase().contains("read-only file system"));
}
public static SpannableStringBuilder replaceCharSequence(String what, CharSequence from, CharSequence obj) {
SpannableStringBuilder spannableStringBuilder;
if (from instanceof SpannableStringBuilder) {
spannableStringBuilder = (SpannableStringBuilder) from;
} else {
spannableStringBuilder = new SpannableStringBuilder(from);
}
int indexOf = TextUtils.indexOf(from, what);
if (indexOf >= 0) {
spannableStringBuilder.replace(indexOf, what.length() + indexOf, obj);
}
return spannableStringBuilder;
}
public static CharSequence replaceMultipleCharSequence(String what, CharSequence from, CharSequence obj) {
SpannableStringBuilder spannableStringBuilder;
if (from instanceof SpannableStringBuilder) {
spannableStringBuilder = (SpannableStringBuilder) from;
} else {
spannableStringBuilder = new SpannableStringBuilder(from);
}
int indexOf = TextUtils.indexOf(from, what, 0);
while (indexOf >= 0) {
spannableStringBuilder.replace(indexOf, what.length() + indexOf, obj);
indexOf = TextUtils.indexOf(spannableStringBuilder, what, indexOf + 1);
}
return spannableStringBuilder;
}
public static Bitmap makeBlurBitmap(View view) {
return makeBlurBitmap(view, 6.0f, 7);
}
public static Bitmap makeBlurBitmap(View view, float downscale, int maxRadius) {
if (view == null) {
return null;
}
int width = (int) (view.getWidth() / downscale);
int height = (int) (view.getHeight() / downscale);
Bitmap createBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(createBitmap);
float f = 1.0f / downscale;
canvas.scale(f, f);
canvas.drawColor(Theme.getColor(Theme.key_windowBackgroundWhite));
view.draw(canvas);
Utilities.stackBlurBitmap(createBitmap, Math.max(maxRadius, Math.max(width, height) / 180));
return createBitmap;
}
public static List<View> allGlobalViews() {
int i;
try {
i = Build.VERSION.SDK_INT;
} catch (Exception e) {
FileLog.e("allGlobalViews()", e);
}
if (i >= 29) {
return WindowInspector.getGlobalWindowViews();
}
if (i >= 17) {
Class<?> cls = Class.forName("android.view.WindowManagerGlobal");
Object invoke = cls.getMethod("getInstance", new Class[0]).invoke(null, null);
Method method = cls.getMethod("getViewRootNames", new Class[0]);
Method method2 = cls.getMethod("getRootView", String.class);
String[] strArr = (String[]) method.invoke(invoke, null);
ArrayList arrayList = new ArrayList();
for (String str : strArr) {
arrayList.add((View) method2.invoke(invoke, str));
}
return arrayList;
}
if (i >= 14 && i < 17) {
Class<?> cls2 = Class.forName("android.view.WindowManagerImpl");
Object invoke2 = cls2.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]);
Field declaredField = cls2.getDeclaredField("mViews");
declaredField.setAccessible(true);
Object obj = declaredField.get(invoke2);
if (obj instanceof List) {
return (List) declaredField.get(invoke2);
}
if (obj instanceof View[]) {
return Arrays.asList((View[]) declaredField.get(invoke2));
}
}
return null;
}
public static boolean hasDialogOnTop(BaseFragment fragment) {
List<View> allGlobalViews;
if (fragment == null) {
return false;
}
if (fragment.visibleDialog != null) {
return true;
}
return (fragment.getParentLayout() == null || (allGlobalViews = allGlobalViews()) == null || allGlobalViews.isEmpty() || allGlobalViews.get(allGlobalViews.size() - 1) == getRootView(fragment.getParentLayout().getView())) ? false : true;
}
public static View getRootView(View v) {
while (v != null && (v.getParent() instanceof View)) {
v = (View) v.getParent();
}
return v;
}
public static void makeGlobalBlurBitmap(Utilities.Callback<Bitmap> onBitmapDone, float amount) {
makeGlobalBlurBitmap(onBitmapDone, amount, (int) amount, null, null);
}
public static void makeGlobalBlurBitmap(Utilities.Callback<Bitmap> onBitmapDone, float downscale, int amount, View forView, List<View> exclude) {
int width;
int height;
if (onBitmapDone == null) {
return;
}
List<View> allGlobalViews = allGlobalViews();
if (allGlobalViews == null) {
onBitmapDone.run((Object) null);
return;
}
makingGlobalBlurBitmap = true;
try {
try {
if (forView == null) {
width = (int) (r7.x / downscale);
height = displaySize.y + statusBarHeight;
} else {
width = (int) (forView.getWidth() / downscale);
height = forView.getHeight();
}
int i = (int) (height / downscale);
int[] iArr = new int[2];
Bitmap createBitmap = Bitmap.createBitmap(width, i, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(createBitmap);
if (forView != null) {
forView.getLocationOnScreen(iArr);
canvas.translate((-iArr[0]) / downscale, (-iArr[1]) / downscale);
}
float f = 1.0f / downscale;
canvas.scale(f, f);
canvas.drawColor(Theme.getColor(Theme.key_windowBackgroundWhite));
for (int i2 = 0; i2 < allGlobalViews.size(); i2++) {
View view = allGlobalViews.get(i2);
if (!(view instanceof PipRoundVideoView.PipFrameLayout) && !(view instanceof PipRoundVideoView.PipFrameLayout) && (exclude == null || !exclude.contains(view))) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
if (layoutParams instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams layoutParams2 = (WindowManager.LayoutParams) layoutParams;
if ((layoutParams2.flags & 2) != 0) {
canvas.drawColor(ColorUtils.setAlphaComponent(-16777216, (int) (layoutParams2.dimAmount * 255.0f)));
}
}
canvas.save();
view.getLocationOnScreen(iArr);
canvas.translate(iArr[0] / downscale, iArr[1] / downscale);
try {
view.draw(canvas);
} catch (Exception unused) {
}
canvas.restore();
}
}
Utilities.stackBlurBitmap(createBitmap, Math.max(amount, Math.max(width, i) / 180));
onBitmapDone.run(createBitmap);
} catch (Exception e) {
FileLog.e(e);
onBitmapDone.run((Object) null);
}
} finally {
makingGlobalBlurBitmap = false;
}
}
public static int[] roundPercents(float[] percents, int[] output) {
Objects.requireNonNull(percents, "percents or output is null");
if (output == null) {
output = new int[percents.length];
}
if (percents.length != output.length) {
throw new IndexOutOfBoundsException("percents.length != output.length");
}
float f = 0.0f;
for (float f2 : percents) {
f += f2;
}
int i = 0;
for (int i2 = 0; i2 < percents.length; i2++) {
int floor = (int) Math.floor((percents[i2] / f) * 100.0f);
output[i2] = floor;
i += floor;
}
while (i < 100) {
int i3 = -1;
float f3 = 0.0f;
for (int i4 = 0; i4 < percents.length; i4++) {
float f4 = (percents[i4] / f) - (output[i4] / 100.0f);
if (percents[i4] > 0.0f && f4 >= f3) {
i3 = i4;
f3 = f4;
}
}
if (i3 < 0) {
break;
}
output[i3] = output[i3] + 1;
i++;
}
return output;
}
public static boolean isRTL(CharSequence text) {
if (text != null && text.length() > 0) {
for (int i = 0; i < text.length(); i++) {
char charAt = text.charAt(i);
if (charAt >= 1424 && charAt <= 1791) {
return true;
}
}
}
return false;
}
private static Pattern getURIParsePattern() {
if (uriParse == null) {
uriParse = Pattern.compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
}
return uriParse;
}
public static String getHostAuthority(String uri) {
if (uri == null) {
return null;
}
Matcher matcher = getURIParsePattern().matcher(uri);
if (!matcher.matches()) {
return null;
}
String group = matcher.group(4);
return group != null ? group.toLowerCase() : group;
}
public static String getHostAuthority(Uri uri) {
if (uri == null) {
return null;
}
return getHostAuthority(uri.toString());
}
public static boolean intersect1d(int x1, int x2, int y1, int y2) {
return Math.max(x1, x2) > Math.min(y1, y2) && Math.max(y1, y2) > Math.min(x1, x2);
}
public static boolean intersect1dInclusive(int x1, int x2, int y1, int y2) {
return Math.max(x1, x2) >= Math.min(y1, y2) && Math.max(y1, y2) >= Math.min(x1, x2);
}
public static java.lang.String getSysInfoString(java.lang.String r3) {
throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.AndroidUtilities.getSysInfoString(java.lang.String):java.lang.String");
}
public static Long getSysInfoLong(String path) {
String sysInfoString = getSysInfoString(path);
if (sysInfoString == null) {
return null;
}
try {
return Utilities.parseLong(sysInfoString);
} catch (Exception unused) {
return null;
}
}
public static boolean isActivityRunning(Activity activity) {
if (activity == null) {
return false;
}
if (Build.VERSION.SDK_INT >= 17) {
return (activity.isDestroyed() || activity.isFinishing()) ? false : true;
}
return !activity.isFinishing();
}
public static boolean isSafeToShow(Context context) {
Activity findActivity = findActivity(context);
if (findActivity == null) {
return true;
}
return isActivityRunning(findActivity);
}
public static Pair<Integer, Integer> getImageOrientation(InputStream is) {
try {
return getImageOrientation(new ExifInterface(is));
} catch (Exception e) {
FileLog.e(e);
return new Pair<>(0, 0);
}
}
public static Pair<Integer, Integer> getImageOrientation(File file) {
try {
return getImageOrientation(new ExifInterface(file));
} catch (Exception e) {
FileLog.e(e);
return new Pair<>(0, 0);
}
}
public static Pair<Integer, Integer> getImageOrientation(String path) {
try {
return getImageOrientation(new ExifInterface(path));
} catch (Exception unused) {
return new Pair<>(0, 0);
}
}
public static Pair<Integer, Integer> getImageOrientation(ExifInterface exif) {
try {
int i = 1;
int i2 = 270;
switch (exif.getAttributeInt("Orientation", 1)) {
case 2:
i2 = 0;
break;
case 3:
i2 = 180;
i = 0;
break;
case 4:
i = 2;
i2 = 0;
break;
case 5:
i = 2;
break;
case 6:
i2 = 90;
i = 0;
break;
case 7:
break;
case 8:
i = 0;
break;
default:
i = 0;
i2 = 0;
break;
}
return new Pair<>(Integer.valueOf(i2), Integer.valueOf(i));
} catch (Exception e) {
FileLog.e(e);
return new Pair<>(0, 0);
}
}
public static void forEachViews(View view, Consumer<View> consumer) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
consumer.accept(view);
forEachViews(viewGroup.getChildAt(i), consumer);
}
return;
}
consumer.accept(view);
}
public static void forEachViews(RecyclerView recyclerView, Consumer<View> consumer) {
if (recyclerView == null) {
return;
}
for (int i = 0; i < recyclerView.getChildCount(); i++) {
consumer.accept(recyclerView.getChildAt(i));
}
for (int i2 = 0; i2 < recyclerView.getCachedChildCount(); i2++) {
consumer.accept(recyclerView.getCachedChildAt(i2));
}
for (int i3 = 0; i3 < recyclerView.getHiddenChildCount(); i3++) {
consumer.accept(recyclerView.getHiddenChildAt(i3));
}
for (int i4 = 0; i4 < recyclerView.getAttachedScrapChildCount(); i4++) {
consumer.accept(recyclerView.getAttachedScrapChildAt(i4));
}
}
public static int getDominantColor(Bitmap bitmap) {
if (bitmap == null) {
return -1;
}
float height = (bitmap.getHeight() - 1) / 10.0f;
float width = (bitmap.getWidth() - 1) / 10.0f;
int i = 0;
int i2 = 0;
int i3 = 0;
int i4 = 0;
for (int i5 = 0; i5 < 10; i5++) {
for (int i6 = 0; i6 < 10; i6++) {
int pixel = bitmap.getPixel((int) (i5 * width), (int) (i6 * height));
if (Color.alpha(pixel) > 200) {
i2 += Color.red(pixel);
i3 += Color.green(pixel);
i4 += Color.blue(pixel);
i++;
}
}
}
if (i == 0) {
return 0;
}
return Color.argb(255, i2 / i, i3 / i, i4 / i);
}
public static String translitSafe(String str) {
if (str != null) {
try {
str = str.toLowerCase();
} catch (Exception unused) {
return "";
}
}
String translitString = LocaleController.getInstance().getTranslitString(str, false);
return translitString == null ? "" : translitString;
}
public static void quietSleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException unused) {
}
}
public static ByteBuffer cloneByteBuffer(ByteBuffer original) {
ByteBuffer allocate;
try {
allocate = ByteBuffer.allocate(original.capacity());
} catch (OutOfMemoryError unused) {
System.gc();
allocate = ByteBuffer.allocate(original.capacity());
}
int position = original.position();
original.rewind();
allocate.put(original);
original.rewind();
allocate.flip();
allocate.position(position);
return allocate;
}
public static void checkAndroidTheme(Context context, boolean open) {
if (context == null) {
return;
}
context.setTheme((Theme.isCurrentThemeDark() && open) ? R.style.Theme_TMessages_Dark : R.style.Theme_TMessages);
}
public static boolean isHonor() {
boolean z;
if (isHonor == null) {
try {
String lowerCase = Build.BRAND.toLowerCase();
if (!lowerCase.contains("huawei") && !lowerCase.contains("honor")) {
z = false;
isHonor = Boolean.valueOf(z);
}
z = true;
isHonor = Boolean.valueOf(z);
} catch (Exception e) {
FileLog.e(e);
isHonor = Boolean.FALSE;
}
}
return isHonor.booleanValue();
}
public static CharSequence withLearnMore(CharSequence text, Runnable onClick) {
SpannableString spannableString = new SpannableString(LocaleController.getString(R.string.LearnMoreArrow));
spannableString.setSpan(new 9(onClick), 0, spannableString.length(), 33);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
spannableStringBuilder.append((CharSequence) " ");
spannableStringBuilder.append((CharSequence) spannableString);
return replaceArrows(spannableStringBuilder, true);
}
public static View findChildViewUnder(ViewGroup parent, float x, float y) {
if (parent == null || parent.getVisibility() != 0) {
return null;
}
for (int i = 0; i < parent.getChildCount(); i++) {
View childAt = parent.getChildAt(i);
if (childAt != null && childAt.getVisibility() == 0) {
if (childAt instanceof ViewGroup) {
View findChildViewUnder = findChildViewUnder((ViewGroup) childAt, x - childAt.getLeft(), y - childAt.getTop());
if (findChildViewUnder != null) {
return findChildViewUnder;
}
} else if (x >= childAt.getX() && x <= childAt.getX() + childAt.getWidth() && y >= childAt.getY() && x <= childAt.getY() + childAt.getHeight()) {
return childAt;
}
}
}
return null;
}
public static void vibrateCursor(View view) {
if (view != null) {
try {
if (view.getContext() != null && Build.VERSION.SDK_INT >= 26 && ((Vibrator) view.getContext().getSystemService("vibrator")).hasAmplitudeControl() && !PlusSettings.disableActionsVibrations) {
view.performHapticFeedback(9, 1);
}
} catch (Exception unused) {
}
}
}
public static void vibrate(View view) {
if (view != null) {
try {
if (view.getContext() != null && Build.VERSION.SDK_INT >= 26 && ((Vibrator) view.getContext().getSystemService("vibrator")).hasAmplitudeControl() && !PlusSettings.disableActionsVibrations) {
view.performHapticFeedback(3, 1);
}
} catch (Exception unused) {
}
}
}
public static File getExternalStorageFilesPath() {
if (Build.VERSION.SDK_INT >= 19) {
try {
for (File file : ApplicationLoader.applicationContext.getExternalFilesDirs(null)) {
if (!file.getPath().contains(Environment.getExternalStorageDirectory().getPath())) {
return file;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Environment.getExternalStorageDirectory();
}
public static void setCursorColor(EditText view, int color) {
try {
if (Build.VERSION.SDK_INT >= 29) {
view.setTextCursorDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{color, color}));
return;
}
Field declaredField = TextView.class.getDeclaredField("mCursorDrawableRes");
declaredField.setAccessible(true);
int i = declaredField.getInt(view);
Field declaredField2 = TextView.class.getDeclaredField("mEditor");
declaredField2.setAccessible(true);
Object obj = declaredField2.get(view);
Drawable drawable = ContextCompat.getDrawable(view.getContext(), i);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
Drawable[] drawableArr = {drawable, drawable};
Field declaredField3 = obj.getClass().getDeclaredField("mCursorDrawable");
declaredField3.setAccessible(true);
declaredField3.set(obj, drawableArr);
} catch (Exception unused) {
}
}
public static void setListViewEdgeEffectColor(AbsListView listView, int color) {
if (Build.VERSION.SDK_INT >= 21) {
try {
Field declaredField = AbsListView.class.getDeclaredField("mEdgeGlowTop");
declaredField.setAccessible(true);
EdgeEffect edgeEffect = (EdgeEffect) declaredField.get(listView);
if (edgeEffect != null) {
edgeEffect.setColor(color);
}
Field declaredField2 = AbsListView.class.getDeclaredField("mEdgeGlowBottom");
declaredField2.setAccessible(true);
EdgeEffect edgeEffect2 = (EdgeEffect) declaredField2.get(listView);
if (edgeEffect2 != null) {
edgeEffect2.setColor(color);
}
} catch (Exception e) {
FileLog.e(e);
}
}
}
public static void brandGlowEffect(Context context, int brandColor) {
context.getResources().getDrawable(context.getResources().getIdentifier("overscroll_glow", "drawable", "android")).setColorFilter(brandColor, PorterDuff.Mode.SRC_IN);
context.getResources().getDrawable(context.getResources().getIdentifier("overscroll_edge", "drawable", "android")).setColorFilter(brandColor, PorterDuff.Mode.SRC_IN);
}
public static int getIntColor(String key) {
return ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getInt(key, defColor);
}
public static int getIntTColor(String key) {
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0);
return sharedPreferences.getInt(key, sharedPreferences.getInt("themeColor", defColor));
}
public static int getIntDef(String key, int def) {
return ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getInt(key, def);
}
public static int getIntAlphaColor(String key, int def, float factor) {
int i = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getInt(key, def);
return Color.argb(Math.round(Color.alpha(i) * factor), Color.red(i), Color.green(i), Color.blue(i));
}
public static int getIntAlphaColor(int color, float factor) {
return Color.argb(Math.round(Color.alpha(color) * factor), Color.red(color), Color.green(color), Color.blue(color));
}
public static int getIntDarkerColor(String key, int factor) {
return setDarkColor(ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getInt(key, defColor), factor);
}
public static int setDarkColor(int color, int factor) {
int alpha = Color.alpha(color);
int red = Color.red(color) - factor;
int green = Color.green(color) - factor;
int blue = Color.blue(color) - factor;
if (factor < 0) {
if (red > 255) {
red = 255;
}
if (green > 255) {
green = 255;
}
if (blue > 255) {
blue = 255;
}
if (red == 255 && green == 255 && blue == 255) {
blue = factor;
red = blue;
green = red;
}
}
if (factor > 0) {
if (red < 0) {
red = 0;
}
if (green < 0) {
green = 0;
}
if (blue < 0) {
blue = 0;
}
if (red == 0 && green == 0 && blue == 0) {
blue = factor;
green = blue;
return Color.argb(alpha, factor, green, blue);
}
}
factor = red;
return Color.argb(alpha, factor, green, blue);
}
public static void setStringPref(Context context, String key, String s) {
SharedPreferences.Editor edit = context.getSharedPreferences(THEME_PREFS, 0).edit();
edit.putString(key, s);
edit.commit();
}
public static boolean getBoolPref(String key) {
return ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, 0).getBoolean(key, false);
}
public static boolean getBoolMain(String key) {
return ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", 0).getBoolean(key, false);
}
public static String getVersion() {
try {
PackageInfo packageInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
return String.format(Locale.US, "Plus v%s-%d", packageInfo.versionName, Integer.valueOf(packageInfo.versionCode));
} catch (Exception e) {
FileLog.e(e);
return null;
}
}
public static int getDefBubbleColor() {
if (getIntColor("themeColor") != -16738680) {
return getIntDarkerColor("themeColor", -80);
}
return -5054501;
}
public static void checkForExternalStoragePermission(final Activity context) {
try {
if (context.getPackageManager().getLaunchIntentForPackage(BuildVars.BETA ? "es.rafalense.telegram.themes.beta" : "es.rafalense.telegram.themes") == null) {
if (context.getPackageManager().getLaunchIntentForPackage(BuildVars.BETA ? "es.rafalense.themes.beta" : "es.rafalense.themes") == null) {
return;
}
}
PlusUtils.askForExternalStoragePermission(context, false);
} catch (Exception e) {
FileLog.e(e);
}
}
public static void resetCheckForThemes() {
lastCheck = -1L;
SharedPreferences.Editor edit = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", 0).edit();
edit.remove("repeatPeriod");
edit.remove("repeatPeriod_");
edit.remove("lastTime");
edit.apply();
}
public static void checkForThemes(final Activity context) {
long j;
boolean z;
try {
map = new HashMap<>();
if (PlusSettings.disableCheckForThemes) {
sendAnalytics("checkForThemesReturn", map);
return;
}
SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", 0);
int i = sharedPreferences.getInt("repeatPeriod_0", 1);
long j2 = i * 24 * 60 * 60 * 1000;
StringBuilder sb = new StringBuilder();
sb.append("es.rafalense.telegram.themes");
sb.append(BuildVars.BETA ? ".beta" : "");
String sb2 = sb.toString();
Intent launchIntentForPackage = context.getPackageManager().getLaunchIntentForPackage(sb2);
boolean z2 = launchIntentForPackage != null;
StringBuilder sb3 = new StringBuilder();
sb3.append("checkForThemes");
sb3.append(z2 ? "Open" : "Market");
String sb4 = sb3.toString();
if (lastCheck >= 0) {
long currentTimeMillis = System.currentTimeMillis();
long j3 = lastCheck;
if (currentTimeMillis - j3 >= j2 || j3 <= 0) {
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putLong("lastTime", System.currentTimeMillis()).apply();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(LocaleController.getString("Themes", R.string.Themes));
builder.setMessage(LocaleController.getString("ThemesAppMsg", R.string.ThemesAppMsg));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new 10(context, launchIntentForPackage, sb2, sb4));
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), new 11(edit, "repeatPeriod_", "repeatPeriod_0", sb4));
builder.create().show();
z = true;
j = 0;
lastCheck = sharedPreferences.getLong("lastTime", j);
map.put("lastCheck", lastCheck + "");
map.put("delay", j2 + "");
map.put("repeatPeriod", i + "");
map.put("dialogShown", z + "");
map.put("currentTag", "repeatPeriod_0");
sendAnalytics(sb4, map);
}
}
j = 0;
if (lastCheck < 0) {
checkForExternalStoragePermission(context);
}
z = false;
lastCheck = sharedPreferences.getLong("lastTime", j);
map.put("lastCheck", lastCheck + "");
map.put("delay", j2 + "");
map.put("repeatPeriod", i + "");
map.put("dialogShown", z + "");
map.put("currentTag", "repeatPeriod_0");
sendAnalytics(sb4, map);
} catch (Exception e) {
FileLog.e(e);
}
}
public static void sendAnalytics(String event, HashMap<String, String> map2) {
map2.put("isPlusDialogEnabled", PlusSettings.isPlusDialogEnabled() + "");
map2.put("plusDialogEnabled", PlusSettings.plusDialogEnabled + "");
map2.put("versionCode", SharedConfig.buildVersion() + "");
map2.put("version", BuildVars.BUILD_VERSION_STRING);
AnalyticsHelper.trackEvent(event, map2);
}
public static void setDrawableStatesColor(Context context, ImageView imageView, int pressed, int normal, int color) {
StateListDrawable stateListDrawable = new StateListDrawable();
Drawable drawable = context.getResources().getDrawable(pressed);
drawable.setColorFilter(Theme.lightColor, PorterDuff.Mode.SRC_IN);
stateListDrawable.addState(new int[]{R.attr.state_pressed}, drawable);
stateListDrawable.addState(new int[]{R.attr.state_focused}, drawable);
stateListDrawable.addState(new int[0], context.getResources().getDrawable(normal));
imageView.setImageDrawable(stateListDrawable);
}
public static boolean isAppInstalled(Context ctx, String packageName) {
try {
ctx.getPackageManager().getPackageInfo(packageName, 1);
return true;
} catch (PackageManager.NameNotFoundException unused) {
return false;
}
}
}