Commit 93fa5019 authored by DrKLO's avatar DrKLO

Update to 2.5.0

Photo editor
Passcode
Sections in shared media\files
parent dff666fc
......@@ -3,7 +3,7 @@ buildscript {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0'
classpath 'com.android.tools.build:gradle:1.1.0'
}
}
apply plugin: 'com.android.application'
......@@ -82,7 +82,7 @@ android {
defaultConfig {
minSdkVersion 8
targetSdkVersion 21
versionCode 423
versionName "2.4.0"
versionCode 453
versionName "2.5.0"
}
}
......@@ -104,7 +104,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_STATIC_LIBRARIES := webp sqlite
LOCAL_MODULE := tmessages.5
LOCAL_MODULE := tmessages.6
LOCAL_CFLAGS := -w -std=gnu99 -O2 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -fno-math-errno
LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math
......
......@@ -21,6 +21,9 @@ jmethodID jclass_Bitmap_createBitmap;
jclass jclass_Config;
jfieldID jclass_Config_ARGB_8888;
const uint32_t PGPhotoEnhanceHistogramBins = 256;
const uint32_t PGPhotoEnhanceSegments = 4;
jclass createGlobarRef(JNIEnv *env, jclass class) {
if (class) {
return (*env)->NewGlobalRef(env, class);
......@@ -312,6 +315,110 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_blurBitmap(JNIEnv *env, jcl
AndroidBitmap_unlockPixels(env, bitmap);
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_calcCDT(JNIEnv *env, jclass class, jobject hsvBuffer, int width, int height, jobject buffer) {
float imageWidth = width;
float imageHeight = height;
float _clipLimit = 1.25f;
uint32_t totalSegments = PGPhotoEnhanceSegments * PGPhotoEnhanceSegments;
uint32_t tileArea = (uint32_t)(floorf(imageWidth / PGPhotoEnhanceSegments) * floorf(imageHeight / PGPhotoEnhanceSegments));
uint32_t clipLimit = (uint32_t)max(1, _clipLimit * tileArea / (float) PGPhotoEnhanceHistogramBins);
float scale = 255.0f / (float) tileArea;
unsigned char *bytes = (*env)->GetDirectBufferAddress(env, hsvBuffer);
uint32_t **hist = calloc(totalSegments, sizeof(uint32_t *));
uint32_t **cdfs = calloc(totalSegments, sizeof(uint32_t *));
uint32_t *cdfsMin = calloc(totalSegments, sizeof(uint32_t));
uint32_t *cdfsMax = calloc(totalSegments, sizeof(uint32_t));
for (uint32_t a = 0; a < totalSegments; a++) {
hist[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
cdfs[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
}
float xMul = PGPhotoEnhanceSegments / imageWidth;
float yMul = PGPhotoEnhanceSegments / imageHeight;
for (uint32_t y = 0; y < imageHeight; y++) {
uint32_t yOffset = y * width * 4;
for (uint32_t x = 0; x < imageWidth; x++) {
uint32_t index = x * 4 + yOffset;
uint32_t tx = (uint32_t)(x * xMul);
uint32_t ty = (uint32_t)(y * yMul);
uint32_t t = ty * PGPhotoEnhanceSegments + tx;
hist[t][bytes[index + 2]]++;
}
}
for (uint32_t i = 0; i < totalSegments; i++) {
if (clipLimit > 0) {
uint32_t clipped = 0;
for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
if (hist[i][j] > clipLimit) {
clipped += hist[i][j] - clipLimit;
hist[i][j] = clipLimit;
}
}
uint32_t redistBatch = clipped / PGPhotoEnhanceHistogramBins;
uint32_t residual = clipped - redistBatch * PGPhotoEnhanceHistogramBins;
for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
hist[i][j] += redistBatch;
}
for (uint32_t j = 0; j < residual; ++j) {
hist[i][j]++;
}
}
memcpy(cdfs[i], hist[i], PGPhotoEnhanceHistogramBins * sizeof(uint32_t));
uint32_t hMin = PGPhotoEnhanceHistogramBins - 1;
for (uint32_t j = 0; j < hMin; ++j) {
if (cdfs[j] != 0) {
hMin = j;
}
}
uint32_t cdf = 0;
for (uint32_t j = hMin; j < PGPhotoEnhanceHistogramBins; ++j) {
cdf += cdfs[i][j];
cdfs[i][j] = (uint8_t) min(255, cdf * scale);
}
cdfsMin[i] = cdfs[i][hMin];
cdfsMax[i] = cdfs[i][PGPhotoEnhanceHistogramBins - 1];
}
uint32_t resultSize = 4 * PGPhotoEnhanceHistogramBins * totalSegments;
uint32_t resultBytesPerRow = 4 * PGPhotoEnhanceHistogramBins;
unsigned char *result = (*env)->GetDirectBufferAddress(env, buffer);
for (uint32_t tile = 0; tile < totalSegments; tile++) {
uint32_t yOffset = tile * resultBytesPerRow;
for (uint32_t i = 0; i < PGPhotoEnhanceHistogramBins; i++) {
uint32_t index = i * 4 + yOffset;
result[index] = (uint8_t)cdfs[tile][i];
result[index + 1] = (uint8_t)cdfsMin[tile];
result[index + 2] = (uint8_t)cdfsMax[tile];
result[index + 3] = 255;
}
}
for (uint32_t a = 0; a < totalSegments; a++) {
free(hist[a]);
free(cdfs[a]);
}
free(hist);
free(cdfs);
free(cdfsMax);
free(cdfsMin);
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jobject bitmap, int scale, int width, int height, int stride) {
AndroidBitmapInfo info;
......
......@@ -23,6 +23,7 @@ import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.StateSet;
import android.view.Display;
import android.view.Surface;
......@@ -33,12 +34,16 @@ import android.widget.AbsListView;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.UserConfig;
import org.telegram.ui.Components.ForegroundDetector;
import org.telegram.ui.Components.NumberPicker;
import org.telegram.ui.Components.TypefaceSpan;
......@@ -59,6 +64,7 @@ public class AndroidUtilities {
public static float density = 1;
public static Point displaySize = new Point();
public static Integer photoSize = null;
public static DisplayMetrics displayMetrics = new DisplayMetrics();
private static Boolean isTablet = null;
static {
......@@ -67,7 +73,7 @@ public class AndroidUtilities {
}
public static void lockOrientation(Activity activity) {
if (activity == null || prevOrientation != -10) {
if (activity == null || prevOrientation != -10 || Build.VERSION.SDK_INT < 9) {
return;
}
try {
......@@ -115,7 +121,7 @@ public class AndroidUtilities {
}
public static void unlockOrientation(Activity activity) {
if (activity == null) {
if (activity == null || Build.VERSION.SDK_INT < 9) {
return;
}
try {
......@@ -228,12 +234,13 @@ public class AndroidUtilities {
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
display.getMetrics(displayMetrics);
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x" + displayMetrics.ydpi);
}
}
} catch (Exception e) {
......@@ -241,6 +248,10 @@ public class AndroidUtilities {
}
}
public static float getPixelsInCM(float cm, boolean isX) {
return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);
}
public static long makeBroadcastId(int id) {
return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL);
}
......@@ -421,6 +432,19 @@ public class AndroidUtilities {
}
}
public static void setProgressBarAnimationDuration(ProgressBar progressBar, int duration) {
if (progressBar == null) {
return;
}
try {
Field mCursorDrawableRes = ProgressBar.class.getDeclaredField("mDuration");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.setInt(progressBar, duration);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static int getViewInset(View view) {
if (view == null || Build.VERSION.SDK_INT < 21) {
return 0;
......@@ -530,4 +554,18 @@ public class AndroidUtilities {
}
return stringBuilder;
}
public static boolean needShowPasscode(boolean reset) {
boolean wasInBackground;
if (Build.VERSION.SDK_INT >= 14) {
wasInBackground = ForegroundDetector.getInstance().isWasInBackground(reset);
if (reset) {
ForegroundDetector.getInstance().resetBackgroundVar();
}
} else {
wasInBackground = UserConfig.lastPauseTime != 0;
}
return UserConfig.passcodeHash.length() > 0 && wasInBackground &&
(UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());
}
}
......@@ -344,7 +344,7 @@ public class ImageLoader {
});
}
});
AndroidUtilities.runOnUIThread(new Runnable() {
imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
......@@ -354,7 +354,7 @@ public class ImageLoader {
@Override
protected void onCancelled() {
AndroidUtilities.runOnUIThread(new Runnable() {
imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
......@@ -633,7 +633,7 @@ public class ImageLoader {
}
}
if (cacheImage.filter == null || blur) {
if (cacheImage.filter == null || blur || cacheImage.httpUrl != null) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else {
opts.inPreferredConfig = Bitmap.Config.RGB_565;
......@@ -1057,6 +1057,12 @@ public class ImageLoader {
FileLog.e("tmessages", e);
}
}
try {
new File(cachePath, ".nomedia").createNewFile();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath);
FileLog.e("tmessages", "cache path = " + cachePath);
......@@ -1678,42 +1684,47 @@ public class ImageLoader {
runHttpFileLoadTasks(null, 0);
}
private void runHttpFileLoadTasks(HttpFileTask oldTask, int reason) {
if (oldTask != null) {
currentHttpFileLoadTasksCount--;
}
if (oldTask != null) {
if (reason == 1) {
if (oldTask.canRetry) {
final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
Runnable runnable = new Runnable() {
@Override
public void run() {
httpFileLoadTasks.add(newTask);
runHttpFileLoadTasks(null, 0);
private void runHttpFileLoadTasks(final HttpFileTask oldTask, final int reason) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (oldTask != null) {
currentHttpFileLoadTasksCount--;
}
if (oldTask != null) {
if (reason == 1) {
if (oldTask.canRetry) {
final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
Runnable runnable = new Runnable() {
@Override
public void run() {
httpFileLoadTasks.add(newTask);
runHttpFileLoadTasks(null, 0);
}
};
retryHttpsTasks.put(oldTask.url, runnable);
AndroidUtilities.runOnUIThread(runnable, 1000);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
}
};
retryHttpsTasks.put(oldTask.url, runnable);
AndroidUtilities.runOnUIThread(runnable, 1000);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
} else if (reason == 2) {
httpFileLoadTasksByKeys.remove(oldTask.url);
File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
}
}
while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
HttpFileTask task = httpFileLoadTasks.poll();
if (android.os.Build.VERSION.SDK_INT >= 11) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
task.execute(null, null, null);
}
currentHttpFileLoadTasksCount++;
}
} else if (reason == 2) {
httpFileLoadTasksByKeys.remove(oldTask.url);
File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
}
}
while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
HttpFileTask task = httpFileLoadTasks.poll();
if (android.os.Build.VERSION.SDK_INT >= 11) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
task.execute(null, null, null);
}
currentHttpFileLoadTasksCount++;
}
});
}
public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight, boolean useMaxScale) {
......
......@@ -69,6 +69,8 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private int alpha = 255;
private boolean isPressed;
private boolean disableRecycle;
private int orientation;
private boolean centerRotation;
private ImageReceiverDelegate delegate;
public ImageReceiver() {
......@@ -209,6 +211,15 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return isPressed;
}
public void setOrientation(int angle, boolean center) {
orientation = angle;
centerRotation = center;
}
public int getOrientation() {
return orientation;
}
public void setImageBitmap(Bitmap bitmap) {
setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null);
}
......@@ -280,8 +291,17 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.drawRoundRect(roundRect, roundRadius, roundRadius, roundPaint);
}
} else {
int bitmapW = bitmapDrawable.getIntrinsicWidth();
int bitmapH = bitmapDrawable.getIntrinsicHeight();
int bitmapW;
int bitmapH;
int originalW = bitmapDrawable.getIntrinsicWidth();
int originalH = bitmapDrawable.getIntrinsicHeight();
if (orientation == 90 || orientation == 270) {
bitmapW = bitmapDrawable.getIntrinsicHeight();
bitmapH = bitmapDrawable.getIntrinsicWidth();
} else {
bitmapW = bitmapDrawable.getIntrinsicWidth();
bitmapH = bitmapDrawable.getIntrinsicHeight();
}
float scaleW = bitmapW / (float) imageW;
float scaleH = bitmapH / (float) imageH;
......@@ -312,14 +332,32 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.save();
canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH);
if (orientation != 0) {
if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2);
} else {
canvas.rotate(orientation, 0, 0);
}
}
if (bitmapW / scaleH > imageW) {
bitmapW /= scaleH;
originalW /= scaleH;
drawRegion.set(imageX - (bitmapW - imageW) / 2, imageY, imageX + (bitmapW + imageW) / 2, imageY + imageH);
} else {
bitmapH /= scaleW;
originalH /= scaleW;
drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2);
}
bitmapDrawable.setBounds(drawRegion);
if (orientation == 90 || orientation == 270) {
int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2;
int centerY = (drawRegion.top + drawRegion.bottom) / 2;
bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
} else {
bitmapDrawable.setBounds(drawRegion);
}
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
......@@ -339,8 +377,24 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.restore();
} else {
canvas.save();
if (orientation != 0) {
if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2);
} else {
canvas.rotate(orientation, 0, 0);
}
}
drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH);
bitmapDrawable.setBounds(drawRegion);
if (orientation == 90 || orientation == 270) {
int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2;
int centerY = (drawRegion.top + drawRegion.bottom) / 2;
bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
} else {
bitmapDrawable.setBounds(drawRegion);
}
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
......@@ -357,6 +411,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
FileLog.e("tmessages", e);
}
}
canvas.restore();
}
}
}
......@@ -391,6 +446,16 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return null;
}
public int getBitmapWidth() {
Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getWidth() : bitmap.getHeight();
}
public int getBitmapHeight() {
Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getHeight() : bitmap.getWidth();
}
public void setVisible(boolean value, boolean invalidate) {
if (isVisible == value) {
return;
......
......@@ -54,6 +54,7 @@ public class LocaleController {
public static FastDateFormat formatterWeek;
public static FastDateFormat formatterMonth;
public static FastDateFormat formatterYear;
public static FastDateFormat formatterMonthYear;
public static FastDateFormat formatterYearMax;
public static FastDateFormat chatDate;
public static FastDateFormat chatFullDate;
......@@ -135,7 +136,7 @@ public class LocaleController {
addRules(new String[]{"bem", "brx", "da", "de", "el", "en", "eo", "es", "et", "fi", "fo", "gl", "he", "iw", "it", "nb",
"nl", "nn", "no", "sv", "af", "bg", "bn", "ca", "eu", "fur", "fy", "gu", "ha", "is", "ku",
"lb", "ml", "mr", "nah", "ne", "om", "or", "pa", "pap", "ps", "so", "sq", "sw", "ta", "te",
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt"}, new PluralRules_One());
"tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt", "an", "ast"}, new PluralRules_One());
addRules(new String[]{"cs", "sk"}, new PluralRules_Czech());
addRules(new String[]{"ff", "fr", "kab"}, new PluralRules_French());
addRules(new String[]{"hr", "ru", "sr", "uk", "be", "bs", "sh"}, new PluralRules_Balkan());
......@@ -544,6 +545,9 @@ public class LocaleController {
currentLocale = newLocale;
currentLocaleInfo = localeInfo;
currentPluralRules = allRules.get(currentLocale.getLanguage());
if (currentPluralRules == null) {
currentPluralRules = allRules.get("en");
}
changingConfiguration = true;
Locale.setDefault(currentLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
......@@ -571,6 +575,9 @@ public class LocaleController {
if (value == null) {
value = ApplicationLoader.applicationContext.getString(res);
}
if (value == null) {
value = "LOC_ERR:" + key;
}
return value;
}
......@@ -638,6 +645,9 @@ public class LocaleController {
}
currentLocale = newLocale;
currentPluralRules = allRules.get(currentLocale.getLanguage());
if (currentPluralRules == null) {
currentPluralRules = allRules.get("en");
}
}
}
}
......@@ -695,6 +705,20 @@ public class LocaleController {
}
}
private FastDateFormat createFormatter(Locale locale, String format, String defaultFormat) {
if (format == null || format.length() == 0) {
format = defaultFormat;
}
FastDateFormat formatter = null;
try {
formatter = FastDateFormat.getInstance(format, locale);
} catch (Exception e) {
format = defaultFormat;
formatter = FastDateFormat.getInstance(format, locale);
}
return formatter;
}
public void recreateFormatters() {
Locale locale = currentLocale;
if (locale == null) {
......@@ -706,59 +730,15 @@ public class LocaleController {
}
isRTL = lang.toLowerCase().equals("ar");
nameDisplayOrder = lang.toLowerCase().equals("ko") ? 2 : 1;
String formatString = getStringInternal("formatterMonth", R.string.formatterMonth);
if (formatString == null || formatString.length() == 0) {
formatString = "dd MMM";
}
formatterMonth = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterYear", R.string.formatterYear);
if (formatString == null || formatString.length() == 0) {
formatString = "dd.MM.yy";
}
formatterYear = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterYearMax", R.string.formatterYearMax);
if (formatString == null || formatString.length() == 0) {
formatString = "dd.MM.yyyy";
}
formatterYearMax = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("chatDate", R.string.chatDate);
if (formatString == null || formatString.length() == 0) {
formatString = "d MMMM";
}
chatDate = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("chatFullDate", R.string.chatFullDate);
if (formatString == null || formatString.length() == 0) {
formatString = "d MMMM yyyy";
}
chatFullDate = FastDateFormat.getInstance(formatString, locale);
formatString = getStringInternal("formatterWeek", R.string.formatterWeek);
if (formatString == null || formatString.length() == 0) {
formatString = "EEE";
}
formatterWeek = FastDateFormat.getInstance(formatString, locale);
if (is24HourFormat) {
formatString = getStringInternal("formatterDay24H", R.string.formatterDay24H);
} else {
formatString = getStringInternal("formatterDay12H", R.string.formatterDay12H);
}
if (formatString == null || formatString.length() == 0) {
if (is24HourFormat) {
formatString = "HH:mm";
} else {
formatString = "h:mm a";
}
}
if (lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko")) {
formatterDay = FastDateFormat.getInstance(formatString, locale);
} else {
formatterDay = FastDateFormat.getInstance(formatString, Locale.US);
}
formatterMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM");
formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy");
formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy");
chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM");
chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy");
formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE");
formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMMM yyyy");
formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H), is24HourFormat ? "HH:mm" : "h:mm a");
}
public static String stringForMessageListDate(long date) {
......
......@@ -165,6 +165,8 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public int size;
public int type;
public int date;
public String thumbPath;
public String imagePath;
}
public final static String MIME_TYPE = "video/avc";
......
......@@ -42,6 +42,7 @@ public class MessageObject {
public int type;
public int contentType;
public String dateKey;
public String monthKey;
public boolean deleted = false;
public float audioProgress;
public int audioProgressSec;
......@@ -199,7 +200,7 @@ public class MessageObject {
}
}
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.formatterDay.format(((long)message.date) * 1000));
String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long) message.date) * 1000), LocaleController.formatterDay.format(((long) message.date) * 1000));
TLRPC.User to_user = UserConfig.getCurrentUser();
if (to_user == null) {
if (users != null) {
......@@ -346,11 +347,14 @@ public class MessageObject {
}
Calendar rightNow = new GregorianCalendar();
rightNow.setTimeInMillis((long)(messageOwner.date) * 1000);
rightNow.setTimeInMillis((long) (messageOwner.date) * 1000);
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
int dateYear = rightNow.get(Calendar.YEAR);
int dateMonth = rightNow.get(Calendar.MONTH);
dateKey = String.format("%d_%02d_%02d", dateYear, dateMonth, dateDay);
if (contentType == 1 || contentType == 2) {
monthKey = String.format("%d_%02d", dateYear, dateMonth);
}
if (generateLayout) {
generateLayout();
......@@ -556,7 +560,7 @@ public class MessageObject {
textHeight = textLayout.getHeight();
int linesCount = textLayout.getLineCount();
int blocksCount = (int)Math.ceil((float)linesCount / LINES_PER_BLOCK);
int blocksCount = (int) Math.ceil((float) linesCount / LINES_PER_BLOCK);
int linesOffset = 0;
float prevOffset = 0;
......@@ -581,7 +585,7 @@ public class MessageObject {
block.textLayout = new StaticLayout(str, textPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
block.textYOffset = textLayout.getLineTop(linesOffset);
if (a != 0) {
blockHeight = Math.min(blockHeight, (int)(block.textYOffset - prevOffset));
blockHeight = Math.min(blockHeight, (int) (block.textYOffset - prevOffset));
}
prevOffset = block.textYOffset;
/*if (a != blocksCount - 1) {
......@@ -613,7 +617,7 @@ public class MessageObject {
FileLog.e("tmessages", e);
}
int linesMaxWidth = (int)Math.ceil(lastLine);
int linesMaxWidth = (int) Math.ceil(lastLine);
int lastLineWidthWithLeft;
int linesMaxWidthWithLeft;
boolean hasNonRTL = false;
......@@ -622,7 +626,7 @@ public class MessageObject {
lastLineWidth = linesMaxWidth;
}
linesMaxWidthWithLeft = lastLineWidthWithLeft = (int)Math.ceil(lastLine + lastLeft);
linesMaxWidthWithLeft = lastLineWidthWithLeft = (int) Math.ceil(lastLine + lastLeft);
if (lastLeft == 0) {
hasNonRTL = true;
}
......@@ -655,8 +659,8 @@ public class MessageObject {
}
textRealMaxWidth = Math.max(textRealMaxWidth, lineWidth);
textRealMaxWidthWithLeft = Math.max(textRealMaxWidthWithLeft, lineWidth + lineLeft);
linesMaxWidth = Math.max(linesMaxWidth, (int)Math.ceil(lineWidth));
linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int)Math.ceil(lineWidth + lineLeft));
linesMaxWidth = Math.max(linesMaxWidth, (int) Math.ceil(lineWidth));
linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int) Math.ceil(lineWidth + lineLeft));
}
if (hasNonRTL) {
textRealMaxWidth = textRealMaxWidthWithLeft;
......@@ -667,7 +671,7 @@ public class MessageObject {
} else if (a == blocksCount - 1) {
lastLineWidth = linesMaxWidth;
}
textWidth = Math.max(textWidth, (int)Math.ceil(textRealMaxWidth));
textWidth = Math.max(textWidth, (int) Math.ceil(textRealMaxWidth));
} else {
textWidth = Math.max(textWidth, Math.min(maxWidth, linesMaxWidth));
}
......@@ -696,7 +700,7 @@ public class MessageObject {
}
public void setIsRead() {
messageOwner.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
messageOwner.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
public boolean isSecretPhoto() {
......@@ -706,15 +710,15 @@ public class MessageObject {
public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret &&
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl != 0 && messageOwner.ttl <= 60 ||
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
}
public static void setIsUnread(TLRPC.Message message, boolean unread) {
if (unread) {
message.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
} else {
message.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
message.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
}
......
......@@ -102,6 +102,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256;
public static final int UPDATE_MASK_SELECT_DIALOG = 512;
public static final int UPDATE_MASK_PHONE = 1024;
public static final int UPDATE_MASK_NEW_MESSAGE = 2048;
public static final int UPDATE_MASK_SEND_STATE = 4096;
public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE;
public static class PrintingUser {
......@@ -863,6 +865,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
......@@ -944,10 +947,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
public void deleteDialog(final long did, int offset, final boolean onlyHistory) {
if (offset == 0) {
MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
}
int lower_part = (int)did;
int high_id = (int)(did >> 32);
......@@ -963,7 +962,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialog.unread_count = 0;
}
dialogMessage.remove(dialog.top_message);
dialog.top_message = 0;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
......@@ -978,8 +980,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
});
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
}
if (high_id == 1) {
......@@ -1437,8 +1439,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
currentDialog.unread_count = entry.getValue();
}
}
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
......@@ -1533,8 +1535,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialogsServerOnly.add(d);
}
}
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
......@@ -1554,8 +1556,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (resetEnd) {
dialogsEndReached = false;
}
loadDialogs(offset, serverOffset, count, false);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
loadDialogs(offset, serverOffset, count, false);
}
});
return;
......@@ -1713,6 +1715,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.peer.chat_id = -lower_part;
} else {
TLRPC.User user = getUser(lower_part);
if (user == null) {
return;
}
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
req.peer = new TLRPC.TL_inputPeerForeign();
req.peer.user_id = user.id;
......@@ -1865,8 +1870,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
updateInterfaceWithMessages(newMsg.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
return 0;
} else {
......@@ -1903,8 +1908,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
if (uploadedAvatar != null) {
changeChatAvatar(chat.id, uploadedAvatar);
}
......@@ -1950,8 +1955,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
if (info != null) {
for (TLRPC.TL_chatParticipant p : info.participants) {
......@@ -2032,8 +2037,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messagesObj.add(new MessageObject(res.message, users, true));
TLRPC.Chat chat = res.chats.get(0);
updateInterfaceWithMessages(-chat.id, messagesObj);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
}
boolean changed = false;
if (info != null) {
......@@ -2851,10 +2856,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
public boolean isDialogMuted(long dialog_id) {
TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
/*TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
if (dialog != null) {
return isNotifySettingsMuted(dialog.notify_settings);
} else {
} else {*/
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
if (mute_type == 2) {
......@@ -2865,7 +2870,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return true;
}
}
}
//}
return false;
}
......
......@@ -838,6 +838,59 @@ public class MessagesStorage {
//database.executeFast("DELETE FROM secret_holes WHERE uid = " + high_id).stepThis().dispose();
}
}
if ((int) did == 0) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM messages WHERE uid = " + did));
ArrayList<File> filesToDelete = new ArrayList<>();
try {
while (cursor.next()) {
ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
TLRPC.Message message = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (message == null || message.media == null) {
continue;
}
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
File file = FileLoader.getPathToAttach(message.media.audio);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
File file = FileLoader.getPathToAttach(message.media.video);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.video.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.document.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
}
buffersStorage.reuseFreeBuffer(data);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
cursor.dispose();
FileLoader.getInstance().deleteFiles(filesToDelete);
}
database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose();
database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose();
database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose();
......@@ -3178,6 +3231,7 @@ public class MessagesStorage {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, mids);
}
});
MessagesStorage.getInstance().updateDialogsWithReadedMessagesInternal(mids);
MessagesStorage.getInstance().markMessagesAsDeletedInternal(mids);
MessagesStorage.getInstance().updateDialogsWithDeletedMessagesInternal(mids);
}
......@@ -3189,9 +3243,6 @@ public class MessagesStorage {
}
private void markMessagesAsDeletedInternal(final ArrayList<Integer> messages) {
if (Thread.currentThread().getId() != storageQueue.getId()) {
throw new RuntimeException("wrong db thread");
}
try {
String ids = TextUtils.join(",", messages);
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data FROM messages WHERE mid IN(%s)", ids));
......@@ -3287,7 +3338,7 @@ public class MessagesStorage {
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
......@@ -3302,6 +3353,10 @@ public class MessagesStorage {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
message.send_state = cursor.intValue(7);
int date = cursor.intValue(8);
if (date != 0) {
dialog.last_message_date = date;
}
dialogs.messages.add(message);
if (!usersToLoad.contains(message.from_id)) {
......@@ -3471,7 +3526,7 @@ public class MessagesStorage {
usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>();
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
......@@ -3495,6 +3550,10 @@ public class MessagesStorage {
if (message != null) {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
int date = cursor.intValue(9);
if (date != 0) {
dialog.last_message_date = date;
}
message.send_state = cursor.intValue(7);
dialogs.messages.add(message);
......
......@@ -23,7 +23,7 @@ import java.util.zip.ZipFile;
public class NativeLoader {
private final static int LIB_VERSION = 5;
private final static int LIB_VERSION = 6;
private final static String LIB_NAME = "tmessages." + LIB_VERSION;
private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so";
private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so";
......
......@@ -48,6 +48,9 @@ public class NotificationCenter {
public static final int updateMessageMedia = totalEvents++;
public static final int recentImagesDidLoaded = totalEvents++;
public static final int replaceMessagesObjects = totalEvents++;
public static final int didSetPasscode = totalEvents++;
public static final int screenStateChanged = totalEvents++;
public static final int appSwitchedToForeground = totalEvents++;
public static final int httpFileDidLoaded = totalEvents++;
public static final int httpFileDidFailedLoad = totalEvents++;
......
......@@ -11,6 +11,7 @@ package org.telegram.android;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
......@@ -29,6 +30,7 @@ import android.support.v4.app.RemoteInput;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
......@@ -48,6 +50,7 @@ public class NotificationsController {
public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
private DispatchQueue notificationsQueue = new DispatchQueue("notificationsQueue");
private ArrayList<MessageObject> pushMessages = new ArrayList<>();
private HashMap<Integer, MessageObject> pushMessagesDict = new HashMap<>();
private NotificationManagerCompat notificationManager = null;
......@@ -130,7 +133,9 @@ public class NotificationsController {
}
String msg = null;
if ((int)dialog_id != 0) {
if ((int)dialog_id == 0 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
} else {
if (chat_id == 0 && user_id != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
if (preferences.getBoolean("EnablePreviewAll", true)) {
......@@ -237,8 +242,6 @@ public class NotificationsController {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, ContactsController.formatName(user.first_name, user.last_name), chat.title);
}
}
} else {
msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
}
return msg;
}
......@@ -250,7 +253,7 @@ public class NotificationsController {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int minutes = preferences.getInt("repeat_messages", 60);
if (minutes > 0 && personal_count > 0) {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minutes * 60 * 1000, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + minutes * 60 * 1000, pintent);
} else {
alarm.cancel(pintent);
}
......@@ -266,9 +269,9 @@ public class NotificationsController {
PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (onlineReason) {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 1000, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
} else {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pintent);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 500, pintent);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
......@@ -416,14 +419,18 @@ public class NotificationsController {
intent.putExtra("userId", user_id);
}
}
if (pushDialogs.size() == 1) {
if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
photoPath = chat.photo.photo_small;
}
} else {
if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
photoPath = user.photo.photo_small;
if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
photoPath = null;
} else {
if (pushDialogs.size() == 1) {
if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
photoPath = chat.photo.photo_small;
}
} else {
if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
photoPath = user.photo.photo_small;
}
}
}
}
......@@ -436,7 +443,7 @@ public class NotificationsController {
String name = null;
boolean replace = true;
if ((int)dialog_id == 0 || pushDialogs.size() > 1) {
if ((int)dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
name = LocaleController.getString("AppName", R.string.AppName);
replace = false;
} else {
......@@ -451,7 +458,7 @@ public class NotificationsController {
if (pushDialogs.size() == 1) {
detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
} else {
detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size()));
detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromChats", pushDialogs.size()));
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext)
......@@ -834,7 +841,7 @@ public class NotificationsController {
notifyCheck = isLast;
}
if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) {
if (!popupMessages.isEmpty() && oldCount != popupMessages.size() && !AndroidUtilities.needShowPasscode(false)) {
if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
MessageObject messageObject = messageObjects.get(0);
if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) {
......@@ -988,20 +995,33 @@ public class NotificationsController {
setBadge(ApplicationLoader.applicationContext, enabled ? total_unread_count : 0);
}
private void setBadge(Context context, int count) {
try {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
private void setBadge(final Context context, final int count) {
notificationsQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
ContentValues cv = new ContentValues();
cv.put("tag", "org.telegram.messenger/org.telegram.ui.LaunchActivity");
cv.put("count", count);
context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
} catch (Throwable e) {
//ignore
}
try {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
} catch (Throwable e) {
FileLog.e("tmessages", e);
}
});
}
public static String getLauncherClassName(Context context) {
......
......@@ -28,5 +28,6 @@ public class ScreenReceiver extends BroadcastReceiver {
ConnectionsManager.getInstance().setAppPaused(false, true);
ApplicationLoader.isScreenOn = true;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenStateChanged);
}
}
......@@ -1072,8 +1072,8 @@ public class SecretChatHelper {
}
});
MessagesStorage.getInstance().deleteDialog(did, true);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
}
});
return null;
......@@ -1616,7 +1616,7 @@ public class SecretChatHelper {
}
public void startSecretChat(final Context context, final TLRPC.User user) {
if (user == null) {
if (user == null || context == null) {
return;
}
startingSecretChat = true;
......
......@@ -59,7 +59,7 @@ public class MP4Builder {
private long dataOffset = 0;
private long writedSinceLastMdat = 0;
private boolean writeNewMdat = true;
private HashMap<Track, long[]> track2SampleSizes = new HashMap<Track, long[]>();
private HashMap<Track, long[]> track2SampleSizes = new HashMap<>();
private ByteBuffer sizeBuffer = null;
public MP4Builder createMovie(Mp4Movie mp4Movie) throws Exception {
......@@ -158,7 +158,7 @@ public class MP4Builder {
}
protected FileTypeBox createFileTypeBox() {
LinkedList<String> minorBrands = new LinkedList<String>();
LinkedList<String> minorBrands = new LinkedList<>();
minorBrands.add("isom");
minorBrands.add("3gp4");
return new FileTypeBox("isom", 0, minorBrands);
......@@ -347,7 +347,7 @@ public class MP4Builder {
protected void createStts(Track track, SampleTableBox stbl) {
TimeToSampleBox.Entry lastEntry = null;
List<TimeToSampleBox.Entry> entries = new ArrayList<TimeToSampleBox.Entry>();
List<TimeToSampleBox.Entry> entries = new ArrayList<>();
for (long delta : track.getSampleDurations()) {
if (lastEntry != null && lastEntry.getDelta() == delta) {
......@@ -418,7 +418,7 @@ public class MP4Builder {
}
protected void createStco(Track track, SampleTableBox stbl) {
ArrayList<Long> chunksOffsets = new ArrayList<Long>();
ArrayList<Long> chunksOffsets = new ArrayList<>();
long lastOffset = -1;
for (Sample sample : track.getSamples()) {
long offset = sample.getOffset();
......
......@@ -8,6 +8,7 @@
package org.telegram.messenger;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
......@@ -19,6 +20,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
......@@ -38,10 +40,13 @@ import org.telegram.android.LocaleController;
import org.telegram.android.MessagesController;
import org.telegram.android.NativeLoader;
import org.telegram.android.ScreenReceiver;
import org.telegram.ui.Components.ForegroundDetector;
import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;
public class ApplicationLoader extends Application {
private GoogleCloudMessaging gcm;
private AtomicInteger msgId = new AtomicInteger();
private String regid;
......@@ -49,15 +54,80 @@ public class ApplicationLoader extends Application {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static Drawable cachedWallpaper = null;
private static Drawable cachedWallpaper;
private static int selectedColor;
private static boolean isCustomTheme;
private static final Object sync = new Object();
public static volatile Context applicationContext = null;
public static volatile Handler applicationHandler = null;
public static volatile Context applicationContext;
public static volatile Handler applicationHandler;
private static volatile boolean applicationInited = false;
public static volatile boolean isScreenOn = false;
public static volatile boolean mainInterfacePaused = true;
public static boolean isCustomTheme() {
return isCustomTheme;
}
public static int getSelectedColor() {
return selectedColor;
}
public static void reloadWallpaper() {
cachedWallpaper = null;
loadWallpaper();
}
public static void loadWallpaper() {
if (cachedWallpaper != null) {
return;
}
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
synchronized (sync) {
int selectedColor = 0;
try {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int selectedBackground = preferences.getInt("selectedBackground", 1000001);
selectedColor = preferences.getInt("selectedColor", 0);
int cacheColorHint = 0;
if (selectedColor == 0) {
if (selectedBackground == 1000001) {
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
isCustomTheme = false;
} else {
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
if (toFile.exists()) {
cachedWallpaper = Drawable.createFromPath(toFile.getAbsolutePath());
isCustomTheme = true;
} else {
cachedWallpaper = applicationContext.getResources().getDrawable(R.drawable.background_hd);
isCustomTheme = false;
}
}
}
} catch (Throwable throwable) {
//ignore
}
if (cachedWallpaper == null) {
if (selectedColor == 0) {
selectedColor = -2693905;
}
cachedWallpaper = new ColorDrawable(selectedColor);
}
}
}
});
}
public static Drawable getCachedWallpaper() {
synchronized (sync) {
return cachedWallpaper;
}
}
public static void postInitApplication() {
if (applicationInited) {
return;
......@@ -117,6 +187,10 @@ public class ApplicationLoader extends Application {
applicationContext = getApplicationContext();
NativeLoader.initNativeLibs(ApplicationLoader.applicationContext);
if (Build.VERSION.SDK_INT >= 14) {
new ForegroundDetector(this);
}
applicationHandler = new Handler(applicationContext.getMainLooper());
startPushService();
......
......@@ -452,7 +452,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
datacenter = new Datacenter();
datacenter.datacenterId = 3;
datacenter.addAddressAndPort("174.140.142.6", 443);
datacenter.addAddressAndPort("149.154.175.100", 443);
datacenters.put(datacenter.datacenterId, datacenter);
datacenter = new Datacenter();
......@@ -488,7 +488,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
datacenter = new Datacenter();
datacenter.datacenterId = 3;
datacenter.addAddressAndPort("174.140.142.6", 443);
datacenter.addAddressAndPort("149.154.175.100", 443);
datacenters.put(datacenter.datacenterId, datacenter);
datacenter = new Datacenter();
......@@ -1406,6 +1406,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (rawRequest != null && (rawRequest instanceof TLRPC.TL_messages_sendMessage ||
rawRequest instanceof TLRPC.TL_messages_sendMedia ||
rawRequest instanceof TLRPC.TL_messages_forwardMessages ||
rawRequest instanceof TLRPC.TL_messages_forwardMessage ||
rawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
rawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
rawRequest instanceof TLRPC.TL_messages_sendEncryptedService)) {
......@@ -1426,6 +1427,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (currentRawRequest instanceof TLRPC.TL_messages_sendMessage ||
currentRawRequest instanceof TLRPC.TL_messages_sendMedia ||
currentRawRequest instanceof TLRPC.TL_messages_forwardMessages ||
currentRawRequest instanceof TLRPC.TL_messages_forwardMessage ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
currentRawRequest instanceof TLRPC.TL_messages_sendEncryptedService) {
......@@ -1438,6 +1440,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (request.rawRequest instanceof TLRPC.TL_messages_sendMessage ||
request.rawRequest instanceof TLRPC.TL_messages_sendMedia ||
request.rawRequest instanceof TLRPC.TL_messages_forwardMessages ||
request.rawRequest instanceof TLRPC.TL_messages_forwardMessage ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncrypted ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncryptedFile ||
request.rawRequest instanceof TLRPC.TL_messages_sendEncryptedService) {
......
......@@ -638,7 +638,7 @@ public class FileLoader {
continue;
}
int currentSide = obj.w >= obj.h ? obj.w : obj.h;
if (closestObject == null || obj instanceof TLRPC.TL_photoCachedSize || currentSide <= side && lastSide < currentSide) {
if (closestObject == null || side > 100 && closestObject.location != null && closestObject.location.dc_id == Integer.MIN_VALUE || obj instanceof TLRPC.TL_photoCachedSize || currentSide <= side && lastSide < currentSide) {
closestObject = obj;
lastSide = currentSide;
}
......
......@@ -31,6 +31,12 @@ public class UserConfig {
public static boolean saveIncomingPhotos = false;
public static int contactsVersion = 1;
public static boolean waitingForPasswordEnter = false;
public static String passcodeHash = "";
public static boolean appLocked = false;
public static int passcodeType = 0;
public static int autoLockIn = 60 * 60;
public static int lastPauseTime = 0;
public static boolean isWaitingForPasscodeEnter = false;
public static int getNewMessageId() {
int id;
......@@ -62,6 +68,12 @@ public class UserConfig {
editor.putBoolean("registeredForInternalPush", registeredForInternalPush);
editor.putBoolean("blockedUsersLoaded", blockedUsersLoaded);
editor.putBoolean("waitingForPasswordEnter", waitingForPasswordEnter);
editor.putString("passcodeHash1", passcodeHash);
editor.putBoolean("appLocked", appLocked);
editor.putInt("passcodeType", passcodeType);
editor.putInt("autoLockIn", autoLockIn);
editor.putInt("lastPauseTime", lastPauseTime);
if (currentUser != null) {
if (withFile) {
SerializedData data = new SerializedData();
......@@ -195,6 +207,11 @@ public class UserConfig {
registeredForInternalPush = preferences.getBoolean("registeredForInternalPush", false);
blockedUsersLoaded = preferences.getBoolean("blockedUsersLoaded", false);
waitingForPasswordEnter = preferences.getBoolean("waitingForPasswordEnter", false);
passcodeHash = preferences.getString("passcodeHash1", "");
appLocked = preferences.getBoolean("appLocked", false);
passcodeType = preferences.getInt("passcodeType", 0);
autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
lastPauseTime = preferences.getInt("lastPauseTime", 0);
String user = preferences.getString("user", null);
if (user != null) {
byte[] userBytes = Base64.decode(user, Base64.DEFAULT);
......@@ -214,12 +231,17 @@ public class UserConfig {
waitingForPasswordEnter = false;
contactsHash = "";
importHash = "";
lastLocalId = -210000;
lastSendMessageId = -210000;
contactsVersion = 1;
lastBroadcastId = -1;
saveIncomingPhotos = false;
blockedUsersLoaded = false;
appLocked = false;
passcodeType = 0;
passcodeHash = "";
autoLockIn = 60 * 60;
lastPauseTime = 0;
isWaitingForPasscodeEnter = false;
saveConfig(true);
}
}
......@@ -109,6 +109,7 @@ public class Utilities {
public native static long doPQNative(long _what);
public native static void loadBitmap(String path, Bitmap bitmap, int scale, int width, int height, int stride);
public native static void blurBitmap(Object bitmap, int radius);
public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer);
public native static Bitmap loadWebpImage(ByteBuffer buffer, int len, BitmapFactory.Options options);
public native static Bitmap loadBpgImage(ByteBuffer buffer, int len, BitmapFactory.Options options);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
......
......@@ -94,7 +94,7 @@ public class AccountPasswordActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
if (type == 0) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
......@@ -271,7 +271,7 @@ public class AccountPasswordActivity extends BaseFragment {
listAdapter.notifyDataSetChanged();
}
private void needShowAlert(final String text) {
private void ShowAlert(final String text) {
if (text == null || getParentActivity() == null) {
return;
}
......@@ -355,20 +355,20 @@ public class AccountPasswordActivity extends BaseFragment {
String hint = hintPasswordCell.getFieldText();
if (hasPassword) {
if (oldPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
return;
}
}
if (newPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
return;
}
if (!newPassword.equals(verifyPasswrod)) {
needShowAlert(LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch));
ShowAlert(LocaleController.getString("PasswordDoNotMatch", R.string.PasswordDoNotMatch));
return;
}
if (hint.toLowerCase().contains(newPassword.toLowerCase())) {
needShowAlert(LocaleController.getString("HintIncorrect", R.string.HintIncorrect));
ShowAlert(LocaleController.getString("HintIncorrect", R.string.HintIncorrect));
return;
}
byte[] oldPasswordBytes = null;
......@@ -418,13 +418,13 @@ public class AccountPasswordActivity extends BaseFragment {
finishFragment();
} else {
if (error.text.contains("PASSWORD_HASH_INVALID")) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
} else if (error.text.contains("NEW_PASSWORD_BAD")) {
needShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
ShowAlert(LocaleController.getString("PasswordNewIncorrect", R.string.PasswordNewIncorrect));
} else if (error.text.startsWith("FLOOD_WAIT")) {
needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else {
needShowAlert(error.text);
ShowAlert(error.text);
}
}
}
......@@ -434,7 +434,7 @@ public class AccountPasswordActivity extends BaseFragment {
} else if (type == 1) {
String oldPassword = oldPasswordCell.getFieldText();
if (oldPassword.length() == 0) {
needShowAlert(LocaleController.getString("PasswordIncorrect", R.string.PasswordIncorrect));
ShowAlert(LocaleController.getString("PasswordIncorrect", R.string.PasswordIncorrect));
return;
}
byte[] oldPasswordBytes = null;
......@@ -486,11 +486,11 @@ public class AccountPasswordActivity extends BaseFragment {
}
} else {
if (error.text.contains("PASSWORD_HASH_INVALID")) {
needShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
ShowAlert(LocaleController.getString("PasswordOldIncorrect", R.string.PasswordOldIncorrect));
} else if (error.text.startsWith("FLOOD_WAIT")) {
needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
ShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else {
needShowAlert(error.text);
ShowAlert(error.text);
}
}
}
......
......@@ -13,6 +13,7 @@ import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
......@@ -91,9 +92,9 @@ public class ActionBar extends FrameLayout {
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
titleTextView.setTextSize(18);
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
} else {
titleTextView.setTextSize(20);
titleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
}
layoutParams = (LayoutParams) titleTextView.getLayoutParams();
......@@ -106,9 +107,9 @@ public class ActionBar extends FrameLayout {
}
if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {
if (!AndroidUtilities.isTablet() && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
subTitleTextView.setTextSize(14);
subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
} else {
subTitleTextView.setTextSize(16);
subTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
}
layoutParams = (LayoutParams) subTitleTextView.getLayoutParams();
......@@ -136,7 +137,7 @@ public class ActionBar extends FrameLayout {
}
if (menu != null) {
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16));
maxTextWidth = Math.min(maxTextWidth, width - menu.getMeasuredWidth() - AndroidUtilities.dp(16) - x);
}
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
......@@ -173,7 +174,7 @@ public class ActionBar extends FrameLayout {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)menu.getLayoutParams();
layoutParams.width = isSearchFieldVisible ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT;
layoutParams.height = height;
layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(54) : 0;
layoutParams.leftMargin = isSearchFieldVisible ? AndroidUtilities.dp(AndroidUtilities.isTablet() ? 74 : 66) : 0;
layoutParams.topMargin = occupyStatusBar ? AndroidUtilities.statusBarHeight : 0;
menu.setLayoutParams(layoutParams);
menu.measure(width, height);
......@@ -366,7 +367,7 @@ public class ActionBar extends FrameLayout {
return;
}
actionMode.setVisibility(VISIBLE);
if (actionModeTop != null) {
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(VISIBLE);
}
if (titleFrameLayout != null) {
......@@ -382,7 +383,7 @@ public class ActionBar extends FrameLayout {
return;
}
actionMode.setVisibility(GONE);
if (actionModeTop != null) {
if (occupyStatusBar && actionModeTop != null) {
actionModeTop.setVisibility(GONE);
}
if (titleFrameLayout != null) {
......@@ -473,6 +474,9 @@ public class ActionBar extends FrameLayout {
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
if (actionMode != null) {
actionMode.setPadding(0, occupyStatusBar ? AndroidUtilities.statusBarHeight : 0, 0, 0);
}
}
public boolean getOccupyStatusBar() {
......
......@@ -225,7 +225,7 @@ public class ActionBarLayout extends FrameLayout {
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
return delegate != null && delegate.onPreIme() || super.dispatchKeyEventPreIme(event);
}
return super.dispatchKeyEventPreIme(event);
......@@ -321,7 +321,7 @@ public class ActionBarLayout extends FrameLayout {
beginTrackingSent = false;
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 2);
View fragmentView = lastFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = lastFragment.createView(parentActivity.getLayoutInflater());
ViewGroup parent = (ViewGroup) fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
......@@ -502,8 +502,7 @@ public class ActionBarLayout extends FrameLayout {
}
public boolean checkTransitionAnimation() {
if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 400) {
transitionAnimationInProgress = false;
if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 1000) {
onAnimationEndCheck(true);
}
return transitionAnimationInProgress;
......@@ -556,7 +555,7 @@ public class ActionBarLayout extends FrameLayout {
final BaseFragment currentFragment = !fragmentsStack.isEmpty() ? fragmentsStack.get(fragmentsStack.size() - 1) : null;
fragment.setParentLayout(this);
View fragmentView = fragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = fragment.createView(parentActivity.getLayoutInflater());
if (fragment.needAddActionBar() && fragment.actionBar != null) {
if (removeActionBarExtraHeight) {
fragment.actionBar.setOccupyStatusBar(false);
......@@ -585,6 +584,7 @@ public class ActionBarLayout extends FrameLayout {
containerView = containerViewBack;
containerViewBack = temp;
containerView.setVisibility(View.VISIBLE);
setInnerTranslationX(0);
bringChildToFront(containerView);
......@@ -633,6 +633,8 @@ public class ActionBarLayout extends FrameLayout {
ViewProxy.setTranslationX(containerView, 0);
}
};
ViewProxy.setAlpha(containerView, 0.0f);
ViewProxy.setTranslationX(containerView, 48.0f);
currentAnimation = new AnimatorSetProxy();
currentAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(containerView, "alpha", 0.0f, 1.0f),
......@@ -640,6 +642,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
......@@ -672,6 +679,22 @@ public class ActionBarLayout extends FrameLayout {
}
fragment.setParentLayout(this);
if (position == -1) {
if (!fragmentsStack.isEmpty()) {
BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 1);
previousFragment.onPause();
if (previousFragment.actionBar != null) {
ViewGroup parent = (ViewGroup) previousFragment.actionBar.getParent();
if (parent != null) {
parent.removeView(previousFragment.actionBar);
}
}
if (previousFragment.fragmentView != null) {
ViewGroup parent = (ViewGroup) previousFragment.fragmentView.getParent();
if (parent != null) {
parent.removeView(previousFragment.fragmentView);
}
}
}
fragmentsStack.add(fragment);
} else {
fragmentsStack.add(position, fragment);
......@@ -689,12 +712,13 @@ public class ActionBarLayout extends FrameLayout {
}
public void closeLastFragment(boolean animated) {
if (delegate != null && !delegate.needCloseLastFragment(this) || checkTransitionAnimation()) {
if (delegate != null && !delegate.needCloseLastFragment(this) || checkTransitionAnimation() || fragmentsStack.isEmpty()) {
return;
}
if (parentActivity.getCurrentFocus() != null) {
AndroidUtilities.hideKeyboard(parentActivity.getCurrentFocus());
}
setInnerTranslationX(0);
boolean needAnimation = Build.VERSION.SDK_INT > 10 && animated && parentActivity.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
final BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
BaseFragment previousFragment = null;
......@@ -709,7 +733,7 @@ public class ActionBarLayout extends FrameLayout {
containerView.setVisibility(View.VISIBLE);
previousFragment.setParentLayout(this);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater());
if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) {
if (removeActionBarExtraHeight) {
previousFragment.actionBar.setOccupyStatusBar(false);
......@@ -754,6 +778,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new DecelerateInterpolator(1.5f));
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
......@@ -796,6 +825,11 @@ public class ActionBarLayout extends FrameLayout {
currentAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
currentAnimation.setDuration(200);
currentAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationStart(Object animation) {
transitionAnimationStartTime = System.currentTimeMillis();
}
@Override
public void onAnimationEnd(Object animation) {
onAnimationEndCheck(false);
......@@ -823,7 +857,7 @@ public class ActionBarLayout extends FrameLayout {
}
BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 1);
previousFragment.setParentLayout(this);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater(), null);
View fragmentView = previousFragment.createView(parentActivity.getLayoutInflater());
if (previousFragment.needAddActionBar() && previousFragment.actionBar != null) {
if (removeActionBarExtraHeight) {
previousFragment.actionBar.setOccupyStatusBar(false);
......
......@@ -348,6 +348,10 @@ public class ActionBarMenuItem extends FrameLayoutFixed {
}
}
public void setIcon(int resId) {
iconView.setImageResource(resId);
}
public EditText getSearchField() {
return searchField;
}
......@@ -399,7 +403,7 @@ public class ActionBarMenuItem extends FrameLayoutFixed {
searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_SEARCH || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
AndroidUtilities.hideKeyboard(searchField);
if (listener != null) {
listener.onSearchPressed(searchField);
......
......@@ -41,7 +41,7 @@ public class BaseFragment {
classGuid = ConnectionsManager.getInstance().generateClassGuid();
}
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
return null;
}
......@@ -76,7 +76,7 @@ public class BaseFragment {
if (parentLayout != null) {
actionBar = new ActionBar(parentLayout.getContext());
actionBar.parentFragment = this;
actionBar.setBackgroundResource(R.color.header);
actionBar.setBackgroundColor(0xff54759e);
actionBar.setItemsBackground(R.drawable.bar_selector);
}
}
......
......@@ -165,6 +165,9 @@ public class DrawerLayoutContainer extends FrameLayout {
}
public void openDrawer(boolean fast) {
if (!allowOpenDrawer) {
return;
}
if (AndroidUtilities.isTablet() && parentActionBarLayout != null && parentActionBarLayout.parentActivity != null) {
AndroidUtilities.hideKeyboard(parentActionBarLayout.parentActivity.getCurrentFocus());
}
......
......@@ -124,10 +124,14 @@ public class ContactsSearchAdapter extends BaseContactsSearchAdapter {
}
String name = ContactsController.formatName(user.first_name, user.last_name).toLowerCase();
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (user.username != null && user.username.startsWith(q)) {
found = 2;
......
......@@ -13,7 +13,6 @@ import android.view.View;
import android.view.ViewGroup;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.MessageObject;
import org.telegram.android.MessagesController;
import org.telegram.messenger.TLRPC;
import org.telegram.ui.Cells.DialogCell;
......@@ -24,6 +23,7 @@ public class DialogsAdapter extends BaseFragmentAdapter {
private Context mContext;
private boolean serverOnly;
private long openedDialogId;
private int currentCount;
public DialogsAdapter(Context context, boolean onlyFromServer) {
mContext = context;
......@@ -34,6 +34,11 @@ public class DialogsAdapter extends BaseFragmentAdapter {
openedDialogId = id;
}
public boolean isDataSetChanged() {
int current = currentCount;
return current != getCount();
}
@Override
public boolean areAllItemsEnabled() {
return true;
......@@ -58,6 +63,7 @@ public class DialogsAdapter extends BaseFragmentAdapter {
if (!MessagesController.getInstance().dialogsEndReached) {
count++;
}
currentCount = count;
return count;
}
......@@ -97,22 +103,23 @@ public class DialogsAdapter extends BaseFragmentAdapter {
if (view == null) {
view = new DialogCell(mContext);
}
((DialogCell) view).useSeparator = (i != getCount() - 1);
TLRPC.TL_dialog dialog = null;
if (serverOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(i);
} else {
dialog = MessagesController.getInstance().dialogs.get(i);
if (AndroidUtilities.isTablet()) {
if (dialog.id == openedDialogId) {
view.setBackgroundColor(0x0f000000);
} else {
view.setBackgroundColor(0);
if (view instanceof DialogCell) { //TODO finally i need to find this crash
((DialogCell) view).useSeparator = (i != getCount() - 1);
TLRPC.TL_dialog dialog = null;
if (serverOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(i);
} else {
dialog = MessagesController.getInstance().dialogs.get(i);
if (AndroidUtilities.isTablet()) {
if (dialog.id == openedDialogId) {
view.setBackgroundColor(0x0f000000);
} else {
view.setBackgroundColor(0);
}
}
}
((DialogCell) view).setDialog(dialog, i, serverOnly);
}
MessageObject message = MessagesController.getInstance().dialogMessage.get(dialog.top_message);
((DialogCell) view).setDialog(dialog.id, message, true, dialog.last_message_date, dialog.unread_count, MessagesController.getInstance().isDialogMuted(dialog.id));
}
return view;
......@@ -133,9 +140,6 @@ public class DialogsAdapter extends BaseFragmentAdapter {
@Override
public boolean isEmpty() {
if (MessagesController.getInstance().loadingDialogs && MessagesController.getInstance().dialogs.isEmpty()) {
return true;
}
int count;
if (serverOnly) {
count = MessagesController.getInstance().dialogsServerOnly.size();
......
......@@ -215,6 +215,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, status, name FROM users WHERE uid IN(%s)", TextUtils.join(",", usersToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
......@@ -222,7 +226,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
......@@ -257,8 +261,12 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, name FROM chats WHERE uid IN(%s)", TextUtils.join(",", chatsToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(1);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
ByteBufferDesc data = MessagesStorage.getInstance().getBuffersStorage().getFreeBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
......@@ -285,6 +293,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT q.data, u.name, q.user, q.g, q.authkey, q.ttl, u.data, u.status, q.layer, q.seq_in, q.seq_out, q.use_count, q.exchange_id, q.key_date, q.fprint, q.fauthkey, q.khash FROM enc_chats as q INNER JOIN users as u ON q.user = u.uid WHERE q.uid IN(%s)", TextUtils.join(",", encryptedToLoad)));
while (cursor.next()) {
String name = cursor.stringValue(1);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
......@@ -293,7 +305,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
......@@ -378,6 +390,10 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
continue;
}
String name = cursor.stringValue(2);
String tName = LocaleController.getInstance().getTranslitString(name);
if (name.equals(tName)) {
tName = null;
}
String username = null;
int usernamePos = name.lastIndexOf(";;;");
if (usernamePos != -1) {
......@@ -385,7 +401,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
int found = 0;
for (String q : search) {
if (name.startsWith(q) || name.contains(" " + q)) {
if (name.startsWith(q) || name.contains(" " + q) || tName != null && (tName.startsWith(q) || tName.contains(" " + q))) {
found = 1;
} else if (username != null && username.startsWith(q)) {
found = 2;
......@@ -618,7 +634,7 @@ public class DialogsSearchAdapter extends BaseContactsSearchAdapter {
}
((DialogCell) view).useSeparator = (i != getCount() - 1);
MessageObject messageObject = (MessageObject)getItem(i);
((DialogCell) view).setDialog(messageObject.getDialogId(), messageObject, false, messageObject.messageOwner.date, 0, false);
((DialogCell) view).setDialog(messageObject.getDialogId(), messageObject, messageObject.messageOwner.date);
} else if (type == 3) {
if (view == null) {
view = new LoadingCell(mContext);
......
......@@ -203,6 +203,9 @@ public class StickersAdapter extends RecyclerView.Adapter implements Notificatio
}
HashMap<Long, TLRPC.Document> documents = new HashMap<>();
for (TLRPC.Document document : res.documents) {
if (document == null) {
continue;
}
documents.put(document.id, document);
if (document.thumb != null && document.thumb.location != null) {
document.thumb.location.ext = "webp";
......
......@@ -25,10 +25,10 @@ import java.util.List;
public final class AnimatorSet10 extends Animator10 {
private ArrayList<Animator10> mPlayingSet = new ArrayList<Animator10>();
private HashMap<Animator10, Node> mNodeMap = new HashMap<Animator10, Node>();
private ArrayList<Node> mNodes = new ArrayList<Node>();
private ArrayList<Node> mSortedNodes = new ArrayList<Node>();
private ArrayList<Animator10> mPlayingSet = new ArrayList<>();
private HashMap<Animator10, Node> mNodeMap = new HashMap<>();
private ArrayList<Node> mNodes = new ArrayList<>();
private ArrayList<Node> mSortedNodes = new ArrayList<>();
private boolean mNeedsSort = true;
private AnimatorSetListener mSetListener = null;
boolean mTerminated = false;
......@@ -89,7 +89,7 @@ public final class AnimatorSet10 extends Animator10 {
}
public ArrayList<Animator10> getChildAnimations() {
ArrayList<Animator10> childList = new ArrayList<Animator10>();
ArrayList<Animator10> childList = new ArrayList<>();
for (Node node : mNodes) {
childList.add(node.animation);
}
......@@ -295,7 +295,7 @@ public final class AnimatorSet10 extends Animator10 {
ArrayList<AnimatorListener> oldListeners = node.animation.getListeners();
if (oldListeners != null && oldListeners.size() > 0) {
final ArrayList<AnimatorListener> clonedListeners = new
ArrayList<AnimatorListener>(oldListeners);
ArrayList<>(oldListeners);
for (AnimatorListener listener : clonedListeners) {
if (listener instanceof DependencyListener ||
......@@ -306,7 +306,7 @@ public final class AnimatorSet10 extends Animator10 {
}
}
final ArrayList<Node> nodesToStart = new ArrayList<Node>();
final ArrayList<Node> nodesToStart = new ArrayList<>();
for (Node node : mSortedNodes) {
if (mSetListener == null) {
mSetListener = new AnimatorSetListener(this);
......@@ -379,12 +379,12 @@ public final class AnimatorSet10 extends Animator10 {
anim.mNeedsSort = true;
anim.mTerminated = false;
anim.mStarted = false;
anim.mPlayingSet = new ArrayList<Animator10>();
anim.mNodeMap = new HashMap<Animator10, Node>();
anim.mNodes = new ArrayList<Node>();
anim.mSortedNodes = new ArrayList<Node>();
anim.mPlayingSet = new ArrayList<>();
anim.mNodeMap = new HashMap<>();
anim.mNodes = new ArrayList<>();
anim.mSortedNodes = new ArrayList<>();
HashMap<Node, Node> nodeCloneMap = new HashMap<Node, Node>();
HashMap<Node, Node> nodeCloneMap = new HashMap<>();
for (Node node : mNodes) {
Node nodeClone = node.clone();
nodeCloneMap.put(node, nodeClone);
......@@ -400,7 +400,7 @@ public final class AnimatorSet10 extends Animator10 {
for (AnimatorListener listener : cloneListeners) {
if (listener instanceof AnimatorSetListener) {
if (listenersToRemove == null) {
listenersToRemove = new ArrayList<AnimatorListener>();
listenersToRemove = new ArrayList<>();
}
listenersToRemove.add(listener);
}
......@@ -543,14 +543,14 @@ public final class AnimatorSet10 extends Animator10 {
private void sortNodes() {
if (mNeedsSort) {
mSortedNodes.clear();
ArrayList<Node> roots = new ArrayList<Node>();
ArrayList<Node> roots = new ArrayList<>();
int numNodes = mNodes.size();
for (Node node : mNodes) {
if (node.dependencies == null || node.dependencies.size() == 0) {
roots.add(node);
}
}
ArrayList<Node> tmpRoots = new ArrayList<Node>();
ArrayList<Node> tmpRoots = new ArrayList<>();
while (roots.size() > 0) {
int numRoots = roots.size();
for (Node root : roots) {
......@@ -582,7 +582,7 @@ public final class AnimatorSet10 extends Animator10 {
for (int j = 0; j < numDependencies; ++j) {
Dependency dependency = node.dependencies.get(j);
if (node.nodeDependencies == null) {
node.nodeDependencies = new ArrayList<Node>();
node.nodeDependencies = new ArrayList<>();
}
if (!node.nodeDependencies.contains(dependency.node)) {
node.nodeDependencies.add(dependency.node);
......@@ -620,8 +620,8 @@ public final class AnimatorSet10 extends Animator10 {
public void addDependency(Dependency dependency) {
if (dependencies == null) {
dependencies = new ArrayList<Dependency>();
nodeDependencies = new ArrayList<Node>();
dependencies = new ArrayList<>();
nodeDependencies = new ArrayList<>();
}
dependencies.add(dependency);
if (!nodeDependencies.contains(dependency.node)) {
......@@ -629,7 +629,7 @@ public final class AnimatorSet10 extends Animator10 {
}
Node dependencyNode = dependency.node;
if (dependencyNode.nodeDependents == null) {
dependencyNode.nodeDependents = new ArrayList<Node>();
dependencyNode.nodeDependents = new ArrayList<>();
}
dependencyNode.nodeDependents.add(this);
}
......
......@@ -31,7 +31,7 @@ public class View10 extends Animation {
public static boolean NEED_PROXY = Build.VERSION.SDK_INT < 11;
private static final WeakHashMap<View, View10> PROXIES = new WeakHashMap<View, View10>();
private static final WeakHashMap<View, View10> PROXIES = new WeakHashMap<>();
public static View10 wrap(View view) {
View10 proxy = PROXIES.get(view);
......@@ -68,7 +68,7 @@ public class View10 extends Animation {
setDuration(0);
setFillAfter(true);
view.setAnimation(this);
mView = new WeakReference<View>(view);
mView = new WeakReference<>(view);
}
public float getAlpha() {
......
......@@ -64,7 +64,7 @@ public class BlockedUsersActivity extends BaseFragment implements NotificationCe
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......
......@@ -574,9 +574,9 @@ public class ChatBaseCell extends BaseCell {
if (drawCheck2) {
if (!media) {
if (drawCheck1) {
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(22.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - checkDrawable.getIntrinsicHeight());
} else {
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - checkDrawable.getIntrinsicHeight());
setDrawableBounds(checkDrawable, layoutWidth - AndroidUtilities.dp(18.5f) - checkDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - checkDrawable.getIntrinsicHeight());
}
checkDrawable.draw(canvas);
} else {
......@@ -590,7 +590,7 @@ public class ChatBaseCell extends BaseCell {
}
if (drawCheck1) {
if (!media) {
setDrawableBounds(halfCheckDrawable, layoutWidth - AndroidUtilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.5f) - halfCheckDrawable.getIntrinsicHeight());
setDrawableBounds(halfCheckDrawable, layoutWidth - AndroidUtilities.dp(18) - halfCheckDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(8.0f) - halfCheckDrawable.getIntrinsicHeight());
halfCheckDrawable.draw(canvas);
} else {
setDrawableBounds(halfCheckMediaDrawable, layoutWidth - AndroidUtilities.dp(20.5f) - halfCheckMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dp(13.0f) - halfCheckMediaDrawable.getIntrinsicHeight());
......
......@@ -530,19 +530,14 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
break;
}
}
float maxWidth;
if (AndroidUtilities.isTablet()) {
maxWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.5f);
} else {
maxWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.5f);
}
float maxHeight = AndroidUtilities.displaySize.y * 0.4f;
if (photoWidth == 0) {
photoWidth = (int)maxWidth;
photoHeight = photoWidth + AndroidUtilities.dp(100);
photoHeight = (int) maxHeight;
photoWidth = photoHeight + AndroidUtilities.dp(100);
}
if (photoWidth > maxWidth) {
photoHeight *= maxWidth / photoWidth;
photoWidth = (int)maxWidth;
if (photoHeight > maxHeight) {
photoWidth *= maxHeight / photoHeight;
photoHeight = (int)maxHeight;
}
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80);
......@@ -870,8 +865,8 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
if (currentMessageObject.type == 9) {
Drawable menuDrawable = null;
if (currentMessageObject.isOut()) {
infoPaint.setColor(0xff75b166);
docBackPaint.setColor(0xffd0f3b3);
infoPaint.setColor(0xff70b15c);
docBackPaint.setColor(0xffdaf5c3);
menuDrawable = docMenuOutDrawable;
} else {
infoPaint.setColor(0xffa1adbb);
......
......@@ -55,12 +55,15 @@ public class DialogCell extends BaseCell {
private static Paint linePaint;
private long currentDialogId;
private boolean allowPrintStrings;
private boolean isDialogCell;
private int lastMessageDate;
private int unreadCount;
private boolean lastUnreadState;
private int lastSendState;
private boolean dialogMuted;
private MessageObject message;
private int index;
private boolean isServerOnly;
private ImageReceiver avatarImage;
private AvatarDrawable avatarDrawable;
......@@ -166,14 +169,24 @@ public class DialogCell extends BaseCell {
avatarDrawable = new AvatarDrawable();
}
public void setDialog(long dialog_id, MessageObject messageObject, boolean usePrintStrings, int date, int unread, boolean muted) {
public void setDialog(TLRPC.TL_dialog dialog, int i, boolean server) {
currentDialogId = dialog.id;
isDialogCell = true;
index = i;
isServerOnly = server;
update(0);
}
public void setDialog(long dialog_id, MessageObject messageObject, int date) {
currentDialogId = dialog_id;
message = messageObject;
allowPrintStrings = usePrintStrings;
isDialogCell = false;
lastMessageDate = date;
unreadCount = unread;
dialogMuted = muted;
unreadCount = 0;
lastUnreadState = messageObject != null && messageObject.isUnread();
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
update(0);
}
......@@ -211,7 +224,7 @@ public class DialogCell extends BaseCell {
String countString = null;
CharSequence messageString = "";
CharSequence printingString = null;
if (allowPrintStrings) {
if (isDialogCell) {
printingString = MessagesController.getInstance().printingStrings.get(currentDialogId);
}
TextPaint currentNamePaint = namePaint;
......@@ -543,15 +556,15 @@ public class DialogCell extends BaseCell {
if (LocaleController.isRTL) {
if (nameLayout != null && nameLayout.getLineCount() > 0) {
left = nameLayout.getLineLeft(0);
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (dialogMuted) {
nameMuteLeft = (int) (nameLeft + (nameWidth - widthpx) - AndroidUtilities.dp(6) - muteDrawable.getIntrinsicWidth());
}
if (left == 0) {
widthpx = Math.ceil(nameLayout.getLineWidth(0));
if (widthpx < nameWidth) {
nameLeft += (nameWidth - widthpx);
}
}
if (dialogMuted) {
nameMuteLeft = (nameLeft - AndroidUtilities.dp(6) - muteDrawable.getIntrinsicWidth());
}
}
if (messageLayout != null && messageLayout.getLineCount() > 0) {
left = messageLayout.getLineLeft(0);
......@@ -587,10 +600,37 @@ public class DialogCell extends BaseCell {
}
}
public void checkCurrentDialogIndex() {
TLRPC.TL_dialog dialog = null;
if (isServerOnly) {
dialog = MessagesController.getInstance().dialogsServerOnly.get(index);
} else {
dialog = MessagesController.getInstance().dialogs.get(index);
}
boolean update = true;
if (currentDialogId != dialog.id || message != null && message.messageOwner.id != dialog.top_message || unreadCount != dialog.unread_count) {
currentDialogId = dialog.id;
update(0);
}
}
public void update(int mask) {
if (isDialogCell) {
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(currentDialogId);
if (dialog != null && mask == 0) {
message = MessagesController.getInstance().dialogMessage.get(dialog.top_message);
lastUnreadState = message != null && message.isUnread();
unreadCount = dialog.unread_count;
lastMessageDate = dialog.last_message_date;
if (message != null) {
lastSendState = message.messageOwner.send_state;
}
}
}
if (mask != 0) {
boolean continueUpdate = false;
if (allowPrintStrings && (mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
if (isDialogCell && (mask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
CharSequence printString = MessagesController.getInstance().printingStrings.get(currentDialogId);
if (lastPrintString != null && printString == null || lastPrintString == null && printString != null || lastPrintString != null && printString != null && !lastPrintString.equals(printString)) {
continueUpdate = true;
......@@ -618,8 +658,9 @@ public class DialogCell extends BaseCell {
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) != 0) {
if (message != null && lastUnreadState != message.isUnread()) {
lastUnreadState = message.isUnread();
continueUpdate = true;
} else if (allowPrintStrings) {
} else if (isDialogCell) {
TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(currentDialogId);
if (dialog != null && unreadCount != dialog.unread_count) {
unreadCount = dialog.unread_count;
......@@ -627,11 +668,19 @@ public class DialogCell extends BaseCell {
}
}
}
if (!continueUpdate && (mask & MessagesController.UPDATE_MASK_SEND_STATE) != 0) {
if (message != null && lastSendState != message.messageOwner.send_state) {
lastSendState = message.messageOwner.send_state;
continueUpdate = true;
}
}
if (!continueUpdate) {
return;
}
}
dialogMuted = isDialogCell && MessagesController.getInstance().isDialogMuted(currentDialogId);
user = null;
chat = null;
encryptedChat = null;
......
......@@ -9,7 +9,6 @@
package org.telegram.ui.Cells;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
......@@ -21,7 +20,9 @@ import org.telegram.android.LocaleController;
public class GreySectionCell extends FrameLayout {
private TextView textView;
private void init() {
public GreySectionCell(Context context) {
super(context);
setBackgroundColor(0xfff2f2f2);
textView = new TextView(getContext());
......@@ -39,26 +40,6 @@ public class GreySectionCell extends FrameLayout {
textView.setLayoutParams(layoutParams);
}
public GreySectionCell(Context context) {
super(context);
init();
}
public GreySectionCell(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GreySectionCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public GreySectionCell(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(36), MeasureSpec.EXACTLY));
......
......@@ -9,6 +9,7 @@
package org.telegram.ui.Cells;
import android.content.Context;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.ImageView;
......@@ -32,28 +33,54 @@ public class PhotoEditToolCell extends FrameLayoutFixed {
LayoutParams layoutParams = (LayoutParams) iconImage.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = LayoutParams.MATCH_PARENT;
layoutParams.bottomMargin = AndroidUtilities.dp(20);
layoutParams.bottomMargin = AndroidUtilities.dp(12);
iconImage.setLayoutParams(layoutParams);
nameTextView = new TextView(context);
nameTextView.setGravity(Gravity.CENTER);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(nameTextView);
layoutParams = (LayoutParams) nameTextView.getLayoutParams();
layoutParams.width = LayoutParams.MATCH_PARENT;
layoutParams.height = AndroidUtilities.dp(20);
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
layoutParams.leftMargin = AndroidUtilities.dp(4);
layoutParams.rightMargin = AndroidUtilities.dp(4);
nameTextView.setLayoutParams(layoutParams);
valueTextView = new TextView(context);
valueTextView.setTextColor(0xff6cc3ff);
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
valueTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
addView(valueTextView);
layoutParams = (LayoutParams) valueTextView.getLayoutParams();
layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.leftMargin = AndroidUtilities.dp(57);
layoutParams.topMargin = AndroidUtilities.dp(3);
valueTextView.setLayoutParams(layoutParams);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(80), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(60), MeasureSpec.EXACTLY));
super.onMeasure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(86), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(60), MeasureSpec.EXACTLY));
}
public void setIconAndText(int resId, String text) {
public void setIconAndTextAndValue(int resId, String text, float value) {
iconImage.setImageResource(resId);
nameTextView.setText(text);
nameTextView.setText(text.toUpperCase());
if (value == 0) {
valueTextView.setText("");
} else if (value > 0) {
valueTextView.setText("+" + (int) value);
} else {
valueTextView.setText("" + (int) value);
}
}
}
......@@ -15,7 +15,7 @@ import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
......@@ -23,8 +23,9 @@ import org.telegram.android.AndroidUtilities;
import org.telegram.android.MediaController;
import org.telegram.messenger.R;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.FrameLayoutFixed;
public class PhotoPickerAlbumsCell extends FrameLayout {
public class PhotoPickerAlbumsCell extends FrameLayoutFixed {
public static interface PhotoPickerAlbumsCellDelegate {
public abstract void didSelectAlbum(MediaController.AlbumEntry albumEntry);
......@@ -35,7 +36,7 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
private int albumsCount;
private PhotoPickerAlbumsCellDelegate delegate;
private class AlbumView extends FrameLayout {
private class AlbumView extends FrameLayoutFixed {
private BackupImageView imageView;
private TextView nameTextView;
......@@ -146,7 +147,9 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
if (albumEntry != null) {
AlbumView albumView = albumViews[a];
albumView.imageView.setOrientation(0, true);
if (albumEntry.coverPhoto != null && albumEntry.coverPhoto.path != null) {
albumView.imageView.setOrientation(albumEntry.coverPhoto.orientation, true);
albumView.imageView.setImage("thumb://" + albumEntry.coverPhoto.imageId + ":" + albumEntry.coverPhoto.path, null, getContext().getResources().getDrawable(R.drawable.nophotos));
} else {
albumView.imageView.setImageResource(R.drawable.nophotos);
......@@ -167,16 +170,21 @@ public class PhotoPickerAlbumsCell extends FrameLayout {
itemWidth = (AndroidUtilities.displaySize.x - ((albumsCount + 1) * AndroidUtilities.dp(4))) / albumsCount;
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(4) + itemWidth, MeasureSpec.EXACTLY));
for (int a = 0; a < albumsCount; a++) {
LayoutParams layoutParams = (LayoutParams) albumViews[a].getLayoutParams();
layoutParams.topMargin = AndroidUtilities.dp(4);
layoutParams.leftMargin = (itemWidth + AndroidUtilities.dp(4)) * a;
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
albumViews[a].setLayoutParams(layoutParams);
albumViews[a].measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY));
}
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
layoutParams.height = AndroidUtilities.dp(4) + itemWidth;
setLayoutParams(layoutParams);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
......@@ -11,7 +11,6 @@ package org.telegram.ui.Cells;
import android.content.Context;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.telegram.android.AndroidUtilities;
import org.telegram.messenger.R;
......@@ -23,7 +22,6 @@ public class PhotoPickerPhotoCell extends FrameLayout {
public BackupImageView photoImage;
public FrameLayout checkFrame;
public CheckBox checkBox;
public ImageView editedImage;
public int itemWidth;
public PhotoPickerPhotoCell(Context context) {
......@@ -57,16 +55,6 @@ public class PhotoPickerPhotoCell extends FrameLayout {
layoutParams.topMargin = AndroidUtilities.dp(6);
layoutParams.rightMargin = AndroidUtilities.dp(6);
checkBox.setLayoutParams(layoutParams);
editedImage = new ImageView(context);
editedImage.setImageResource(R.drawable.photo_edit);
editedImage.setScaleType(ImageView.ScaleType.CENTER);
addView(editedImage);
layoutParams = (LayoutParams) editedImage.getLayoutParams();
layoutParams.width = AndroidUtilities.dp(42);
layoutParams.height = AndroidUtilities.dp(42);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
editedImage.setLayoutParams(layoutParams);
}
@Override
......
......@@ -10,6 +10,7 @@ package org.telegram.ui.Cells;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
......@@ -39,62 +40,57 @@ public class PhotoPickerSearchCell extends LinearLayout {
public SearchButton(Context context) {
super(context);
setBackgroundColor(0xff292929);
setBackgroundColor(0xff1a1a1a);
selector = new View(context);
selector.setBackgroundResource(R.drawable.list_selector);
addView(selector);
FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) selector.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.MATCH_PARENT;
selector.setLayoutParams(layoutParams1);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(HORIZONTAL);
addView(linearLayout);
layoutParams1 = (FrameLayout.LayoutParams) linearLayout.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.gravity = Gravity.CENTER;
linearLayout.setLayoutParams(layoutParams1);
imageView = new ImageView(context);
linearLayout.addView(imageView);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
imageView.setScaleType(ImageView.ScaleType.CENTER);
addView(imageView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.height = AndroidUtilities.dp(48);
layoutParams.width = AndroidUtilities.dp(48);
layoutParams1.gravity = Gravity.LEFT | Gravity.TOP;
imageView.setLayoutParams(layoutParams);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setPadding(AndroidUtilities.dp(4), 0, 0, 0);
linearLayout.addView(frameLayout);
layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
frameLayout.setLayoutParams(layoutParams);
textView1 = new TextView(context);
textView1.setGravity(Gravity.CENTER_VERTICAL);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
textView1.setPadding(0, 0, AndroidUtilities.dp(8), 0);
textView1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView1.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView1.setTextColor(0xffffffff);
frameLayout.addView(textView1);
textView1.setSingleLine(true);
textView1.setEllipsize(TextUtils.TruncateAt.END);
addView(textView1);
layoutParams1 = (FrameLayout.LayoutParams) textView1.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams1.rightMargin = AndroidUtilities.dp(4);
layoutParams1.leftMargin = AndroidUtilities.dp(51);
layoutParams1.topMargin = AndroidUtilities.dp(8);
textView1.setLayoutParams(layoutParams1);
textView2 = new TextView(context);
textView2.setGravity(Gravity.CENTER_VERTICAL);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 9);
textView2.setPadding(0, AndroidUtilities.dp(24), AndroidUtilities.dp(8), 0);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
textView2.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView2.setTextColor(0xff464646);
frameLayout.addView(textView2);
textView2.setTextColor(0xff666666);
textView2.setSingleLine(true);
textView2.setEllipsize(TextUtils.TruncateAt.END);
addView(textView2);
layoutParams1 = (FrameLayout.LayoutParams) textView2.getLayoutParams();
layoutParams1.width = FrameLayout.LayoutParams.WRAP_CONTENT;
layoutParams1.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams1.width = LayoutParams.MATCH_PARENT;
layoutParams1.height = LayoutParams.WRAP_CONTENT;
layoutParams1.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams1.leftMargin = AndroidUtilities.dp(51);
layoutParams1.rightMargin = AndroidUtilities.dp(4);
layoutParams1.topMargin = AndroidUtilities.dp(26);
textView2.setLayoutParams(layoutParams1);
}
......@@ -115,7 +111,8 @@ public class PhotoPickerSearchCell extends LinearLayout {
SearchButton searchButton = new SearchButton(context);
searchButton.textView1.setText(LocaleController.getString("SearchImages", R.string.SearchImages));
searchButton.imageView.setImageResource(R.drawable.web_search);
searchButton.textView2.setText(LocaleController.getString("SearchImagesInfo", R.string.SearchImagesInfo));
searchButton.imageView.setImageResource(R.drawable.search_web);
addView(searchButton);
LayoutParams layoutParams = (LayoutParams) searchButton.getLayoutParams();
layoutParams.weight = 0.5f;
......@@ -144,7 +141,7 @@ public class PhotoPickerSearchCell extends LinearLayout {
searchButton = new SearchButton(context);
searchButton.textView1.setText(LocaleController.getString("SearchGifs", R.string.SearchGifs));
searchButton.textView2.setText("GIPHY");
searchButton.imageView.setImageResource(R.drawable.gif_search);
searchButton.imageView.setImageResource(R.drawable.search_gif);
addView(searchButton);
layoutParams = (LayoutParams) searchButton.getLayoutParams();
layoutParams.weight = 0.5f;
......
......@@ -249,6 +249,12 @@ public class SharedDocumentCell extends FrameLayout implements MediaController.
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
MediaController.getInstance().removeLoadingFileObserver(this);
}
public void setChecked(boolean checked, boolean animated) {
if (checkBox.getVisibility() != VISIBLE) {
checkBox.setVisibility(VISIBLE);
......@@ -262,30 +268,40 @@ public class SharedDocumentCell extends FrameLayout implements MediaController.
loaded = false;
loading = false;
int idx = -1;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));
nameTextView.setText(name);
extTextView.setText((idx = name.lastIndexOf(".")) == -1 ? "" : name.substring(idx + 1).toLowerCase());
if (document.messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty) {
if (document != null && document.messageOwner.media != null) {
int idx = -1;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));
nameTextView.setText(name);
extTextView.setText((idx = name.lastIndexOf(".")) == -1 ? "" : name.substring(idx + 1).toLowerCase());
if (document.messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty) {
thumbImageView.setVisibility(GONE);
thumbImageView.setImageBitmap(null);
} else {
thumbImageView.setVisibility(VISIBLE);
thumbImageView.setImage(document.messageOwner.media.document.thumb.location, "40_40", (Drawable) null);
}
long date = (long) document.messageOwner.date * 1000;
dateTextView.setText(String.format("%s, %s", Utilities.formatFileSize(document.messageOwner.media.document.size), LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(new Date(date)), LocaleController.formatterDay.format(new Date(date)))));
} else {
nameTextView.setText("");
extTextView.setText("");
dateTextView.setText("");
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
thumbImageView.setVisibility(GONE);
thumbImageView.setImageBitmap(null);
} else {
thumbImageView.setVisibility(VISIBLE);
thumbImageView.setImage(document.messageOwner.media.document.thumb.location, "40_40", (Drawable) null);
}
long date = (long) document.messageOwner.date * 1000;
dateTextView.setText(String.format("%s, %s", Utilities.formatFileSize(document.messageOwner.media.document.size), LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(new Date(date)), LocaleController.formatterDay.format(new Date(date)))));
setWillNotDraw(!needDivider);
progressView.setProgress(0, false);
updateFileExistIcon();
}
public void updateFileExistIcon() {
if (message != null) {
if (message != null && message.messageOwner.media != null) {
String fileName = null;
File cacheFile = null;
if (message.messageOwner.attachPath == null || message.messageOwner.attachPath.length() == 0 || !(new File(message.messageOwner.attachPath).exists())) {
......
/*
* This is the source code of Telegram for Android v. 2.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2015.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.LocaleController;
public class SharedMediaSectionCell extends FrameLayout {
private TextView textView;
public SharedMediaSectionCell(Context context) {
super(context);
textView = new TextView(getContext());
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setTextColor(0xff222222);
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
addView(textView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)textView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.leftMargin = AndroidUtilities.dp(13);
layoutParams.rightMargin = AndroidUtilities.dp(13);
layoutParams.gravity = LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT;
textView.setLayoutParams(layoutParams);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
}
public void setText(String text) {
textView.setText(text);
}
}
......@@ -55,7 +55,7 @@ public class ChangeChatNameActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
......
......@@ -48,7 +48,7 @@ public class ChangeNameActivity extends BaseFragment {
private final static int done_button = 1;
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......
......@@ -101,7 +101,7 @@ public class ChangePhoneActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName));
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
......@@ -289,9 +289,9 @@ public class ChangePhoneActivity extends BaseFragment {
private int countryState = 0;
private ArrayList<String> countriesArray = new ArrayList<String>();
private HashMap<String, String> countriesMap = new HashMap<String, String>();
private HashMap<String, String> codesMap = new HashMap<String, String>();
private ArrayList<String> countriesArray = new ArrayList<>();
private HashMap<String, String> countriesMap = new HashMap<>();
private HashMap<String, String> codesMap = new HashMap<>();
private boolean ignoreSelection = false;
private boolean ignoreOnTextChange = false;
......@@ -533,7 +533,7 @@ public class ChangePhoneActivity extends BaseFragment {
layoutParams.gravity = Gravity.LEFT;
textView.setLayoutParams(layoutParams);
HashMap<String, String> languageMap = new HashMap<String, String>();
HashMap<String, String> languageMap = new HashMap<>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().getAssets().open("countries.txt")));
String line;
......@@ -1013,7 +1013,7 @@ public class ChangePhoneActivity extends BaseFragment {
destroyCodeTimer();
UserConfig.setCurrentUser(user);
UserConfig.saveConfig(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().putUser(user, false);
......
......@@ -35,7 +35,7 @@ import org.telegram.ui.ActionBar.BaseFragment;
public class ChangePhoneHelpActivity extends BaseFragment {
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......
......@@ -61,7 +61,7 @@ public class ChangeUsernameActivity extends BaseFragment {
private final static int done_button = 1;
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......@@ -205,14 +205,19 @@ public class ChangeUsernameActivity extends BaseFragment {
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if (error.equals("USERNAME_INVALID")) {
builder.setMessage(LocaleController.getString("UsernameInvalid", R.string.UsernameInvalid));
} else if (error.equals("USERNAME_OCCUPIED")) {
builder.setMessage(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
} else if (error.equals("USERNAMES_UNAVAILABLE")) {
builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable));
} else {
builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred));
switch (error) {
case "USERNAME_INVALID":
builder.setMessage(LocaleController.getString("UsernameInvalid", R.string.UsernameInvalid));
break;
case "USERNAME_OCCUPIED":
builder.setMessage(LocaleController.getString("UsernameInUse", R.string.UsernameInUse));
break;
case "USERNAMES_UNAVAILABLE":
builder.setMessage(LocaleController.getString("FeatureUnavailable", R.string.FeatureUnavailable));
break;
default:
builder.setMessage(LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred));
break;
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder);
......
......@@ -13,6 +13,7 @@ import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
......@@ -164,6 +165,11 @@ public class AvatarDrawable extends Drawable {
drawBrodcast = isBroadcast;
if (firstName == null || firstName.length() == 0) {
firstName = lastName;
lastName = null;
}
String text = "";
if (firstName != null && firstName.length() > 0) {
text += firstName.substring(0, 1);
......@@ -176,8 +182,26 @@ public class AvatarDrawable extends Drawable {
}
lastch = lastName.substring(a, a + 1);
}
text += lastch;
if (Build.VERSION.SDK_INT >= 14) {
text += "\u200C" + lastch;
} else {
text += lastch;
}
} else if (firstName != null && firstName.length() > 0) {
for (int a = firstName.length() - 1; a >= 0; a--) {
if (firstName.charAt(a) == ' ') {
if (a != firstName.length() - 1 && firstName.charAt(a + 1) != ' ') {
if (Build.VERSION.SDK_INT >= 14) {
text += "\u200C" + firstName.substring(a + 1, a + 2);
} else {
text += firstName.substring(a + 1, a + 2);
}
break;
}
}
}
}
if (text.length() > 0) {
text = text.toUpperCase();
try {
......
......@@ -11,12 +11,14 @@ package org.telegram.ui.Components;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import org.telegram.android.AndroidUtilities;
import org.telegram.android.ImageLoader;
import org.telegram.android.MediaController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
......@@ -24,10 +26,13 @@ import org.telegram.android.NotificationCenter;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PhotoAlbumPickerActivity;
import org.telegram.ui.PhotoCropActivity;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.PhotoViewer;
import java.io.File;
import java.util.ArrayList;
public class AvatarUpdater implements NotificationCenter.NotificationCenterDelegate, PhotoCropActivity.PhotoEditActivityDelegate {
public String currentPicturePath;
......@@ -68,13 +73,33 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
}
public void openGallery() {
try {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
parentFragment.startActivityForResult(photoPickerIntent, 14);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
PhotoAlbumPickerActivity fragment = new PhotoAlbumPickerActivity(true);
fragment.setDelegate(new PhotoAlbumPickerActivity.PhotoAlbumPickerActivityDelegate() {
@Override
public void didSelectPhotos(ArrayList<String> photos) {
if (!photos.isEmpty()) {
Bitmap bitmap = ImageLoader.loadBitmap(photos.get(0), null, 800, 800, true);
processBitmap(bitmap);
}
}
@Override
public void didSelectWebPhotos(ArrayList<MediaController.SearchImage> photos) {
}
@Override
public void startPhotoSelectActivity() {
try {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
parentFragment.startActivityForResult(photoPickerIntent, 14);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
parentFragment.presentFragment(fragment);
}
private void startCrop(String path, Uri uri) {
......@@ -102,9 +127,42 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 13) {
PhotoViewer.getInstance().setParentActivity(parentFragment.getParentActivity());
int orientation = 0;
try {
ExifInterface ei = new ExifInterface(currentPicturePath);
int exif = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(exif) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
final ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(new MediaController.PhotoEntry(0, 0, 0, currentPicturePath, orientation));
PhotoViewer.getInstance().openPhotoForSelect(arrayList, 0, 1, new PhotoViewer.EmptyPhotoViewerProvider() {
@Override
public void sendButtonPressed(int index) {
String path = null;
MediaController.PhotoEntry photoEntry = (MediaController.PhotoEntry) arrayList.get(0);
if (photoEntry.imagePath != null) {
path = photoEntry.imagePath;
} else if (photoEntry.path != null) {
path = photoEntry.path;
}
Bitmap bitmap = ImageLoader.loadBitmap(path, null, 800, 800, true);
processBitmap(bitmap);
}
});
Utilities.addMediaToGallery(currentPicturePath);
startCrop(currentPicturePath, null);
currentPicturePath = null;
} else if (requestCode == 14) {
if (data == null || data.getData() == null) {
......
......@@ -68,6 +68,10 @@ public class BackupImageView extends View {
setImage(null, path, filter, thumb, null, null, null, 0);
}
public void setOrientation(int angle, boolean center) {
imageReceiver.setOrientation(angle, center);
}
public void setImage(TLObject path, String httpUrl, String filter, Drawable thumb, Bitmap thumbBitmap, TLRPC.FileLocation thumbLocation, String thumbFilter, int size) {
if (thumbBitmap != null) {
thumb = new BitmapDrawable(null, thumbBitmap);
......
......@@ -14,7 +14,6 @@ import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
......@@ -27,9 +26,11 @@ public class ClippingImageView extends View {
private int clipLeft;
private int clipRight;
private int clipTop;
private Rect drawRect;
private int orientation;
private RectF drawRect;
private Paint paint;
private Bitmap bmp;
private Matrix matrix;
private onDrawListener drawListener;
private boolean needRadius;
......@@ -48,7 +49,9 @@ public class ClippingImageView extends View {
super(context);
paint = new Paint();
paint.setFilterBitmap(true);
drawRect = new Rect();
matrix = new Matrix();
drawRect = new RectF();
bitmapRect = new RectF();
}
public int getClipBottom() {
......@@ -85,6 +88,7 @@ public class ClippingImageView extends View {
drawListener.onDraw();
}
canvas.save();
if (needRadius) {
roundRect.set(0, 0, getWidth(), getHeight());
shaderMatrix.reset();
......@@ -92,10 +96,24 @@ public class ClippingImageView extends View {
bitmapShader.setLocalMatrix(shaderMatrix);
canvas.drawRoundRect(roundRect, radius, radius, roundPaint);
} else {
if (orientation == 90 || orientation == 270) {
drawRect.set(-getHeight() / 2, -getWidth() / 2, getHeight() / 2, getWidth() / 2);
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
matrix.postRotate(orientation, 0, 0);
matrix.postTranslate(getWidth() / 2, getHeight() / 2);
} else if (orientation == 180) {
drawRect.set(-getWidth() / 2, -getHeight() / 2, getWidth() / 2, getHeight() / 2);
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
matrix.postRotate(orientation, 0, 0);
matrix.postTranslate(getWidth() / 2, getHeight() / 2);
} else {
drawRect.set(0, 0, getWidth(), getHeight());
matrix.setRectToRect(bitmapRect, drawRect, Matrix.ScaleToFit.FILL);
}
canvas.clipRect(clipLeft / scaleY, clipTop / scaleY, getWidth() - clipRight / scaleY, getHeight() - clipBottom / scaleY);
drawRect.set(0, 0, getWidth(), getHeight());
try {
canvas.drawBitmap(bmp, null, drawRect, paint);
canvas.drawBitmap(bmp, matrix, paint);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
......@@ -136,16 +154,21 @@ public class ClippingImageView extends View {
invalidate();
}
public void setOrientation(int angle) {
orientation = angle;
}
public void setImageBitmap(Bitmap bitmap) {
bmp = bitmap;
if (bitmap != null && needRadius) {
roundRect = new RectF();
shaderMatrix = new Matrix();
bitmapRect = new RectF();
if (bitmap != null) {
bitmapRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
roundPaint.setShader(bitmapShader);
if (needRadius) {
roundRect = new RectF();
shaderMatrix = new Matrix();
bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
roundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
roundPaint.setShader(bitmapShader);
}
}
invalidate();
}
......
/*
* This is the source code of Telegram for Android v. 2.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2015.
*/
package org.telegram.ui.Components;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import org.telegram.messenger.FileLog;
import java.util.concurrent.CopyOnWriteArrayList;
public class ForegroundDetector implements Application.ActivityLifecycleCallbacks {
public interface Listener {
public void onBecameForeground();
public void onBecameBackground();
}
private int refs;
private boolean wasInBackground = true;
private long enterBackgroundTime = 0;
private CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
private static ForegroundDetector Instance = null;
public static ForegroundDetector getInstance() {
return Instance;
}
public ForegroundDetector(Application application) {
Instance = this;
application.registerActivityLifecycleCallbacks(this);
}
public boolean isForeground() {
return refs > 0;
}
public boolean isBackground() {
return refs == 0;
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
@Override
public void onActivityStarted(Activity activity) {
if (++refs == 1) {
if (System.currentTimeMillis() - enterBackgroundTime < 200) {
wasInBackground = false;
}
FileLog.e("tmessages", "switch to foreground");
for (Listener listener : listeners) {
try {
listener.onBecameForeground();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
}
public boolean isWasInBackground(boolean reset) {
if (reset && Build.VERSION.SDK_INT >= 21 && (System.currentTimeMillis() - enterBackgroundTime < 200)) {
wasInBackground = false;
}
return wasInBackground;
}
public void resetBackgroundVar() {
wasInBackground = false;
}
@Override
public void onActivityStopped(Activity activity) {
if (--refs == 0) {
enterBackgroundTime = System.currentTimeMillis();
wasInBackground = true;
FileLog.e("tmessages", "switch to background");
for (Listener listener : listeners) {
try {
listener.onBecameBackground();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
......@@ -73,7 +73,7 @@ public class NumberPicker extends LinearLayout {
private OnScrollListener mOnScrollListener;
private Formatter mFormatter;
private long mLongPressUpdateInterval = DEFAULT_LONG_PRESS_UPDATE_INTERVAL;
private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<String>();
private final SparseArray<String> mSelectorIndexToStringCache = new SparseArray<>();
private final int[] mSelectorIndices = new int[SELECTOR_WHEEL_ITEM_COUNT];
private Paint mSelectorWheelPaint;
private Drawable mVirtualButtonPressedDrawable;
......
......@@ -78,7 +78,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......
......@@ -32,7 +32,7 @@ import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Components.SectionsListView;
import org.telegram.ui.Components.LetterSectionsListView;
public class CountrySelectActivity extends BaseFragment {
......@@ -40,7 +40,7 @@ public class CountrySelectActivity extends BaseFragment {
public abstract void didSelectCountry(String name);
}
private SectionsListView listView;
private LetterSectionsListView listView;
private TextView emptyTextView;
private CountryAdapter listViewAdapter;
private CountrySearchAdapter searchListViewAdapter;
......@@ -61,7 +61,7 @@ public class CountrySelectActivity extends BaseFragment {
}
@Override
public View createView(LayoutInflater inflater, final ViewGroup container) {
public View createView(LayoutInflater inflater) {
if (fragmentView == null) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
......@@ -88,7 +88,6 @@ public class CountrySelectActivity extends BaseFragment {
searchListViewAdapter.search(null);
searching = false;
searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter);
if (android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(true);
......@@ -165,7 +164,7 @@ public class CountrySelectActivity extends BaseFragment {
layoutParams1.weight = 0.5f;
frameLayout.setLayoutParams(layoutParams1);
listView = new SectionsListView(getParentActivity());
listView = new LetterSectionsListView(getParentActivity());
listView.setEmptyView(emptyTextLayout);
listView.setVerticalScrollBarEnabled(false);
listView.setDivider(null);
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment