diff --git a/TMessagesProj/config/debug/AndroidManifest.xml b/TMessagesProj/config/debug/AndroidManifest.xml
index 7836674f..dacb8608 100644
--- a/TMessagesProj/config/debug/AndroidManifest.xml
+++ b/TMessagesProj/config/debug/AndroidManifest.xml
@@ -9,14 +9,14 @@
-
-
+
+
-
-
+
+
-
+
@@ -37,7 +37,7 @@
-
+
diff --git a/TMessagesProj/config/foss/AndroidManifest.xml b/TMessagesProj/config/foss/AndroidManifest.xml
index df2d1e24..59b2f53b 100644
--- a/TMessagesProj/config/foss/AndroidManifest.xml
+++ b/TMessagesProj/config/foss/AndroidManifest.xml
@@ -9,7 +9,7 @@
android:label="@string/AppName"
android:theme="@style/Theme.TMessages.Start"
android:name=".ApplicationLoader"
- android:hardwareAccelerated="true"
+ android:hardwareAccelerated="@bool/useHardwareAcceleration"
android:largeHeap="true">
diff --git a/TMessagesProj/config/release/AndroidManifest.xml b/TMessagesProj/config/release/AndroidManifest.xml
index 17c2c245..31c5f085 100644
--- a/TMessagesProj/config/release/AndroidManifest.xml
+++ b/TMessagesProj/config/release/AndroidManifest.xml
@@ -9,14 +9,14 @@
-
-
+
+
-
-
+
+
-
+
@@ -37,7 +37,7 @@
-
+
diff --git a/TMessagesProj/jni/Android.mk b/TMessagesProj/jni/Android.mk
index 88b4e639..ae2c6323 100755
--- a/TMessagesProj/jni/Android.mk
+++ b/TMessagesProj/jni/Android.mk
@@ -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
diff --git a/TMessagesProj/jni/image.c b/TMessagesProj/jni/image.c
index 1532095b..06c5e9f3 100644
--- a/TMessagesProj/jni/image.c
+++ b/TMessagesProj/jni/image.c
@@ -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;
diff --git a/TMessagesProj/libs/armeabi-v7a/libtmessages.5.so b/TMessagesProj/libs/armeabi-v7a/libtmessages.6.so
old mode 100755
new mode 100644
similarity index 84%
rename from TMessagesProj/libs/armeabi-v7a/libtmessages.5.so
rename to TMessagesProj/libs/armeabi-v7a/libtmessages.6.so
index 132154ab..41f66ec8
Binary files a/TMessagesProj/libs/armeabi-v7a/libtmessages.5.so and b/TMessagesProj/libs/armeabi-v7a/libtmessages.6.so differ
diff --git a/TMessagesProj/libs/armeabi/libtmessages.5.so b/TMessagesProj/libs/armeabi/libtmessages.6.so
old mode 100755
new mode 100644
similarity index 76%
rename from TMessagesProj/libs/armeabi/libtmessages.5.so
rename to TMessagesProj/libs/armeabi/libtmessages.6.so
index 3e08cd8f..aa46c089
Binary files a/TMessagesProj/libs/armeabi/libtmessages.5.so and b/TMessagesProj/libs/armeabi/libtmessages.6.so differ
diff --git a/TMessagesProj/libs/x86/libtmessages.5.so b/TMessagesProj/libs/x86/libtmessages.6.so
old mode 100755
new mode 100644
similarity index 72%
rename from TMessagesProj/libs/x86/libtmessages.5.so
rename to TMessagesProj/libs/x86/libtmessages.6.so
index 326a064f..e455cf5a
Binary files a/TMessagesProj/libs/x86/libtmessages.5.so and b/TMessagesProj/libs/x86/libtmessages.6.so differ
diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml
index 5ca90c91..dd3c5fc2 100644
--- a/TMessagesProj/src/main/AndroidManifest.xml
+++ b/TMessagesProj/src/main/AndroidManifest.xml
@@ -43,7 +43,7 @@
diff --git a/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java b/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
index 39966ac1..878a92ac 100755
--- a/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
+++ b/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
@@ -28,7 +28,7 @@ public class ByteStream {
private final ArrayList queue;
public ByteStream() {
- this.queue = new ArrayList();
+ this.queue = new ArrayList<>();
}
public void append(ByteBufferDesc buf) {
diff --git a/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java b/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
index a6dbff0a..63081ef8 100644
--- a/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
+++ b/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
@@ -25,6 +25,7 @@
package org.telegram.PhoneFormat;
import org.telegram.messenger.ApplicationLoader;
+import org.telegram.messenger.FileLog;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -97,9 +98,11 @@ public class PhoneFormat {
}
public void init(String countryCode) {
+ InputStream stream = null;
+ ByteArrayOutputStream bos = null;
try {
- InputStream stream = ApplicationLoader.applicationContext.getAssets().open("PhoneFormats.dat");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ stream = ApplicationLoader.applicationContext.getAssets().open("PhoneFormats.dat");
+ bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = stream.read(buf, 0, 1024)) != -1) {
@@ -111,6 +114,21 @@ public class PhoneFormat {
} catch (Exception e) {
e.printStackTrace();
return;
+ } finally {
+ try {
+ if (bos != null) {
+ bos.close();
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
if (countryCode != null && countryCode.length() != 0) {
@@ -119,10 +137,10 @@ public class PhoneFormat {
Locale loc = Locale.getDefault();
defaultCountry = loc.getCountry().toLowerCase();
}
- callingCodeOffsets = new HashMap(255);
- callingCodeCountries = new HashMap>(255);
- callingCodeData = new HashMap(10);
- countryCallingCode = new HashMap(255);
+ callingCodeOffsets = new HashMap<>(255);
+ callingCodeCountries = new HashMap<>(255);
+ callingCodeData = new HashMap<>(10);
+ countryCallingCode = new HashMap<>(255);
parseDataHeader();
initialzed = true;
@@ -293,7 +311,7 @@ public class PhoneFormat {
offset += 2;
- ArrayList strs = new ArrayList(5);
+ ArrayList strs = new ArrayList<>(5);
String str;
while ((str = valueString(offset)).length() != 0) {
strs.add(str);
@@ -302,14 +320,14 @@ public class PhoneFormat {
res.trunkPrefixes = strs;
offset++;
- strs = new ArrayList(5);
+ strs = new ArrayList<>(5);
while ((str = valueString(offset)).length() != 0) {
strs.add(str);
offset += str.length() + 1;
}
res.intlPrefixes = strs;
- ArrayList ruleSets = new ArrayList(setCnt);
+ ArrayList ruleSets = new ArrayList<>(setCnt);
offset = start + block1Len;
for (int s = 0; s < setCnt; s++) {
RuleSet ruleSet = new RuleSet();
@@ -317,7 +335,7 @@ public class PhoneFormat {
offset += 2;
int ruleCnt = value16(offset);
offset += 2;
- ArrayList rules = new ArrayList(ruleCnt);
+ ArrayList rules = new ArrayList<>(ruleCnt);
for (int r = 0; r < ruleCnt; r++) {
PhoneRule rule = new PhoneRule();
rule.minVal = value32(offset);
@@ -380,7 +398,7 @@ public class PhoneFormat {
callingCodeOffsets.put(callingCode, offset);
ArrayList countries = callingCodeCountries.get(callingCode);
if (countries == null) {
- countries = new ArrayList();
+ countries = new ArrayList<>();
callingCodeCountries.put(callingCode, countries);
}
countries.add(country);
diff --git a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
index 4455445f..fe19cfc7 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
@@ -9,20 +9,30 @@
package org.telegram.android;
import android.app.Activity;
+import android.app.AlarmManager;
import android.app.AlertDialog;
+import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
+import android.graphics.Color;
import android.graphics.Point;
+import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Typeface;
+import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
+import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
+import android.util.DisplayMetrics;
+import android.util.Log;
import android.util.StateSet;
import android.view.Display;
import android.view.Surface;
@@ -33,20 +43,34 @@ 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 android.widget.Toast;
+import org.telegram.messenger.ApplicationLoader;
+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.ActionBar.ActionBar;
+import org.telegram.ui.Components.ForegroundDetector;
import org.telegram.ui.Components.NumberPicker;
import org.telegram.ui.Components.TypefaceSpan;
+import org.telegram.ui.LaunchActivity;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Hashtable;
+import java.util.List;
public class AndroidUtilities {
@@ -59,15 +83,26 @@ 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;
+ public static final String THEME_PREFS = "theme";
+ private static final String TAG = "AndroidUtilities";
+ public static final int defColor = 0xff58BCD5;//0xff43C3DB;//0xff2f8cc9;58BCD5//0xff55abd2
+ public static int themeColor = getIntColor("themeColor");
+
+ public static boolean needRestart = false;
+
+ //public static boolean hideScreenshot = false;
+ //public static boolean hideMobile = false;
+
static {
density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
checkDisplaySize();
}
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 +150,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 +263,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 +277,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 +461,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 +583,364 @@ 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());
+ }
+
+ /*public static void turnOffHardwareAcceleration(Window window) {
+ if (window == null || Build.MODEL == null || Build.VERSION.SDK_INT < 11) {
+ return;
+ }
+ if (Build.MODEL.contains("GT-S5301") ||
+ Build.MODEL.contains("GT-S5303") ||
+ Build.MODEL.contains("GT-B5330") ||
+ Build.MODEL.contains("GT-S5302") ||
+ Build.MODEL.contains("GT-S6012B") ||
+ Build.MODEL.contains("MegaFon_SP-AI")) {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
+ }
+ }*/
+ //NEW
+ public static int getIntColor(String key){
+ SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, Activity.MODE_PRIVATE);
+ return themePrefs.getInt(key, defColor);
+ }
+
+ public static int getIntDef(String key, int def){
+ SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, Activity.MODE_PRIVATE);
+ return themePrefs.getInt(key, def);
+ }
+
+ public static int getIntAlphaColor(String key, float factor){
+ SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, Activity.MODE_PRIVATE);
+ int color = themePrefs.getInt(key, defColor);
+ int alpha = Math.round(Color.alpha(color) * factor);
+ int red = Color.red(color);
+ int green = Color.green(color);
+ int blue = Color.blue(color);
+ return Color.argb(alpha, red, green, blue);
+ }
+
+ public static int getIntDarkerColor(String key, int factor){
+ SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, Activity.MODE_PRIVATE);
+ int color = themePrefs.getInt(key, defColor);
+ return setDarkColor(color, factor);
+ }
+
+ public static int setDarkColor(int color, int factor){
+ int red = Color.red(color) - factor;
+ int green = Color.green(color) - factor;
+ int blue = Color.blue(color) - factor;
+ if(factor < 0){
+ red = (red > 0xff) ? 0xff : red;
+ green = (green > 0xff) ? 0xff : green;
+ blue = (blue > 0xff) ? 0xff : blue;
+ if(red == 0xff && green == 0xff && blue == 0xff){
+ red = factor;
+ green = factor;
+ blue = factor;
+ }
+ }
+ if(factor > 0){
+ red = (red < 0) ? 0 : red;
+ green = (green < 0) ? 0 : green;
+ blue = (blue < 0) ? 0 : blue;
+ if(red == 0 && green == 0 && blue == 0){
+ red = factor;
+ green = factor;
+ blue = factor;
+ }
+ }
+ return Color.argb(0xff, red, green, blue);
+ }
+
+ public static void setIntColor(String key, int value){
+ SharedPreferences themePrefs = ApplicationLoader.applicationContext.getSharedPreferences(THEME_PREFS, Activity.MODE_PRIVATE);
+ SharedPreferences.Editor e = themePrefs.edit();
+ e.putInt(key, value);
+ e.commit();
+ }
+
+ public static void setBoolPref(Context context, String key, Boolean b){
+ SharedPreferences sharedPref = context.getSharedPreferences(THEME_PREFS, 0);
+ SharedPreferences.Editor e = sharedPref.edit();
+ e.putBoolean(key, b);
+ e.commit();
+ }
+
+ public static void setStringPref(Context context, String key, String s){
+ SharedPreferences sharedPref = context.getSharedPreferences(THEME_PREFS, 0);
+ SharedPreferences.Editor e = sharedPref.edit();
+ e.putString(key, s);
+ e.commit();
+ }
+
+ public static boolean getBoolPref(Context context,String key){
+ boolean s = false;
+ if (context.getSharedPreferences(THEME_PREFS, 0).getBoolean(key, false)) s=true;
+ return s;
+ }
+
+ public static boolean getBoolMain(String key){
+ boolean s = false;
+ if (ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean(key, false)) s=true;
+ return s;
+ }
+
+ public static int getIntPref(Context context,String key){
+ int i=0;
+ if(key.contains("picker")){
+ int intColor = context.getSharedPreferences(THEME_PREFS, 0).getInt(key, Color.WHITE );
+ i=intColor;
+ }
+ return i;
+ }
+/*
+ public static int getIntColorDef(Context context, String key, int def){
+ int i=def;
+ if(context.getSharedPreferences(THEME_PREFS, 0).getBoolean(key, false)){
+ i = context.getSharedPreferences(THEME_PREFS, 0).getInt(key.replace("_check", "_picker"), def);
+ }
+ return i;
+ }*/
+
+ public static void setTVTextColor(Context ctx, TextView tv, String key, int def){
+ if(tv==null)return;
+ if(getBoolPref(ctx, key))
+ def = getIntPref(ctx, key.replace("_check", "_picker"));
+ tv.setTextColor(def);
+ }
+
+ public static int getSizePref(Context context,String key, int def){
+ if(key.contains("picker"))return context.getSharedPreferences(THEME_PREFS, 0).getInt(key, def);
+ return def;
+ }
+
+ public static void paintActionBarHeader(Activity a, ActionBar ab, String hdCheck, String gdMode){
+ if(ab==null)return;
+ ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#54759E")));
+ if(getBoolPref(a, hdCheck)){
+ int i = getIntPref(a, hdCheck.replace("_check", "_picker"));
+ Drawable d = new ColorDrawable(i);
+ try{
+ ab.setBackgroundDrawable(d);
+ d = paintGradient(a,i,gdMode.replace("mode","color_picker"),gdMode);
+ if(d!=null)ab.setBackgroundDrawable(d);
+ } catch (Exception e) {
+ Log.e(TAG, e.toString());
+ }
+ }
+ }
+
+ public static Drawable paintGradient(Context c, int mainColor, String gColor, String g){
+ GradientDrawable gd = null;
+ int[] a ={mainColor,getIntPref(c,gColor)};
+ int gType = Integer.parseInt(c.getSharedPreferences(THEME_PREFS, 0).getString(g, "0"));
+ if(gType==2) gd = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,a);
+ if(gType==1) gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM ,a);
+ return gd;
+ }
+
+ public static Drawable paintDrawable(Context c, int resId, int resIdW, String color){
+ Drawable d = c.getResources().getDrawable(resId);
+ if(color.contains("_check")){
+ if(getBoolPref(c, color)){
+ d = c.getResources().getDrawable(resIdW);
+ d.setColorFilter(getIntPref(c, color.replace("_check", "_picker")), PorterDuff.Mode.MULTIPLY);
+ }
+ }
+ return d;
+ }
+
+ public static void restartApp(){
+ Intent mRestartApp = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
+ int mPendingIntentId = 123456;
+ PendingIntent mPendingIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, mPendingIntentId, mRestartApp, PendingIntent.FLAG_CANCEL_CURRENT);
+ AlarmManager mgr = (AlarmManager)ApplicationLoader.applicationContext.getSystemService(Context.ALARM_SERVICE);
+ mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
+ System.exit(0);
+ }
+
+ public static void savePreferencesToSD(Context context, String prefName, String tName, boolean toast){
+ String folder = "/Telegram/Themes";
+ File dataF = new File (findPrefFolder(context),prefName);
+ if(checkSDStatus() > 1){
+ File f = new File (Environment.getExternalStorageDirectory(), folder);
+ f.mkdirs();
+ File sdF = new File(f, tName);
+ String s = getError(copyFile(dataF,sdF,true));
+ if (s.equalsIgnoreCase("4")) {
+ if(toast && sdF.getName()!="")Toast.makeText(context,context.getString(R.string.SavedTo,sdF.getName(),folder),Toast.LENGTH_SHORT ).show();
+ }else if (s.contains("0")) {
+ s = context.getString(R.string.SaveErrorMsg0);
+ Toast.makeText(context,"ERROR: "+ s ,Toast.LENGTH_LONG ).show();
+ }else{
+ Toast.makeText(context,"ERROR: "+s,Toast.LENGTH_LONG ).show();
+ Toast.makeText(context,dataF.getAbsolutePath(),Toast.LENGTH_LONG ).show();
+ }
+ }else{
+ Toast.makeText(context,"ERROR: " + context.getString(R.string.NoMediaMessage) , Toast.LENGTH_LONG ).show();
+ }
+ }
+
+ public static void copyWallpaperToSD(Context context, String tName, boolean toast){
+ String folder = "/Telegram/Themes";
+ String nFile = "wallpaper.jpg";
+ if(checkSDStatus()>0){
+ File f1 = context.getFilesDir();
+ f1 = new File (f1.getAbsolutePath(), nFile);
+ File f2 = new File (Environment.getExternalStorageDirectory(), folder);
+ f2.mkdirs();
+ f2 = new File(f2, tName+"_"+nFile);
+ if(f1.length()>1){
+ String s = getError(copyFile(f1,f2,true));
+ if(s.contains("4")){
+ if(toast && f2.getName()!="" && folder !="")Toast.makeText(context,context.getString(R.string.SavedTo,f2.getName(),folder),Toast.LENGTH_SHORT ).show();
+ if(f2.getName()=="" || folder =="") Toast.makeText(context,"ERROR: "+s,Toast.LENGTH_SHORT ).show();
+
+ }else{
+ Toast.makeText(context,"ERROR: "+s+"\n"+f1.getAbsolutePath(),Toast.LENGTH_LONG ).show();
+ }
+ }
+ }
+ }
+
+ static String findPrefFolder(Context context){
+ File f = context.getFilesDir();
+ String appDir = f.getAbsolutePath();
+ File SPDir = new File (appDir.substring(0,appDir.lastIndexOf('/')+1)+ "shared_prefs/");
+ if(!SPDir.exists()) {// && SPDir.isDirectory()) {
+ String pck = context.getPackageName();
+ SPDir=new File ("/dbdata/databases/"+pck+"/shared_prefs/");
+ }
+ //Log.i("TAG", SPDir.getAbsolutePath());
+ return SPDir.getAbsolutePath();
+ }
+
+ static int checkSDStatus(){
+ int b=0;
+ String s = Environment.getExternalStorageState();
+ if (s.equals(Environment.MEDIA_MOUNTED))b=2;
+ else if (s.equals(Environment.MEDIA_MOUNTED_READ_ONLY))b=1;
+ return b;
+ }
+
+ static String getError(int i){
+ String s="-1";
+ if(i==0)s="0: SOURCE FILE DOESN'T EXIST";
+ if(i==1)s="1: DESTINATION FILE DOESN'T EXIST";
+ if(i==2)s="2: NULL SOURCE & DESTINATION FILES";
+ if(i==3)s="3: NULL SOURCE FILE";
+ if(i==4)s="4";
+ return s;
+ }
+
+ //0: source file doesn't exist
+ //1: dest file doesn't exist
+ //2: source & dest = NULL
+ //3: source = NULL
+ //4: dest = NULL
+ static int copyFile(File sourceFile, File destFile, boolean save) {
+ int i=-1;
+ try{
+ if (!sourceFile.exists()) {
+ return i+1;
+ }
+ if (!destFile.exists()) {
+ if(save)i=i+2;
+ destFile.createNewFile();
+ }
+ FileChannel source = null;
+ FileChannel destination = null;
+ FileInputStream fileInputStream = new FileInputStream(sourceFile);
+ source = fileInputStream.getChannel();
+ FileOutputStream fileOutputStream = new FileOutputStream(destFile);
+ destination = fileOutputStream.getChannel();
+ if (destination != null && source != null) {
+ destination.transferFrom(source, 0, source.size());
+ i=2;
+ }
+ if (source != null) {
+ source.close();
+ i=3;
+ }
+ if (destination != null) {
+ destination.close();
+ i=4;
+ }
+ fileInputStream.close();
+ fileOutputStream.close();
+ }catch (Exception e)
+ {
+ System.err.println("Error saving preferences: " + e.getMessage());
+ Log.e(e.getMessage() , e.toString());
+ }
+ return i;
+ }
+
+ public static int loadPrefFromSD(Context context, String prefPath){
+ File dataF = new File (findPrefFolder(context), THEME_PREFS + ".xml");
+ File prefFile = new File (prefPath);
+ String s = getError(copyFile(prefFile, dataF, false));
+ if (s.contains("0")) {
+ Toast.makeText(context,"ERROR: "+ context.getString(R.string.restoreErrorMsg, prefFile.getAbsolutePath()) , Toast.LENGTH_LONG ).show();
+ }
+ return Integer.parseInt(s);
+ }
+
+ public static int loadWallpaperFromSDPath(Context context, String wPath){
+ String nFile = "wallpaper.jpg";
+ File f1 = context.getFilesDir();
+ f1= new File (f1.getAbsolutePath(), nFile);
+ //Log.i("f1", f1.getAbsolutePath());
+ File wFile = new File (wPath);
+ //Log.i("wPath", wPath);
+ //Log.i("wFile", wFile.getAbsolutePath());
+ String s = "-1";
+ if (wFile.exists()){
+ s = getError(copyFile(wFile,f1,false));
+ if (s.contains("0")) {
+ Toast.makeText(context,"ERROR: "+ context.getString(R.string.restoreErrorMsg,wFile.getAbsolutePath()) ,Toast.LENGTH_LONG ).show();
+ }else{
+ Toast.makeText(context,"ERROR: "+s+"\n"+wFile.getAbsolutePath(),Toast.LENGTH_LONG ).show();
+ }
+ }
+ return Integer.parseInt(s);
+ }
+/*
+ static void modifyXMLfile(File preffile,String sname){
+ try {
+ File file = preffile;
+ //Log.e("modifyXMLfile",preffile.getAbsolutePath());
+ //Log.e("modifyXMLfile",preffile.exists()+"");
+ List lines = new ArrayList();
+ // first, read the file and store the changes
+ BufferedReader in = new BufferedReader(new FileReader(file));
+ String line = in.readLine();
+ while (line != null) {
+ if (!line.contains(sname))lines.add(line);
+ //Log.e("modifyXMLfile",line);
+ line = in.readLine();
+ }
+ in.close();
+ // now, write the file again with the changes
+ PrintWriter out = new PrintWriter(file);
+ for (String l : lines)
+ out.println(l);
+ out.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }*/
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
index 75cb7bcb..4894e628 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
@@ -54,6 +54,7 @@ public class ContactsController {
private ArrayList delayedContactsUpdate = new ArrayList<>();
private String inviteText;
private boolean updatingInviteText = false;
+ private HashMap sectionsToReplace = new HashMap<>();
private int loadingDeleteInfo = 0;
private int deleteAccountTTL;
@@ -114,6 +115,28 @@ public class ContactsController {
if (preferences.getBoolean("needGetStatuses", false)) {
reloadContactsStatuses();
}
+
+ sectionsToReplace.put("À", "A");
+ sectionsToReplace.put("Á", "A");
+ sectionsToReplace.put("Ä", "A");
+ sectionsToReplace.put("Ù", "U");
+ sectionsToReplace.put("Ú", "U");
+ sectionsToReplace.put("Ü", "U");
+ sectionsToReplace.put("Ì", "I");
+ sectionsToReplace.put("Í", "I");
+ sectionsToReplace.put("Ï", "I");
+ sectionsToReplace.put("È", "E");
+ sectionsToReplace.put("É", "E");
+ sectionsToReplace.put("Ê", "E");
+ sectionsToReplace.put("Ë", "E");
+ sectionsToReplace.put("Ò", "O");
+ sectionsToReplace.put("Ó", "O");
+ sectionsToReplace.put("Ö", "O");
+ sectionsToReplace.put("Ç", "C");
+ sectionsToReplace.put("Ñ", "N");
+ sectionsToReplace.put("Ÿ", "Y");
+ sectionsToReplace.put("Ý", "Y");
+ sectionsToReplace.put("Ţ", "Y");
}
public void cleanup() {
@@ -514,10 +537,10 @@ public class ContactsController {
checkContactsInternal();
}
final HashMap contactsMap = readContactsFromPhoneBook();
- final HashMap contactsBookShort = new HashMap();
+ final HashMap contactsBookShort = new HashMap<>();
int oldCount = contactHashMap.size();
- ArrayList toImport = new ArrayList();
+ ArrayList toImport = new ArrayList<>();
if (!contactHashMap.isEmpty()) {
for (HashMap.Entry pair : contactsMap.entrySet()) {
Integer id = pair.getKey();
@@ -619,10 +642,10 @@ public class ContactsController {
}
}
- final ArrayList toDelete = new ArrayList();
+ final ArrayList toDelete = new ArrayList<>();
if (contactHashMap != null && !contactHashMap.isEmpty()) {
try {
- final HashMap contactsPhonesShort = new HashMap();
+ final HashMap contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -692,7 +715,7 @@ public class ContactsController {
}
final int count = (int)Math.ceil(toImport.size() / 500.0f);
for (int a = 0; a < count; a++) {
- ArrayList finalToImport = new ArrayList();
+ ArrayList finalToImport = new ArrayList<>();
finalToImport.addAll(toImport.subList(a * 500, Math.min((a + 1) * 500, toImport.size())));
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
req.contacts = finalToImport;
@@ -713,7 +736,7 @@ public class ContactsController {
// }
}
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
- ArrayList cArr = new ArrayList();
+ ArrayList cArr = new ArrayList<>();
for (TLRPC.TL_importedContact c : res.imported) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = c.user_id;
@@ -848,7 +871,7 @@ public class ContactsController {
public void run() {
MessagesController.getInstance().putUsers(usersArr, from == 1);
- final HashMap usersDict = new HashMap();
+ final HashMap usersDict = new HashMap<>();
final boolean isEmpty = contactsArr.isEmpty();
@@ -933,9 +956,9 @@ public class ContactsController {
}
});
- final SparseArray contactsDictionary = new SparseArray();
- final HashMap> sectionsDict = new HashMap>();
- final ArrayList sortedSectionsArray = new ArrayList();
+ final SparseArray contactsDictionary = new SparseArray<>();
+ final HashMap> sectionsDict = new HashMap<>();
+ final ArrayList sortedSectionsArray = new ArrayList<>();
HashMap contactsByPhonesDict = null;
if (!contactsBookLoaded) {
@@ -958,13 +981,17 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
+ if (key.length() > 1) {
+ key = key.substring(0, 1);
+ }
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
- if (key.length() > 1) {
- key = key.substring(0, 1);
+ String replace = sectionsToReplace.get(key);
+ if (replace != null) {
+ key = replace;
}
ArrayList arr = sectionsDict.get(key);
if (arr == null) {
@@ -1067,7 +1094,7 @@ public class ContactsController {
}
private void updateUnregisteredContacts(final ArrayList contactsArr) {
- final HashMap contactsPhonesShort = new HashMap();
+ final HashMap contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contactsArr) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -1077,7 +1104,7 @@ public class ContactsController {
contactsPhonesShort.put(user.phone, value);
}
- final ArrayList sortedPhoneBookContacts = new ArrayList();
+ final ArrayList sortedPhoneBookContacts = new ArrayList<>();
for (HashMap.Entry pair : contactsBook.entrySet()) {
Contact value = pair.getValue();
int id = pair.getKey();
@@ -1135,8 +1162,8 @@ public class ContactsController {
}
StringBuilder ids = new StringBuilder();
- final HashMap> sectionsDict = new HashMap>();
- final ArrayList sortedSectionsArray = new ArrayList();
+ final HashMap> sectionsDict = new HashMap<>();
+ final ArrayList sortedSectionsArray = new ArrayList<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -1148,17 +1175,21 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
+ if (key.length() > 1) {
+ key = key.substring(0, 1);
+ }
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
- if (key.length() > 1) {
- key = key.substring(0, 1);
+ String replace = sectionsToReplace.get(key);
+ if (replace != null) {
+ key = replace;
}
ArrayList arr = sectionsDict.get(key);
if (arr == null) {
- arr = new ArrayList();
+ arr = new ArrayList<>();
sectionsDict.put(key, arr);
sortedSectionsArray.add(key);
}
@@ -1193,7 +1224,7 @@ public class ContactsController {
try {
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, currentAccount.type).build();
Cursor c1 = ApplicationLoader.applicationContext.getContentResolver().query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
- HashMap bookContacts = new HashMap();
+ HashMap bookContacts = new HashMap<>();
if (c1 != null) {
while (c1.moveToNext()) {
bookContacts.put(c1.getInt(1), c1.getLong(0));
@@ -1213,7 +1244,7 @@ public class ContactsController {
}
private void performWriteContactsToPhoneBook() {
- final ArrayList contactsArray = new ArrayList();
+ final ArrayList contactsArray = new ArrayList<>();
contactsArray.addAll(contacts);
Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override
@@ -1225,8 +1256,8 @@ public class ContactsController {
private void applyContactsUpdates(ArrayList ids, ConcurrentHashMap userDict, ArrayList newC, ArrayList contactsTD) {
if (newC == null || contactsTD == null) {
- newC = new ArrayList();
- contactsTD = new ArrayList();
+ newC = new ArrayList<>();
+ contactsTD = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@@ -1351,8 +1382,8 @@ public class ContactsController {
}
public void processContactsUpdates(ArrayList ids, ConcurrentHashMap userDict) {
- final ArrayList newContacts = new ArrayList();
- final ArrayList contactsToDelete = new ArrayList();
+ final ArrayList newContacts = new ArrayList<>();
+ final ArrayList contactsToDelete = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@@ -1406,7 +1437,7 @@ public class ContactsController {
}
}
- ArrayList query = new ArrayList();
+ ArrayList query = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name);
@@ -1471,7 +1502,7 @@ public class ContactsController {
}
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
- ArrayList contactsParams = new ArrayList();
+ ArrayList contactsParams = new ArrayList<>();
TLRPC.TL_inputPhoneContact c = new TLRPC.TL_inputPhoneContact();
c.phone = user.phone;
if (!c.phone.startsWith("+")) {
@@ -1510,7 +1541,7 @@ public class ContactsController {
});
TLRPC.TL_contact newContact = new TLRPC.TL_contact();
newContact.user_id = u.id;
- ArrayList arrayList = new ArrayList();
+ ArrayList arrayList = new ArrayList<>();
arrayList.add(newContact);
MessagesStorage.getInstance().putContacts(arrayList, false);
@@ -1552,7 +1583,7 @@ public class ContactsController {
return;
}
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
- final ArrayList uids = new ArrayList();
+ final ArrayList uids = new ArrayList<>();
for (TLRPC.User user : users) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser == null) {
@@ -1631,7 +1662,7 @@ public class ContactsController {
editor.remove("needGetStatuses").commit();
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
- ArrayList dbUsersStatus = new ArrayList();
+ ArrayList dbUsersStatus = new ArrayList<>();
for (Object object : vector.objects) {
TLRPC.User toDbUser = new TLRPC.User();
TLRPC.TL_contactStatus status = (TLRPC.TL_contactStatus) object;
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
index 1e9a454a..2cca9e96 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
@@ -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);
@@ -449,6 +449,11 @@ public class ImageLoader {
originalBitmap = scaledBitmap;
FileOutputStream stream = new FileOutputStream(thumbFile);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
+ try {
+ stream.close();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
final BitmapDrawable bitmapDrawable = new BitmapDrawable(originalBitmap);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
@@ -615,7 +620,9 @@ public class ImageLoader {
if (mediaId != null) {
MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts);
} else {
- BitmapFactory.decodeFile(cacheImage.finalFilePath.getAbsolutePath(), opts);
+ FileInputStream is = new FileInputStream(cacheFileFinal);
+ image = BitmapFactory.decodeStream(is, null, opts);
+ is.close();
}
float photoW = opts.outWidth;
@@ -633,7 +640,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 +1064,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 +1691,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);
- }
- };
- retryHttpsTasks.put(oldTask.url, runnable);
- AndroidUtilities.runOnUIThread(runnable, 1000);
- } else {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
+ 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);
+ }
+ } 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) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
index 9c467f72..6ecff83d 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
@@ -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;
diff --git a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
index db7b228b..1d2094bc 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
@@ -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());
@@ -443,10 +444,12 @@ public class LocaleController {
}
private HashMap getLocaleFileStrings(File file) {
+ FileInputStream stream = null;
try {
HashMap stringMap = new HashMap<>();
XmlPullParser parser = Xml.newPullParser();
- parser.setInput(new FileInputStream(file), "UTF-8");
+ stream = new FileInputStream(file);
+ parser.setInput(stream, "UTF-8");
int eventType = parser.getEventType();
String name = null;
String value = null;
@@ -483,6 +486,15 @@ public class LocaleController {
return stringMap;
} catch (Exception e) {
FileLog.e("tmessages", e);
+ } finally {
+ try {
+ if (stream != null) {
+ stream.close();
+ stream = null;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
return null;
}
@@ -544,6 +556,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 +586,9 @@ public class LocaleController {
if (value == null) {
value = ApplicationLoader.applicationContext.getString(res);
}
+ if (value == null) {
+ value = "LOC_ERR:" + key;
+ }
return value;
}
@@ -638,6 +656,9 @@ public class LocaleController {
}
currentLocale = newLocale;
currentPluralRules = allRules.get(currentLocale.getLanguage());
+ if (currentPluralRules == null) {
+ currentPluralRules = allRules.get("en");
+ }
}
}
}
@@ -695,6 +716,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 +741,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) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
index efa53b09..0207db4e 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
@@ -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";
@@ -1696,10 +1698,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
FileLog.e("tmessages", e);
result = false;
} finally {
- if(source != null) {
+ if (source != null) {
source.close();
}
- if(destination != null) {
+ if (destination != null) {
destination.close();
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
index 1c6c0dd4..afc8fee5 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
@@ -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;
@@ -71,6 +72,12 @@ public class MessageObject {
textPaint.linkColor = 0xff316f9f;
}
+ int color = AndroidUtilities.getIntDef("chatRTextColor", 0xff000000);
+ textPaint.setColor(color);
+ if(color != 0xff000000){
+ textPaint.linkColor = AndroidUtilities.getIntDarkerColor("chatRTextColor", -0x50);
+ }
+
textPaint.setTextSize(AndroidUtilities.dp(MessagesController.getInstance().fontSize));
messageOwner = message;
@@ -199,7 +206,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 +353,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 +566,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 +591,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 +623,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 +632,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 +665,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 +677,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 +706,7 @@ public class MessageObject {
}
public void setIsRead() {
- messageOwner.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
+ messageOwner.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
public boolean isSecretPhoto() {
@@ -714,7 +724,7 @@ public class MessageObject {
if (unread) {
message.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
} else {
- message.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
+ message.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
index 71bd216e..a7c97325 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
@@ -9,10 +9,12 @@
package org.telegram.android;
import android.app.Activity;
+import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.text.Html;
+import android.util.Base64;
import android.util.SparseArray;
import org.telegram.messenger.ConnectionsManager;
@@ -20,11 +22,14 @@ import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
+import org.telegram.messenger.SerializedData;
+import org.telegram.messenger.TLClassStore;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.ApplicationLoader;
+import org.telegram.ui.ActionBar.BaseFragment;
import java.util.ArrayList;
import java.util.Collections;
@@ -86,6 +91,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public int fontSize = AndroidUtilities.dp(16);
public int maxGroupCount = 200;
public int maxBroadcastCount = 100;
+ public int groupBigSize;
+ private ArrayList disabledFeatures = new ArrayList<>();
private class UserActionUpdates extends TLRPC.Updates {
@@ -102,6 +109,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 {
@@ -138,7 +147,26 @@ public class MessagesController implements NotificationCenter.NotificationCenter
preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
maxGroupCount = preferences.getInt("maxGroupCount", 200);
maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100);
+ groupBigSize = preferences.getInt("groupBigSize", 10);
fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
+ String disabledFeaturesString = preferences.getString("disabledFeatures", null);
+ if (disabledFeaturesString != null && disabledFeaturesString.length() != 0) {
+ try {
+ byte[] bytes = Base64.decode(disabledFeaturesString, Base64.DEFAULT);
+ if (bytes != null) {
+ SerializedData data = new SerializedData(bytes);
+ int count = data.readInt32();
+ for (int a = 0; a < count; a++) {
+ TLRPC.TL_disabledFeature feature = (TLRPC.TL_disabledFeature) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
+ if (feature != null && feature.feature != null && feature.description != null) {
+ disabledFeatures.add(feature);
+ }
+ }
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
}
public void updateConfig(final TLRPC.TL_config config) {
@@ -147,15 +175,52 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void run() {
maxBroadcastCount = config.broadcast_size_max;
maxGroupCount = config.chat_size_max;
+ groupBigSize = config.chat_big_size;
+ disabledFeatures = config.disabled_features;
+
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("maxGroupCount", maxGroupCount);
editor.putInt("maxBroadcastCount", maxBroadcastCount);
+ editor.putInt("groupBigSize", groupBigSize);
+ try {
+ SerializedData data = new SerializedData();
+ data.writeInt32(disabledFeatures.size());
+ for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) {
+ disabledFeature.serializeToStream(data);
+ }
+ String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
+ if (string != null && string.length() != 0) {
+ editor.putString("disabledFeatures", string);
+ }
+ } catch (Exception e) {
+ editor.remove("disabledFeatures");
+ FileLog.e("tmessages", e);
+ }
editor.commit();
}
});
}
+ public static boolean isFeatureEnabled(String feature, BaseFragment fragment) {
+ if (feature == null || feature.length() == 0 || getInstance().disabledFeatures.isEmpty() || fragment == null) {
+ return true;
+ }
+ for (TLRPC.TL_disabledFeature disabledFeature : getInstance().disabledFeatures) {
+ if (disabledFeature.feature.equals(feature)) {
+ if (fragment.getParentActivity() != null) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
+ builder.setTitle("Oops!");
+ builder.setPositiveButton(R.string.OK, null);
+ builder.setMessage(disabledFeature.description);
+ fragment.showAlertDialog(builder);
+ }
+ return false;
+ }
+ }
+ return true;
+ }
+
public void addSupportUser() {
TLRPC.TL_userForeign user = new TLRPC.TL_userForeign();
user.phone = "333";
@@ -863,6 +928,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 +1010,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 +1025,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 +1043,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 +1502,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 +1598,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 +1619,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 +1778,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 +1933,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 +1971,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 +2018,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 +2100,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 +2919,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 +2933,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return true;
}
}
- }
+ //}
return false;
}
@@ -3577,4 +3645,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
}
+
+
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
index 87f0e198..160447de 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
@@ -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 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 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 usersToLoad = new ArrayList<>();
ArrayList chatsToLoad = new ArrayList<>();
ArrayList 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 chatsToLoad = new ArrayList<>();
ArrayList 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);
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
index eecbbb17..17e55ea2 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
@@ -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";
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
index 6e045c32..5ae1cae0 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
@@ -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++;
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
index c0cc5d4f..cef1faa8 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
@@ -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 pushMessages = new ArrayList<>();
private HashMap 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,6 +419,9 @@ public class NotificationsController {
intent.putExtra("userId", user_id);
}
}
+ 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) {
@@ -427,6 +433,7 @@ public class NotificationsController {
}
}
}
+ }
} else {
if (pushDialogs.size() == 1) {
intent.putExtra("encId", (int) (dialog_id >> 32));
@@ -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)
@@ -462,7 +469,8 @@ public class NotificationsController {
.setContentIntent(contentIntent)
.setGroup("messages")
.setGroupSummary(true)
- .setColor(0xff2ca5e0);
+ //.setColor(0xff2ca5e0);
+ .setColor(AndroidUtilities.getIntColor("themeColor"));
if (priority == 0) {
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
@@ -834,7 +842,7 @@ public class NotificationsController {
notifyCheck = isLast;
}
- if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) {
+ if (!popupMessages.isEmpty() && oldCount != popupMessages.size() && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) {
if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
MessageObject messageObject = messageObjects.get(0);
if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) {
@@ -988,7 +996,18 @@ public class NotificationsController {
setBadge(ApplicationLoader.applicationContext, enabled ? total_unread_count : 0);
}
- private void setBadge(Context context, int count) {
+ 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) {
@@ -1003,6 +1022,8 @@ public class NotificationsController {
FileLog.e("tmessages", e);
}
}
+ });
+ }
public static String getLauncherClassName(Context context) {
try {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
index e6b6c757..d7824f18 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
@@ -28,5 +28,6 @@ public class ScreenReceiver extends BroadcastReceiver {
ConnectionsManager.getInstance().setAppPaused(false, true);
ApplicationLoader.isScreenOn = true;
}
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenStateChanged);
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
index 6a114024..e9d672fc 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
@@ -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;
@@ -1777,6 +1777,10 @@ public class SecretChatHelper {
}
}
});
- progressDialog.show();
+ try {
+ progressDialog.show();
+ } catch (Exception e) {
+ //don't promt
+ }
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
index b7dc050d..4cb3e851 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
@@ -481,6 +481,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null);
}
+ public void sendMessage(ArrayList messages) {
+
+ }
+
public void sendMessage(MessageObject message) {
sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath);
}
@@ -1610,6 +1614,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
try {
Bitmap bitmap = ImageLoader.loadBitmap(f.getAbsolutePath(), null, 90, 90, true);
if (bitmap != null) {
+ fileName.file_name = "animation.gif";
document.thumb = ImageLoader.scaleAndSaveImage(bitmap, 90, 90, 55, isEncrypted);
}
} catch (Exception e) {
@@ -1744,7 +1749,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
document.id = 0;
document.date = ConnectionsManager.getInstance().getCurrentTime();
TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename();
- fileName.file_name = md5;
+ fileName.file_name = "animation.gif";
document.attributes.add(fileName);
document.size = searchImage.size;
document.dc_id = 0;
@@ -1940,112 +1945,116 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
new Thread(new Runnable() {
@Override
public void run() {
+
boolean isEncrypted = (int)dialog_id == 0;
- String path = videoPath;
- String originalPath = videoPath;
- File temp = new File(originalPath);
- originalPath += temp.length() + "_" + temp.lastModified();
- if (videoEditedInfo != null) {
- originalPath += duration + "_" + videoEditedInfo.startTime + "_" + videoEditedInfo.endTime;
- }
- TLRPC.TL_video video = null;
- if (!isEncrypted) {
- video = (TLRPC.TL_video) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 2 : 5);
- }
- if (video == null) {
- Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
- TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(thumb, 90, 90, 55, isEncrypted);
- video = new TLRPC.TL_video();
- video.thumb = size;
- if (video.thumb == null) {
- video.thumb = new TLRPC.TL_photoSizeEmpty();
- video.thumb.type = "s";
- } else {
- video.thumb.type = "s";
- }
- video.caption = "";
- video.mime_type = "video/mp4";
- video.id = 0;
- UserConfig.saveConfig(false);
-
+ if (videoEditedInfo != null || videoPath.endsWith("mp4")) {
+ String path = videoPath;
+ String originalPath = videoPath;
+ File temp = new File(originalPath);
+ originalPath += temp.length() + "_" + temp.lastModified();
if (videoEditedInfo != null) {
- video.duration = (int)(duration / 1000);
- if (videoEditedInfo.rotationValue == 90 || videoEditedInfo.rotationValue == 270) {
- video.w = height;
- video.h = width;
+ originalPath += duration + "_" + videoEditedInfo.startTime + "_" + videoEditedInfo.endTime;
+ }
+ TLRPC.TL_video video = null;
+ if (!isEncrypted) {
+ video = (TLRPC.TL_video) MessagesStorage.getInstance().getSentFile(originalPath, !isEncrypted ? 2 : 5);
+ }
+ if (video == null) {
+ Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
+ TLRPC.PhotoSize size = ImageLoader.scaleAndSaveImage(thumb, 90, 90, 55, isEncrypted);
+ video = new TLRPC.TL_video();
+ video.thumb = size;
+ if (video.thumb == null) {
+ video.thumb = new TLRPC.TL_photoSizeEmpty();
+ video.thumb.type = "s";
} else {
- video.w = width;
- video.h = height;
+ video.thumb.type = "s";
}
- video.size = (int)estimatedSize;
- video.videoEditedInfo = videoEditedInfo;
- String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
- UserConfig.lastLocalId--;
- File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
+ video.caption = "";
+ video.mime_type = "video/mp4";
+ video.id = 0;
UserConfig.saveConfig(false);
- path = cacheFile.getAbsolutePath();
- } else {
- if (temp != null && temp.exists()) {
- video.size = (int) temp.length();
- }
- boolean infoObtained = false;
- if (Build.VERSION.SDK_INT >= 14) {
- MediaMetadataRetriever mediaMetadataRetriever = null;
- try {
- mediaMetadataRetriever = new MediaMetadataRetriever();
- mediaMetadataRetriever.setDataSource(videoPath);
- String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
- if (width != null) {
- video.w = Integer.parseInt(width);
- }
- String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
- if (height != null) {
- video.h = Integer.parseInt(height);
- }
- String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
- if (duration != null) {
- video.duration = (int) Math.ceil(Long.parseLong(duration) / 1000.0f);
- }
- infoObtained = true;
- } catch (Exception e) {
- FileLog.e("tmessages", e);
- } finally {
+
+ if (videoEditedInfo != null) {
+ video.duration = (int) (duration / 1000);
+ if (videoEditedInfo.rotationValue == 90 || videoEditedInfo.rotationValue == 270) {
+ video.w = height;
+ video.h = width;
+ } else {
+ video.w = width;
+ video.h = height;
+ }
+ video.size = (int) estimatedSize;
+ video.videoEditedInfo = videoEditedInfo;
+ String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
+ UserConfig.lastLocalId--;
+ File cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
+ UserConfig.saveConfig(false);
+ path = cacheFile.getAbsolutePath();
+ } else {
+ if (temp != null && temp.exists()) {
+ video.size = (int) temp.length();
+ }
+ boolean infoObtained = false;
+ if (Build.VERSION.SDK_INT >= 14) {
+ MediaMetadataRetriever mediaMetadataRetriever = null;
try {
- if (mediaMetadataRetriever != null) {
- mediaMetadataRetriever.release();
- mediaMetadataRetriever = null;
+ mediaMetadataRetriever = new MediaMetadataRetriever();
+ mediaMetadataRetriever.setDataSource(videoPath);
+ String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
+ if (width != null) {
+ video.w = Integer.parseInt(width);
+ }
+ String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
+ if (height != null) {
+ video.h = Integer.parseInt(height);
+ }
+ String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
+ if (duration != null) {
+ video.duration = (int) Math.ceil(Long.parseLong(duration) / 1000.0f);
+ }
+ infoObtained = true;
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ } finally {
+ try {
+ if (mediaMetadataRetriever != null) {
+ mediaMetadataRetriever.release();
+ mediaMetadataRetriever = null;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+ }
+ if (!infoObtained) {
+ try {
+ MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(videoPath)));
+ if (mp != null) {
+ video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
+ video.w = mp.getVideoWidth();
+ video.h = mp.getVideoHeight();
+ mp.release();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
- if (!infoObtained) {
- try {
- MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(videoPath)));
- if (mp != null) {
- video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
- video.w = mp.getVideoWidth();
- video.h = mp.getVideoHeight();
- mp.release();
- }
- } catch (Exception e) {
- FileLog.e("tmessages", e);
- }
+ }
+ final TLRPC.TL_video videoFinal = video;
+ final String originalPathFinal = originalPath;
+ final String finalPath = path;
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ SendMessagesHelper.getInstance().sendMessage(videoFinal, originalPathFinal, finalPath, dialog_id);
}
- }
+ });
+ } else {
+ prepareSendingDocumentInternal(videoPath, videoPath, null, null, dialog_id);
}
-
- final TLRPC.TL_video videoFinal = video;
- final String originalPathFinal = originalPath;
- final String finalPath = path;
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- SendMessagesHelper.getInstance().sendMessage(videoFinal, originalPathFinal, finalPath, dialog_id);
- }
- });
}
}).start();
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/video/MP4Builder.java b/TMessagesProj/src/main/java/org/telegram/android/video/MP4Builder.java
index 9d9eca96..cdb69332 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/video/MP4Builder.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/video/MP4Builder.java
@@ -59,7 +59,7 @@ public class MP4Builder {
private long dataOffset = 0;
private long writedSinceLastMdat = 0;
private boolean writeNewMdat = true;
- private HashMap