Commit 2cb6bb3e authored by DrKLO's avatar DrKLO

Merge branch 'dev'

parents d1c9175b d728d9c4
...@@ -81,7 +81,7 @@ android { ...@@ -81,7 +81,7 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 8 minSdkVersion 8
targetSdkVersion 19 targetSdkVersion 19
versionCode 250 versionCode 267
versionName "1.5.0" versionName "1.5.7"
} }
} }
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := tmessages LOCAL_MODULE := tmessages
LOCAL_CFLAGS := -w -std=gnu99 -O3 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 LOCAL_CFLAGS := -w -std=gnu99 -O2 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 -DLOG_DISABLED
LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -fno-math-errno 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 LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT
LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O3 -funroll-loops LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O2 -funroll-loops
LOCAL_LDLIBS := -llog -lm -ljnigraphics #LOCAL_LDLIBS := -llog
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
./opus/src/opus.c \ ./opus/src/opus.c \
......
#include <jni.h> #include <jni.h>
#include <stdio.h> #include <stdio.h>
#include <setjmp.h> #include <setjmp.h>
#include <android/bitmap.h>
#include <libjpeg/jpeglib.h> #include <libjpeg/jpeglib.h>
#include "utils.h" #include "utils.h"
...@@ -17,12 +16,10 @@ METHODDEF(void) my_error_exit(j_common_ptr cinfo) { ...@@ -17,12 +16,10 @@ METHODDEF(void) my_error_exit(j_common_ptr cinfo) {
longjmp(myerr->setjmp_buffer, 1); longjmp(myerr->setjmp_buffer, 1);
} }
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jobject bitmap, int scale) { JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jintArray bitmap, int scale, int format, int width, int height) {
AndroidBitmapInfo info;
int i; int i;
if ((i = AndroidBitmap_getInfo(env, bitmap, &info)) >= 0) {
char *fileName = (*env)->GetStringUTFChars(env, path, NULL); char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
FILE *infile; FILE *infile;
...@@ -34,6 +31,8 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl ...@@ -34,6 +31,8 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl
jerr.pub.error_exit = my_error_exit; jerr.pub.error_exit = my_error_exit;
if (!setjmp(jerr.setjmp_buffer)) { if (!setjmp(jerr.setjmp_buffer)) {
unsigned char *bitmapBuf = (*env)->GetPrimitiveArrayCritical(env, bitmap, 0);
if (bitmapBuf) {
jpeg_create_decompress(&cinfo); jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile); jpeg_stdio_src(&cinfo, infile);
...@@ -45,17 +44,22 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl ...@@ -45,17 +44,22 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl
jpeg_start_decompress(&cinfo); jpeg_start_decompress(&cinfo);
int row_stride = cinfo.output_width * cinfo.output_components; int row_stride = cinfo.output_width * cinfo.output_components;
JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
int stride = width;
if (format == 0) {
stride *= 4;
} else if (format == 1) {
stride *= 2;
}
unsigned char *pixels; unsigned char *pixels = bitmapBuf;
if ((i = AndroidBitmap_lockPixels(env, bitmap, &pixels)) >= 0) {
int rowCount = min(cinfo.output_height, info.height); int rowCount = min(cinfo.output_height, height);
int colCount = min(cinfo.output_width, info.width); int colCount = min(cinfo.output_width, width);
while (cinfo.output_scanline < rowCount) { while (cinfo.output_scanline < rowCount) {
jpeg_read_scanlines(&cinfo, buffer, 1); jpeg_read_scanlines(&cinfo, buffer, 1);
if (info.format == ANDROID_BITMAP_FORMAT_RGBA_8888) { if (format == 0) {
if (cinfo.out_color_space == JCS_GRAYSCALE) { if (cinfo.out_color_space == JCS_GRAYSCALE) {
for (i = 0; i < colCount; i++) { for (i = 0; i < colCount; i++) {
float alpha = buffer[0][i] / 255.0f; float alpha = buffer[0][i] / 255.0f;
...@@ -67,26 +71,24 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl ...@@ -67,26 +71,24 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl
} else { } else {
int c = 0; int c = 0;
for (i = 0; i < colCount; i++) { for (i = 0; i < colCount; i++) {
pixels[i * 4] = buffer[0][i * 3]; pixels[i * 4] = buffer[0][i * 3 + 2];
pixels[i * 4 + 1] = buffer[0][i * 3 + 1]; pixels[i * 4 + 1] = buffer[0][i * 3 + 1];
pixels[i * 4 + 2] = buffer[0][i * 3 + 2]; pixels[i * 4 + 2] = buffer[0][i * 3];
pixels[i * 4 + 3] = 255; pixels[i * 4 + 3] = 255;
c += 4; c += 4;
} }
} }
} else if (info.format == ANDROID_BITMAP_FORMAT_RGB_565) { } else if (format == 1) {
} }
pixels += info.stride; pixels += stride;
} }
(*env)->ReleasePrimitiveArrayCritical(env, bitmap, bitmapBuf, 0);
AndroidBitmap_unlockPixels(env, bitmap); jpeg_finish_decompress(&cinfo);
} else { } else {
throwException(env, "AndroidBitmap_lockPixels() failed ! error=%d", i); throwException(env, "can't get bitmap buff");
} }
jpeg_finish_decompress(&cinfo);
} else { } else {
throwException(env, "the JPEG code has signaled an error"); throwException(env, "the JPEG code has signaled an error");
} }
...@@ -94,11 +96,8 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl ...@@ -94,11 +96,8 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jcl
jpeg_destroy_decompress(&cinfo); jpeg_destroy_decompress(&cinfo);
fclose(infile); fclose(infile);
} else { } else {
throwException(env, "can't open %s\n", fileName); throwException(env, "can't open %s", fileName);
} }
(*env)->ReleaseStringUTFChars(env, path, fileName); (*env)->ReleaseStringUTFChars(env, path, fileName);
} else {
throwException(env, "AndroidBitmap_getInfo() failed ! error=%d", i);
}
} }
...@@ -5,10 +5,17 @@ ...@@ -5,10 +5,17 @@
#include <jni.h> #include <jni.h>
#define LOG_TAG "tmessages_native" #define LOG_TAG "tmessages_native"
#ifndef LOG_DISABLED
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGV(...)
#endif
#ifndef max #ifndef max
#define max(x, y) ((x) > (y)) ? (x) : (y) #define max(x, y) ((x) > (y)) ? (x) : (y)
......
...@@ -17,7 +17,7 @@ import java.util.Map; ...@@ -17,7 +17,7 @@ import java.util.Map;
public class SQLiteDatabase { public class SQLiteDatabase {
private final int sqliteHandle; private final int sqliteHandle;
private final Map<String, SQLitePreparedStatement> preparedMap; private final Map<String, SQLitePreparedStatement> preparedMap = new HashMap<String, SQLitePreparedStatement>();
private boolean isOpen = false; private boolean isOpen = false;
private boolean inTransaction = false; private boolean inTransaction = false;
...@@ -28,7 +28,6 @@ public class SQLiteDatabase { ...@@ -28,7 +28,6 @@ public class SQLiteDatabase {
public SQLiteDatabase(String fileName) throws SQLiteException { public SQLiteDatabase(String fileName) throws SQLiteException {
sqliteHandle = opendb(fileName, ApplicationLoader.applicationContext.getFilesDir().getPath()); sqliteHandle = opendb(fileName, ApplicationLoader.applicationContext.getFilesDir().getPath());
isOpen = true; isOpen = true;
preparedMap = new HashMap<String, SQLitePreparedStatement>();
} }
public boolean tableExists(String tableName) throws SQLiteException { public boolean tableExists(String tableName) throws SQLiteException {
...@@ -47,7 +46,7 @@ public class SQLiteDatabase { ...@@ -47,7 +46,7 @@ public class SQLiteDatabase {
} }
} }
public SQLitePreparedStatement executeFast(String sql) throws SQLiteException{ public SQLitePreparedStatement executeFast(String sql) throws SQLiteException {
return new SQLitePreparedStatement(this, sql, true); return new SQLitePreparedStatement(this, sql, true);
} }
...@@ -64,29 +63,6 @@ public class SQLiteDatabase { ...@@ -64,29 +63,6 @@ public class SQLiteDatabase {
} }
} }
public int executeIntOrThrow(String sql, Object... args) throws SQLiteException, SQLiteNoRowException {
checkOpened();
Integer val = executeInt(sql, args);
if (val != null) {
return val;
}
throw new SQLiteNoRowException();
}
public String executeString(String sql, Object... args) throws SQLiteException {
checkOpened();
SQLiteCursor cursor = query(sql, args);
try {
if (!cursor.next()) {
return null;
}
return cursor.stringValue(0);
} finally {
cursor.dispose();
}
}
public SQLiteCursor query(String sql, Object... args) throws SQLiteException { public SQLiteCursor query(String sql, Object... args) throws SQLiteException {
checkOpened(); checkOpened();
SQLitePreparedStatement stmt = preparedMap.get(sql); SQLitePreparedStatement stmt = preparedMap.get(sql);
...@@ -110,6 +86,7 @@ public class SQLiteDatabase { ...@@ -110,6 +86,7 @@ public class SQLiteDatabase {
for (SQLitePreparedStatement stmt : preparedMap.values()) { for (SQLitePreparedStatement stmt : preparedMap.values()) {
stmt.finalizeQuery(); stmt.finalizeQuery();
} }
commitTransaction();
closedb(sqliteHandle); closedb(sqliteHandle);
} catch (SQLiteException e) { } catch (SQLiteException e) {
FileLog.e("tmessages", e.getMessage(), e); FileLog.e("tmessages", e.getMessage(), e);
...@@ -139,6 +116,9 @@ public class SQLiteDatabase { ...@@ -139,6 +116,9 @@ public class SQLiteDatabase {
} }
public void commitTransaction() { public void commitTransaction() {
if (!inTransaction) {
return;
}
inTransaction = false; inTransaction = false;
commitTransaction(sqliteHandle); commitTransaction(sqliteHandle);
} }
......
...@@ -17,6 +17,7 @@ public class BuffersStorage { ...@@ -17,6 +17,7 @@ public class BuffersStorage {
private final ArrayList<ByteBufferDesc> freeBuffers4096; private final ArrayList<ByteBufferDesc> freeBuffers4096;
private final ArrayList<ByteBufferDesc> freeBuffers16384; private final ArrayList<ByteBufferDesc> freeBuffers16384;
private final ArrayList<ByteBufferDesc> freeBuffers32768; private final ArrayList<ByteBufferDesc> freeBuffers32768;
private final ArrayList<ByteBufferDesc> freeBuffersBig;
private static volatile BuffersStorage Instance = null; private static volatile BuffersStorage Instance = null;
public static BuffersStorage getInstance() { public static BuffersStorage getInstance() {
...@@ -38,6 +39,7 @@ public class BuffersStorage { ...@@ -38,6 +39,7 @@ public class BuffersStorage {
freeBuffers4096 = new ArrayList<ByteBufferDesc>(); freeBuffers4096 = new ArrayList<ByteBufferDesc>();
freeBuffers16384 = new ArrayList<ByteBufferDesc>(); freeBuffers16384 = new ArrayList<ByteBufferDesc>();
freeBuffers32768 = new ArrayList<ByteBufferDesc>(); freeBuffers32768 = new ArrayList<ByteBufferDesc>();
freeBuffersBig = new ArrayList<ByteBufferDesc>();
for (int a = 0; a < 5; a++) { for (int a = 0; a < 5; a++) {
freeBuffers128.add(new ByteBufferDesc(128)); freeBuffers128.add(new ByteBufferDesc(128));
...@@ -113,6 +115,17 @@ public class BuffersStorage { ...@@ -113,6 +115,17 @@ public class BuffersStorage {
buffer = new ByteBufferDesc(40000); buffer = new ByteBufferDesc(40000);
FileLog.e("tmessages", "create new 40000 buffer"); FileLog.e("tmessages", "create new 40000 buffer");
} }
} else if (size <= 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() > 0) {
buffer = freeBuffersBig.get(0);
freeBuffersBig.remove(0);
}
}
if (buffer == null) {
buffer = new ByteBufferDesc(280000);
FileLog.e("tmessages", "create new big buffer");
}
} else { } else {
buffer = new ByteBufferDesc(size); buffer = new ByteBufferDesc(size);
} }
...@@ -126,24 +139,40 @@ public class BuffersStorage { ...@@ -126,24 +139,40 @@ public class BuffersStorage {
} }
if (buffer.buffer.capacity() == 128) { if (buffer.buffer.capacity() == 128) {
synchronized (freeBuffers128) { synchronized (freeBuffers128) {
if (freeBuffers128.size() < 10) {
freeBuffers128.add(buffer); freeBuffers128.add(buffer);
} }
}
} else if (buffer.buffer.capacity() == 1024 + 200) { } else if (buffer.buffer.capacity() == 1024 + 200) {
synchronized (freeBuffers1024) { synchronized (freeBuffers1024) {
if (freeBuffers1024.size() < 10) {
freeBuffers1024.add(buffer); freeBuffers1024.add(buffer);
} }
}
} else if (buffer.buffer.capacity() == 4096 + 200) { } else if (buffer.buffer.capacity() == 4096 + 200) {
synchronized (freeBuffers4096) { synchronized (freeBuffers4096) {
if (freeBuffers4096.size() < 10) {
freeBuffers4096.add(buffer); freeBuffers4096.add(buffer);
} }
}
} else if (buffer.buffer.capacity() == 16384 + 200) { } else if (buffer.buffer.capacity() == 16384 + 200) {
synchronized (freeBuffers16384) { synchronized (freeBuffers16384) {
if (freeBuffers16384.size() < 10) {
freeBuffers16384.add(buffer); freeBuffers16384.add(buffer);
} }
}
} else if (buffer.buffer.capacity() == 40000) { } else if (buffer.buffer.capacity() == 40000) {
synchronized (freeBuffers32768) { synchronized (freeBuffers32768) {
if (freeBuffers32768.size() < 10) {
freeBuffers32768.add(buffer); freeBuffers32768.add(buffer);
} }
} }
} else if (buffer.buffer.capacity() == 280000) {
synchronized (freeBuffersBig) {
if (freeBuffersBig.size() < 4) {
freeBuffersBig.add(buffer);
}
}
}
} }
} }
...@@ -35,8 +35,8 @@ public class Datacenter { ...@@ -35,8 +35,8 @@ public class Datacenter {
private volatile int currentAddressNum = 0; private volatile int currentAddressNum = 0;
public TcpConnection connection; public TcpConnection connection;
public TcpConnection downloadConnection; private ArrayList<TcpConnection> downloadConnections = new ArrayList<TcpConnection>();
public TcpConnection uploadConnection; private TcpConnection uploadConnection;
public TcpConnection pushConnection; public TcpConnection pushConnection;
private ArrayList<ServerSalt> authServerSaltSet = new ArrayList<ServerSalt>(); private ArrayList<ServerSalt> authServerSaltSet = new ArrayList<ServerSalt>();
...@@ -319,4 +319,81 @@ public class Datacenter { ...@@ -319,4 +319,81 @@ public class Datacenter {
} }
return false; return false;
} }
public void suspendConnections() {
if (connection != null) {
connection.suspendConnection(true);
}
if (uploadConnection != null) {
uploadConnection.suspendConnection(true);
}
for (TcpConnection downloadConnection : downloadConnections) {
downloadConnection.suspendConnection(true);
}
}
public void getSessions(ArrayList<Long> sessions) {
if (connection != null) {
sessions.add(connection.getSissionId());
}
if (uploadConnection != null) {
sessions.add(uploadConnection.getSissionId());
}
for (TcpConnection downloadConnection : downloadConnections) {
sessions.add(downloadConnection.getSissionId());
}
}
public void recreateSessions() {
if (connection != null) {
connection.recreateSession();
}
if (uploadConnection != null) {
uploadConnection.recreateSession();
}
for (TcpConnection downloadConnection : downloadConnections) {
downloadConnection.recreateSession();
}
}
public TcpConnection getDownloadConnection(int num, TcpConnection.TcpConnectionDelegate delegate) {
if (num >= 0 && authKey != null) {
TcpConnection downloadConnection = null;
if (num < downloadConnections.size()) {
downloadConnection = downloadConnections.get(num);
} else {
downloadConnection = new TcpConnection(datacenterId);
downloadConnection.delegate = delegate;
downloadConnection.transportRequestClass = RPCRequest.RPCRequestClassDownloadMedia;
downloadConnections.add(downloadConnection);
}
downloadConnection.connect();
return downloadConnection;
}
return null;
}
public TcpConnection getUploadConnection(TcpConnection.TcpConnectionDelegate delegate) {
if (authKey != null) {
if (uploadConnection == null) {
uploadConnection = new TcpConnection(datacenterId);
uploadConnection.delegate = delegate;
uploadConnection.transportRequestClass = RPCRequest.RPCRequestClassUploadMedia;
}
uploadConnection.connect();
}
return uploadConnection;
}
public TcpConnection getGenericConnection(TcpConnection.TcpConnectionDelegate delegate) {
if (authKey != null) {
if (connection == null) {
connection = new TcpConnection(datacenterId);
connection.delegate = delegate;
connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric;
}
connection.connect();
}
return connection;
}
} }
...@@ -11,7 +11,6 @@ package org.telegram.messenger; ...@@ -11,7 +11,6 @@ package org.telegram.messenger;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.os.Message; import android.os.Message;
import android.util.Log;
public class DispatchQueue extends Thread { public class DispatchQueue extends Thread {
public volatile Handler handler = null; public volatile Handler handler = null;
...@@ -68,6 +67,12 @@ public class DispatchQueue extends Thread { ...@@ -68,6 +67,12 @@ public class DispatchQueue extends Thread {
} }
} }
public void cleanupQueue() {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
}
public void run() { public void run() {
Looper.prepare(); Looper.prepare();
synchronized (handlerSyncObject) { synchronized (handlerSyncObject) {
......
...@@ -13,7 +13,6 @@ import java.io.InputStream; ...@@ -13,7 +13,6 @@ import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.ColorFilter; import android.graphics.ColorFilter;
...@@ -34,8 +33,21 @@ public class Emoji { ...@@ -34,8 +33,21 @@ public class Emoji {
private static int drawImgSize, bigImgSize; private static int drawImgSize, bigImgSize;
private static boolean inited = false; private static boolean inited = false;
private static Paint placeholderPaint; private static Paint placeholderPaint;
private static Bitmap emojiBmp[] = new Bitmap[5]; private static EmojiBitmap emojiBmp[] = new EmojiBitmap[5];
private static boolean loadingEmoji[] = new boolean[5]; private static boolean loadingEmoji[] = new boolean[5];
private static int emojiFullSize;
private static class EmojiBitmap {
public int[] colors;
public int width;
public int height;
public EmojiBitmap(int[] colors, int width, int height) {
this.colors = colors;
this.width = width;
this.height = height;
}
}
private static final int[] cols = { private static final int[] cols = {
13, 10, 15, 10, 14 13, 10, 15, 10, 14
...@@ -190,22 +202,21 @@ public class Emoji { ...@@ -190,22 +202,21 @@ public class Emoji {
0x00000000D83DDD34L, 0x00000000D83DDD35L, 0x00000000D83DDD3BL, 0x00000000D83DDD36L, 0x00000000D83DDD37L, 0x00000000D83DDD38L, 0x00000000D83DDD39L}}; 0x00000000D83DDD34L, 0x00000000D83DDD35L, 0x00000000D83DDD3BL, 0x00000000D83DDD36L, 0x00000000D83DDD37L, 0x00000000D83DDD38L, 0x00000000D83DDD39L}};
static { static {
int imgSize = 30;
if (Utilities.density <= 1.0f) { if (Utilities.density <= 1.0f) {
imgSize = 30; emojiFullSize = 30;
} else if (Utilities.density <= 1.5f) { } else if (Utilities.density <= 1.5f) {
imgSize = 45; emojiFullSize = 45;
} else if (Utilities.density <= 2.0f) { } else if (Utilities.density <= 2.0f) {
imgSize = 60; emojiFullSize = 60;
} else { } else {
imgSize = 90; emojiFullSize = 90;
} }
drawImgSize = Utilities.dp(20); drawImgSize = Utilities.dp(20);
bigImgSize = Utilities.dp(30); bigImgSize = Utilities.dp(30);
for (int j = 1; j < data.length; j++) { for (int j = 1; j < data.length; j++) {
for (int i = 0; i < data[j].length; i++) { for (int i = 0; i < data[j].length; i++) {
Rect rect = new Rect((i % cols[j - 1]) * imgSize, (i / cols[j - 1]) * imgSize, (i % cols[j - 1] + 1) * imgSize, (i / cols[j - 1] + 1) * imgSize); Rect rect = new Rect((i % cols[j - 1]) * emojiFullSize, (i / cols[j - 1]) * emojiFullSize, emojiFullSize, emojiFullSize);
rects.put(data[j][i], new DrawableInfo(rect, (byte)(j - 1))); rects.put(data[j][i], new DrawableInfo(rect, (byte)(j - 1)));
} }
} }
...@@ -213,7 +224,7 @@ public class Emoji { ...@@ -213,7 +224,7 @@ public class Emoji {
placeholderPaint.setColor(0x00000000); placeholderPaint.setColor(0x00000000);
} }
private static Bitmap loadEmoji(final int page) { private static void loadEmoji(final int page) {
try { try {
float scale = 1.0f; float scale = 1.0f;
int imageResize = 1; int imageResize = 1;
...@@ -241,8 +252,10 @@ public class Emoji { ...@@ -241,8 +252,10 @@ public class Emoji {
opts.inJustDecodeBounds = true; opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFile.getAbsolutePath(), opts); BitmapFactory.decodeFile(imageFile.getAbsolutePath(), opts);
final Bitmap colorsBitmap = Bitmap.createBitmap(opts.outWidth / imageResize, opts.outHeight / imageResize, Bitmap.Config.ARGB_8888); int width = opts.outWidth / imageResize;
Utilities.loadBitmap(imageFile.getAbsolutePath(), colorsBitmap, imageResize); int height = opts.outHeight / imageResize;
int[] bitmap = new int[width * height];
Utilities.loadBitmap(imageFile.getAbsolutePath(), bitmap, imageResize, 0, width, height);
imageName = String.format(Locale.US, "emoji%.01fx_a_%d.jpg", scale, page); imageName = String.format(Locale.US, "emoji%.01fx_a_%d.jpg", scale, page);
imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName); imageFile = ApplicationLoader.applicationContext.getFileStreamPath(imageName);
...@@ -252,21 +265,19 @@ public class Emoji { ...@@ -252,21 +265,19 @@ public class Emoji {
is.close(); is.close();
} }
Utilities.loadBitmap(imageFile.getAbsolutePath(), colorsBitmap, imageResize); Utilities.loadBitmap(imageFile.getAbsolutePath(), bitmap, imageResize, 0, width, height);
final EmojiBitmap emojiBitmap = new EmojiBitmap(bitmap, width, height);
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
emojiBmp[page] = colorsBitmap; emojiBmp[page] = emojiBitmap;
NotificationCenter.getInstance().postNotificationName(999); NotificationCenter.getInstance().postNotificationName(999);
} }
}); });
return colorsBitmap;
} catch(Throwable x) { } catch(Throwable x) {
FileLog.e("tmessages", "Error loading emoji", x); FileLog.e("tmessages", "Error loading emoji", x);
} }
return null;
} }
private static void loadEmojiAsync(final int page) { private static void loadEmojiAsync(final int page) {
...@@ -330,20 +341,25 @@ public class Emoji { ...@@ -330,20 +341,25 @@ public class Emoji {
@Override @Override
public void draw(Canvas canvas) { public void draw(Canvas canvas) {
if (emojiBmp[info.page] == null) { EmojiBitmap bitmap = emojiBmp[info.page];
if (bitmap == null) {
loadEmojiAsync(info.page); loadEmojiAsync(info.page);
canvas.drawRect(getBounds(), placeholderPaint); canvas.drawRect(getBounds(), placeholderPaint);
return; return;
} }
Rect b = copyBounds(); float scale = 1;
int cX = b.centerX(), cY = b.centerY(); int offset = 0;
b.left = cX - (fullSize ? bigImgSize : drawImgSize) / 2; if (fullSize) {
b.right = cX + (fullSize ? bigImgSize : drawImgSize) / 2; scale = (float) bigImgSize / (float) emojiFullSize;
b.top = cY - (fullSize ? bigImgSize : drawImgSize) / 2; offset = (getBounds().width() - bigImgSize) / 2;
b.bottom = cY + (fullSize ? bigImgSize : drawImgSize) / 2; } else {
if (!canvas.quickReject(b.left, b.top, b.right, b.bottom, Canvas.EdgeType.AA)) { scale = (float) getBounds().width() / (float) emojiFullSize;
canvas.drawBitmap(emojiBmp[info.page], info.rect, b, paint);
} }
canvas.save();
canvas.scale(scale, scale);
canvas.drawBitmap(bitmap.colors, info.rect.top * bitmap.width + info.rect.left, bitmap.width, offset, offset, info.rect.right, info.rect.bottom, true, paint);
canvas.restore();
} }
@Override @Override
...@@ -393,6 +409,7 @@ public class Emoji { ...@@ -393,6 +409,7 @@ public class Emoji {
} }
long buf = 0; long buf = 0;
int emojiCount = 0; int emojiCount = 0;
try {
for (int i = 0; i < cs.length(); i++) { for (int i = 0; i < cs.length(); i++) {
char c = cs.charAt(i); char c = cs.charAt(i);
if (c == 0xD83C || c == 0xD83D || (buf != 0 && (buf & 0xFFFFFFFF00000000L) == 0 && (c >= 0xDDE6 && c <= 0xDDFA))) { if (c == 0xD83C || c == 0xD83D || (buf != 0 && (buf & 0xFFFFFFFF00000000L) == 0 && (c >= 0xDDE6 && c <= 0xDDFA))) {
...@@ -440,17 +457,26 @@ public class Emoji { ...@@ -440,17 +457,26 @@ public class Emoji {
break; break;
} }
} }
} catch (Exception e) {
FileLog.e("tmessages", e);
return cs;
}
return s; return s;
} }
public static class EmojiSpan extends ImageSpan { public static class EmojiSpan extends ImageSpan {
private Paint.FontMetricsInt fontMetrics = null; private Paint.FontMetricsInt fontMetrics = null;
private int size = Utilities.dp(20); int size = Utilities.dp(20);
public EmojiSpan(Drawable d, int verticalAlignment, int s, Paint.FontMetricsInt original) { public EmojiSpan(Drawable d, int verticalAlignment, int s, Paint.FontMetricsInt original) {
super(d, verticalAlignment); super(d, verticalAlignment);
fontMetrics = original; fontMetrics = original;
size = s; if (original != null) {
size = Math.abs(fontMetrics.descent) + Math.abs(fontMetrics.ascent);
if (size == 0) {
size = Utilities.dp(20);
}
}
} }
@Override @Override
...@@ -479,6 +505,9 @@ public class Emoji { ...@@ -479,6 +505,9 @@ public class Emoji {
fm.top = fontMetrics.top; fm.top = fontMetrics.top;
fm.bottom = fontMetrics.bottom; fm.bottom = fontMetrics.bottom;
} }
if (getDrawable() != null) {
getDrawable().setBounds(0, 0, size, size);
}
return size; return size;
} }
} }
......
...@@ -85,6 +85,6 @@ public class ExportAuthorizationAction extends Action { ...@@ -85,6 +85,6 @@ public class ExportAuthorizationAction extends Action {
} }
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassEnableUnauthorized, datacenter.datacenterId); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassEnableUnauthorized | RPCRequest.RPCRequestClassWithoutLogin, datacenter.datacenterId);
} }
} }
...@@ -337,11 +337,11 @@ public class FileLoader { ...@@ -337,11 +337,11 @@ public class FileLoader {
return memCache.get(key) != null; return memCache.get(key) != null;
} }
public void uploadFile(final String location, final byte[] key, final byte[] iv) { public void uploadFile(final String location, final boolean encrypted) {
fileLoaderQueue.postRunnable(new Runnable() { fileLoaderQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (key != null) { if (encrypted) {
if (uploadOperationPathsEnc.containsKey(location)) { if (uploadOperationPathsEnc.containsKey(location)) {
return; return;
} }
...@@ -350,8 +350,8 @@ public class FileLoader { ...@@ -350,8 +350,8 @@ public class FileLoader {
return; return;
} }
} }
FileUploadOperation operation = new FileUploadOperation(location, key, iv); FileUploadOperation operation = new FileUploadOperation(location, encrypted);
if (key != null) { if (encrypted) {
uploadOperationPathsEnc.put(location, operation); uploadOperationPathsEnc.put(location, operation);
} else { } else {
uploadOperationPaths.put(location, operation); uploadOperationPaths.put(location, operation);
...@@ -369,7 +369,7 @@ public class FileLoader { ...@@ -369,7 +369,7 @@ public class FileLoader {
fileProgresses.remove(location); fileProgresses.remove(location);
} }
}); });
if (key != null) { if (encrypted) {
uploadOperationPathsEnc.remove(location); uploadOperationPathsEnc.remove(location);
} else { } else {
uploadOperationPaths.remove(location); uploadOperationPaths.remove(location);
...@@ -396,11 +396,11 @@ public class FileLoader { ...@@ -396,11 +396,11 @@ public class FileLoader {
public void run() { public void run() {
fileProgresses.remove(location); fileProgresses.remove(location);
if (operation.state != 2) { if (operation.state != 2) {
NotificationCenter.getInstance().postNotificationName(FileDidFailUpload, location, key != null); NotificationCenter.getInstance().postNotificationName(FileDidFailUpload, location, encrypted);
} }
} }
}); });
if (key != null) { if (encrypted) {
uploadOperationPathsEnc.remove(location); uploadOperationPathsEnc.remove(location);
} else { } else {
uploadOperationPaths.remove(location); uploadOperationPaths.remove(location);
...@@ -428,7 +428,7 @@ public class FileLoader { ...@@ -428,7 +428,7 @@ public class FileLoader {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
NotificationCenter.getInstance().postNotificationName(FileUploadProgressChanged, location, progress, key != null); NotificationCenter.getInstance().postNotificationName(FileUploadProgressChanged, location, progress, encrypted);
} }
}); });
} }
......
...@@ -44,6 +44,7 @@ public class FileLog { ...@@ -44,6 +44,7 @@ public class FileLog {
return; return;
} }
dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US); dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US);
try {
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null); File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
if (sdCard == null) { if (sdCard == null) {
return; return;
...@@ -57,6 +58,9 @@ public class FileLog { ...@@ -57,6 +58,9 @@ public class FileLog {
if (currentFile == null) { if (currentFile == null) {
return; return;
} }
} catch (Exception e) {
e.printStackTrace();
}
try { try {
currentFile.createNewFile(); currentFile.createNewFile();
FileOutputStream stream = new FileOutputStream(currentFile); FileOutputStream stream = new FileOutputStream(currentFile);
...@@ -110,7 +114,7 @@ public class FileLog { ...@@ -110,7 +114,7 @@ public class FileLog {
} }
} }
public static void e(final String tag, final Exception e) { public static void e(final String tag, final Throwable e) {
if (!BuildVars.DEBUG_VERSION) { if (!BuildVars.DEBUG_VERSION) {
return; return;
} }
......
...@@ -30,6 +30,7 @@ public class FileUploadOperation { ...@@ -30,6 +30,7 @@ public class FileUploadOperation {
private long currentUploaded = 0; private long currentUploaded = 0;
private byte[] key; private byte[] key;
private byte[] iv; private byte[] iv;
private byte[] ivChange;
private int fingerprint; private int fingerprint;
private boolean isBigFile = false; private boolean isBigFile = false;
FileInputStream stream; FileInputStream stream;
...@@ -41,12 +42,15 @@ public class FileUploadOperation { ...@@ -41,12 +42,15 @@ public class FileUploadOperation {
public abstract void didChangedUploadProgress(FileUploadOperation operation, float progress); public abstract void didChangedUploadProgress(FileUploadOperation operation, float progress);
} }
public FileUploadOperation(String location, byte[] keyarr, byte[] ivarr) { public FileUploadOperation(String location, boolean encrypted) {
uploadingFilePath = location; uploadingFilePath = location;
if (ivarr != null && keyarr != null) { if (encrypted) {
iv = new byte[32]; iv = new byte[32];
key = keyarr; key = new byte[32];
System.arraycopy(ivarr, 0, iv, 0, 32); ivChange = new byte[32];
Utilities.random.nextBytes(iv);
Utilities.random.nextBytes(key);
System.arraycopy(iv, 0, ivChange, 0, 32);
try { try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] arr = new byte[64]; byte[] arr = new byte[64];
...@@ -106,7 +110,7 @@ public class FileUploadOperation { ...@@ -106,7 +110,7 @@ public class FileUploadOperation {
isBigFile = true; isBigFile = true;
} }
uploadChunkSize = (int)Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000))); uploadChunkSize = (int) Math.max(32, Math.ceil(totalFileSize / (1024.0f * 3000)));
if (1024 % uploadChunkSize != 0) { if (1024 % uploadChunkSize != 0) {
int chunkSize = 64; int chunkSize = 64;
while (uploadChunkSize > chunkSize) { while (uploadChunkSize > chunkSize) {
...@@ -116,7 +120,7 @@ public class FileUploadOperation { ...@@ -116,7 +120,7 @@ public class FileUploadOperation {
} }
uploadChunkSize *= 1024; uploadChunkSize *= 1024;
totalPartsCount = (int)Math.ceil((float)totalFileSize / (float)uploadChunkSize); totalPartsCount = (int) Math.ceil((float) totalFileSize / (float) uploadChunkSize);
readBuffer = new byte[uploadChunkSize]; readBuffer = new byte[uploadChunkSize];
} }
...@@ -134,7 +138,7 @@ public class FileUploadOperation { ...@@ -134,7 +138,7 @@ public class FileUploadOperation {
for (int a = 0; a < toAdd; a++) { for (int a = 0; a < toAdd; a++) {
sendBuffer.writeByte(0); sendBuffer.writeByte(0);
} }
Utilities.aesIgeEncryption2(sendBuffer.buffer, key, iv, true, true, readed + toAdd); Utilities.aesIgeEncryption2(sendBuffer.buffer, key, ivChange, true, true, readed + toAdd);
} }
sendBuffer.rewind(); sendBuffer.rewind();
if (!isBigFile) { if (!isBigFile) {
...@@ -167,7 +171,7 @@ public class FileUploadOperation { ...@@ -167,7 +171,7 @@ public class FileUploadOperation {
if (error == null) { if (error == null) {
if (response instanceof TLRPC.TL_boolTrue) { if (response instanceof TLRPC.TL_boolTrue) {
currentPartNum++; currentPartNum++;
delegate.didChangedUploadProgress(FileUploadOperation.this, (float)currentUploaded / (float)totalFileSize); delegate.didChangedUploadProgress(FileUploadOperation.this, (float) currentUploaded / (float) totalFileSize);
if (isLastPart) { if (isLastPart) {
state = 3; state = 3;
if (key == null) { if (key == null) {
...@@ -193,6 +197,8 @@ public class FileUploadOperation { ...@@ -193,6 +197,8 @@ public class FileUploadOperation {
result.parts = currentPartNum; result.parts = currentPartNum;
result.id = currentFileId; result.id = currentFileId;
result.key_fingerprint = fingerprint; result.key_fingerprint = fingerprint;
result.iv = iv;
result.key = key;
delegate.didFinishUploadingFile(FileUploadOperation.this, null, result); delegate.didFinishUploadingFile(FileUploadOperation.this, null, result);
} }
} else { } else {
......
...@@ -12,7 +12,6 @@ import android.app.Activity; ...@@ -12,7 +12,6 @@ import android.app.Activity;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.PowerManager;
import org.json.JSONObject; import org.json.JSONObject;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
...@@ -20,7 +19,6 @@ import org.telegram.ui.ApplicationLoader; ...@@ -20,7 +19,6 @@ import org.telegram.ui.ApplicationLoader;
public class GcmBroadcastReceiver extends BroadcastReceiver { public class GcmBroadcastReceiver extends BroadcastReceiver {
public static final int NOTIFICATION_ID = 1; public static final int NOTIFICATION_ID = 1;
private static PowerManager.WakeLock wakeLock = null;
private static final Integer sync = 1; private static final Integer sync = 1;
@Override @Override
...@@ -28,27 +26,6 @@ public class GcmBroadcastReceiver extends BroadcastReceiver { ...@@ -28,27 +26,6 @@ public class GcmBroadcastReceiver extends BroadcastReceiver {
FileLog.d("tmessages", "GCM received intent: " + intent); FileLog.d("tmessages", "GCM received intent: " + intent);
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
synchronized (sync) {
try {
if (wakeLock == null) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
}
if (!wakeLock.isHeld()) {
wakeLock.acquire(5000);
}
} catch (Exception e) {
try {
if (wakeLock != null) {
wakeLock.release();
}
} catch (Exception e2) {
FileLog.e("tmessages", e2);
}
FileLog.e("tmessages", e);
}
}
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
......
...@@ -52,9 +52,9 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -52,9 +52,9 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
void beginHandshake(boolean dropConnection) { void beginHandshake(boolean dropConnection) {
if (datacenter.connection == null) { if (datacenter.connection == null) {
datacenter.connection = new TcpConnection(datacenter.datacenterId); datacenter.connection = new TcpConnection(datacenter.datacenterId);
datacenter.connection.delegate = this;
datacenter.connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric; datacenter.connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric;
} }
datacenter.connection.delegate = this;
processedMessageIds = new ArrayList<Long>(); processedMessageIds = new ArrayList<Long>();
authNonce = null; authNonce = null;
...@@ -209,7 +209,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -209,7 +209,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
ByteBuffer data = ByteBuffer.wrap(resPq.pq); ByteBuffer data = ByteBuffer.wrap(resPq.pq);
final long pqf = data.getLong(); final long pqf = data.getLong();
final long messageIdf = messageId; final long messageIdf = messageId;
Utilities.globalQueue.postRunnable(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -281,7 +281,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -281,7 +281,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
} }
}); });
} }
}); }).start();
} else { } else {
FileLog.e("tmessages", "***** Error: invalid handshake nonce"); FileLog.e("tmessages", "***** Error: invalid handshake nonce");
beginHandshake(false); beginHandshake(false);
...@@ -566,8 +566,14 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -566,8 +566,14 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
} }
@Override @Override
public void tcpConnectionClosed(TcpConnection connection) { public void tcpConnectionClosed(final TcpConnection connection) {
wasDisconnect = true; wasDisconnect = true;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
connection.connect();
}
}, 1000);
} }
@Override @Override
...@@ -591,9 +597,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti ...@@ -591,9 +597,7 @@ public class HandshakeAction extends Action implements TcpConnection.TcpConnecti
@Override @Override
public void tcpConnectionReceivedData(TcpConnection connection, ByteBufferDesc data, int length) { public void tcpConnectionReceivedData(TcpConnection connection, ByteBufferDesc data, int length) {
long keyId = data.readInt64(); long keyId = data.readInt64();
if (keyId == 0) { if (keyId == 0) {
long messageId = data.readInt64(); long messageId = data.readInt64();
if (processedMessageIds.contains(messageId)) { if (processedMessageIds.contains(messageId)) {
......
...@@ -1024,7 +1024,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1024,7 +1024,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
fileDecodingQueue.postRunnable(new Runnable() { fileDecodingQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (playingMessageObject.audioProgress != 0) { if (playingMessageObject != null && playingMessageObject.audioProgress != 0) {
lastPlayPcm = (long)(currentTotalPcmDuration * playingMessageObject.audioProgress); lastPlayPcm = (long)(currentTotalPcmDuration * playingMessageObject.audioProgress);
seekOpusFile(playingMessageObject.audioProgress); seekOpusFile(playingMessageObject.audioProgress);
} }
...@@ -1143,7 +1143,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1143,7 +1143,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
recordingAudio = new TLRPC.TL_audio(); recordingAudio = new TLRPC.TL_audio();
recordingAudio.dc_id = Integer.MIN_VALUE; recordingAudio.dc_id = Integer.MIN_VALUE;
recordingAudio.id = UserConfig.lastLocalId; recordingAudio.id = UserConfig.lastLocalId;
recordingAudio.user_id = UserConfig.clientUserId; recordingAudio.user_id = UserConfig.getClientUserId();
UserConfig.lastLocalId--; UserConfig.lastLocalId--;
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
...@@ -1352,7 +1352,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1352,7 +1352,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
final ProgressDialog finalProgress = progressDialog; final ProgressDialog finalProgress = progressDialog;
Utilities.globalQueue.postRunnable(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
...@@ -1427,7 +1427,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1427,7 +1427,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
}); });
} }
} }
}); }).start();
} }
} }
...@@ -1536,7 +1536,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1536,7 +1536,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
return false; return false;
} }
public static String copyDocumentToCache(Uri uri) { public static String copyDocumentToCache(Uri uri, String ext) {
ParcelFileDescriptor parcelFD = null; ParcelFileDescriptor parcelFD = null;
FileInputStream input = null; FileInputStream input = null;
FileOutputStream output = null; FileOutputStream output = null;
...@@ -1545,7 +1545,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel ...@@ -1545,7 +1545,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
UserConfig.lastLocalId--; UserConfig.lastLocalId--;
parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r"); parcelFD = ApplicationLoader.applicationContext.getContentResolver().openFileDescriptor(uri, "r");
input = new FileInputStream(parcelFD.getFileDescriptor()); input = new FileInputStream(parcelFD.getFileDescriptor());
File f = new File(Utilities.getCacheDir(), String.format(Locale.US, "%d.gif", id)); File f = new File(Utilities.getCacheDir(), String.format(Locale.US, "%d.%s", id, ext));
output = new FileOutputStream(f); output = new FileOutputStream(f);
input.getChannel().transferTo(0, input.getChannel().size(), output.getChannel()); input.getChannel().transferTo(0, input.getChannel().size(), output.getChannel());
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
......
...@@ -36,6 +36,11 @@ public class MessagesStorage { ...@@ -36,6 +36,11 @@ public class MessagesStorage {
public static byte[] secretPBytes = null; public static byte[] secretPBytes = null;
public static int secretG = 0; public static int secretG = 0;
private int lastSavedSeq = 0;
private int lastSavedPts = 0;
private int lastSavedDate = 0;
private int lastSavedQts = 0;
public static final int wallpapersDidLoaded = 171; public static final int wallpapersDidLoaded = 171;
private static volatile MessagesStorage Instance = null; private static volatile MessagesStorage Instance = null;
...@@ -92,6 +97,8 @@ public class MessagesStorage { ...@@ -92,6 +97,8 @@ public class MessagesStorage {
database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose(); database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose(); database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose();
database.executeFast("CREATE TABLE sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
...@@ -161,6 +168,8 @@ public class MessagesStorage { ...@@ -161,6 +168,8 @@ public class MessagesStorage {
database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS sphone_deleted_idx_user_phones ON user_phones_v6(sphone, deleted);").stepThis().dispose();
database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose(); database.executeFast("CREATE INDEX IF NOT EXISTS mid_idx_randoms ON randoms(mid);").stepThis().dispose();
database.executeFast("CREATE TABLE IF NOT EXISTS sent_files_v2(uid TEXT, type INTEGER, data BLOB, PRIMARY KEY (uid, type))").stepThis().dispose();
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
...@@ -168,6 +177,7 @@ public class MessagesStorage { ...@@ -168,6 +177,7 @@ public class MessagesStorage {
} }
public void cleanUp() { public void cleanUp() {
storageQueue.cleanupQueue();
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -176,6 +186,12 @@ public class MessagesStorage { ...@@ -176,6 +186,12 @@ public class MessagesStorage {
lastPtsValue = 0; lastPtsValue = 0;
lastQtsValue = 0; lastQtsValue = 0;
lastSecretVersion = 0; lastSecretVersion = 0;
lastSavedSeq = 0;
lastSavedPts = 0;
lastSavedDate = 0;
lastSavedQts = 0;
secretPBytes = null; secretPBytes = null;
secretG = 0; secretG = 0;
if (database != null) { if (database != null) {
...@@ -186,6 +202,7 @@ public class MessagesStorage { ...@@ -186,6 +202,7 @@ public class MessagesStorage {
cacheFile.delete(); cacheFile.delete();
cacheFile = null; cacheFile = null;
} }
storageQueue.cleanupQueue();
openDatabase(); openDatabase();
} }
}); });
...@@ -218,6 +235,9 @@ public class MessagesStorage { ...@@ -218,6 +235,9 @@ public class MessagesStorage {
@Override @Override
public void run() { public void run() {
try { try {
if (lastSavedSeq == seq && lastSavedPts == pts && lastSavedDate == date && lastQtsValue == qts) {
return;
}
SQLitePreparedStatement state = database.executeFast("UPDATE params SET seq = ?, pts = ?, date = ?, qts = ? WHERE id = 1"); SQLitePreparedStatement state = database.executeFast("UPDATE params SET seq = ?, pts = ?, date = ?, qts = ? WHERE id = 1");
state.bindInteger(1, seq); state.bindInteger(1, seq);
state.bindInteger(2, pts); state.bindInteger(2, pts);
...@@ -225,6 +245,10 @@ public class MessagesStorage { ...@@ -225,6 +245,10 @@ public class MessagesStorage {
state.bindInteger(4, qts); state.bindInteger(4, qts);
state.step(); state.step();
state.dispose(); state.dispose();
lastSavedSeq = seq;
lastSavedPts = pts;
lastSavedDate = date;
lastSavedQts = qts;
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
...@@ -781,7 +805,7 @@ public class MessagesStorage { ...@@ -781,7 +805,7 @@ public class MessagesStorage {
if (userData != null) { if (userData != null) {
SerializedData data = new SerializedData(userData); SerializedData data = new SerializedData(userData);
TLRPC.User user = (TLRPC.User)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); TLRPC.User user = (TLRPC.User)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (user.id == UserConfig.clientUserId) { if (user.id == UserConfig.getClientUserId()) {
continue; continue;
} }
if (user.status != null) { if (user.status != null) {
...@@ -1018,7 +1042,7 @@ public class MessagesStorage { ...@@ -1018,7 +1042,7 @@ public class MessagesStorage {
String uids = ""; String uids = "";
while (cursor.next()) { while (cursor.next()) {
int user_id = cursor.intValue(0); int user_id = cursor.intValue(0);
if (user_id == UserConfig.clientUserId) { if (user_id == UserConfig.getClientUserId()) {
continue; continue;
} }
TLRPC.TL_contact contact = new TLRPC.TL_contact(); TLRPC.TL_contact contact = new TLRPC.TL_contact();
...@@ -1415,6 +1439,73 @@ public class MessagesStorage { ...@@ -1415,6 +1439,73 @@ public class MessagesStorage {
} }
} }
public TLObject getSentFile(final String path, final int type) {
if (path == null) {
return null;
}
final Semaphore semaphore = new Semaphore(0);
final ArrayList<TLObject> result = new ArrayList<TLObject>();
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
String id = Utilities.MD5(path);
if (id != null) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM sent_files_v2 WHERE uid = '%s' AND type = %d", id, type));
if (cursor.next()) {
byte[] fileData = cursor.byteArrayValue(0);
if (fileData != null) {
SerializedData data = new SerializedData(fileData);
TLObject file = TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (file != null) {
result.add(file);
}
}
}
cursor.dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
semaphore.release();
}
}
});
try {
semaphore.acquire();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return !result.isEmpty() ? result.get(0) : null;
}
public void putSentFile(final String path, final TLObject file, final int type) {
if (path == null || file == null) {
return;
}
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
String id = Utilities.MD5(path);
if (id != null) {
SQLitePreparedStatement state = database.executeFast("REPLACE INTO sent_files_v2 VALUES(?, ?, ?)");
state.requery();
SerializedData data = new SerializedData();
file.serializeToStream(data);
state.bindString(1, id);
state.bindInteger(2, type);
state.bindByteArray(3, data.toByteArray());
state.step();
state.dispose();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public void updateEncryptedChatTTL(final TLRPC.EncryptedChat chat) { public void updateEncryptedChatTTL(final TLRPC.EncryptedChat chat) {
if (chat == null) { if (chat == null) {
return; return;
...@@ -1838,6 +1929,7 @@ public class MessagesStorage { ...@@ -1838,6 +1929,7 @@ public class MessagesStorage {
state.bindInteger(2, count); state.bindInteger(2, count);
state.step(); state.step();
} }
cursor.dispose();
} }
state.dispose(); state.dispose();
} }
...@@ -2484,7 +2576,7 @@ public class MessagesStorage { ...@@ -2484,7 +2576,7 @@ public class MessagesStorage {
ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<TLRPC.EncryptedChat>(); ArrayList<TLRPC.EncryptedChat> encryptedChats = new ArrayList<TLRPC.EncryptedChat>();
try { try {
ArrayList<Integer> usersToLoad = new ArrayList<Integer>(); ArrayList<Integer> usersToLoad = new ArrayList<Integer>();
usersToLoad.add(UserConfig.clientUserId); usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = new ArrayList<Integer>(); ArrayList<Integer> chatsToLoad = new ArrayList<Integer>();
ArrayList<Integer> encryptedToLoad = new ArrayList<Integer>(); ArrayList<Integer> encryptedToLoad = new ArrayList<Integer>();
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 FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid 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 FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid ORDER BY d.date DESC LIMIT %d,%d", offset, count));
......
...@@ -22,9 +22,9 @@ import java.util.zip.ZipFile; ...@@ -22,9 +22,9 @@ import java.util.zip.ZipFile;
public class NativeLoader { public class NativeLoader {
private static final long sizes[] = new long[] { private static final long sizes[] = new long[] {
922256, //armeabi 795280, //armeabi
991908, //armeabi-v7a 844452, //armeabi-v7a
1713204, //x86 1242164, //x86
0, //mips 0, //mips
}; };
...@@ -48,6 +48,53 @@ public class NativeLoader { ...@@ -48,6 +48,53 @@ public class NativeLoader {
return null; return null;
} }
private static boolean loadFromZip(Context context, File destLocalFile, String folder) {
ZipFile zipFile = null;
InputStream stream = null;
try {
zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
ZipEntry entry = zipFile.getEntry("lib/" + folder + "/libtmessages.so");
if (entry == null) {
throw new Exception("Unable to find file in apk:" + "lib/" + folder + "/libtmessages.so");
}
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
try {
System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true;
} catch (Error e) {
FileLog.e("tmessages", e);
}
return true;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
return false;
}
public static synchronized void initNativeLibs(Context context) { public static synchronized void initNativeLibs(Context context) {
if (nativeLoaded) { if (nativeLoaded) {
...@@ -87,6 +134,12 @@ public class NativeLoader { ...@@ -87,6 +134,12 @@ public class NativeLoader {
libSize2 = sizes[1]; libSize2 = sizes[1];
} }
String javaArch = System.getProperty("os.arch");
if (javaArch != null && javaArch.contains("686")) {
folder = "x86";
libSize = sizes[2];
}
File destFile = getNativeLibraryDir(context); File destFile = getNativeLibraryDir(context);
if (destFile != null) { if (destFile != null) {
destFile = new File(destFile, "libtmessages.so"); destFile = new File(destFile, "libtmessages.so");
...@@ -96,22 +149,22 @@ public class NativeLoader { ...@@ -96,22 +149,22 @@ public class NativeLoader {
System.loadLibrary("tmessages"); System.loadLibrary("tmessages");
nativeLoaded = true; nativeLoaded = true;
return; return;
} catch (Exception e) { } catch (Error e) {
e.printStackTrace(); FileLog.e("tmessages", e);
} }
} }
} }
File destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessages.so"); File destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessages.so");
if (destLocalFile.exists()) { if (destLocalFile != null && destLocalFile.exists()) {
if (destLocalFile.length() == libSize) { if (destLocalFile.length() == libSize) {
try { try {
FileLog.d("tmessages", "Load local lib"); FileLog.d("tmessages", "Load local lib");
System.load(destLocalFile.getAbsolutePath()); System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true; nativeLoaded = true;
return; return;
} catch (Exception e) { } catch (Error e) {
e.printStackTrace(); FileLog.e("tmessages", e);
} }
} else { } else {
destLocalFile.delete(); destLocalFile.delete();
...@@ -120,51 +173,24 @@ public class NativeLoader { ...@@ -120,51 +173,24 @@ public class NativeLoader {
FileLog.e("tmessages", "Library not found, arch = " + folder); FileLog.e("tmessages", "Library not found, arch = " + folder);
ZipFile zipFile = null; if (!loadFromZip(context, destLocalFile, folder)) {
InputStream stream = null; folder = "x86";
try { destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessages86.so");
zipFile = new ZipFile(context.getApplicationInfo().sourceDir); if (!loadFromZip(context, destLocalFile, folder)) {
ZipEntry entry = zipFile.getEntry("lib/" + folder + "/libtmessages.so"); destLocalFile = new File(context.getFilesDir().getAbsolutePath() + "/libtmessagesarm.so");
if (entry == null) { folder = "armeabi";
throw new Exception("Unable to find file in apk:" + "lib/" + folder + "/libtmessages.so"); loadFromZip(context, destLocalFile, folder);
}
stream = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(destLocalFile);
byte[] buf = new byte[4096];
int len;
while ((len = stream.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
System.load(destLocalFile.getAbsolutePath());
nativeLoaded = true;
return;
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
} }
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
try {
System.loadLibrary("tmessages"); System.loadLibrary("tmessages");
nativeLoaded = true; nativeLoaded = true;
} catch (Error e) {
FileLog.e("tmessages", e);
}
} }
} }
...@@ -28,6 +28,8 @@ public class RPCRequest { ...@@ -28,6 +28,8 @@ public class RPCRequest {
public static int RPCRequestClassFailOnServerErrors = 16; public static int RPCRequestClassFailOnServerErrors = 16;
public static int RPCRequestClassCanCompress = 32; public static int RPCRequestClassCanCompress = 32;
public static int RPCRequestClassPush = 64; public static int RPCRequestClassPush = 64;
public static int RPCRequestClassWithoutLogin = 128;
public static int RPCRequestClassDownloadMedia2 = 256;
static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia); static int RPCRequestClassTransportMask = (RPCRequestClassGeneric | RPCRequestClassDownloadMedia | RPCRequestClassUploadMedia);
......
...@@ -19,9 +19,13 @@ public class ScreenReceiver extends BroadcastReceiver { ...@@ -19,9 +19,13 @@ public class ScreenReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
FileLog.e("tmessages", "screen off"); FileLog.e("tmessages", "screen off");
if (ConnectionsManager.lastPauseTime == 0) {
ConnectionsManager.lastPauseTime = System.currentTimeMillis();
}
ApplicationLoader.isScreenOn = false; ApplicationLoader.isScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
FileLog.e("tmessages", "screen on"); FileLog.e("tmessages", "screen on");
ConnectionsManager.resetLastPauseTime();
ApplicationLoader.isScreenOn = true; ApplicationLoader.isScreenOn = true;
} }
} }
......
...@@ -9,6 +9,8 @@ ...@@ -9,6 +9,8 @@
package org.telegram.messenger; package org.telegram.messenger;
public class TLObject { public class TLObject {
public boolean disableFree = false;
public TLObject () { public TLObject () {
} }
......
...@@ -3783,14 +3783,6 @@ public class TLRPC { ...@@ -3783,14 +3783,6 @@ public class TLRPC {
} }
} }
public static class InputEncryptedFile extends TLObject {
public long id;
public long access_hash;
public int parts;
public int key_fingerprint;
public String md5_checksum;
}
public static class TL_inputEncryptedFile extends InputEncryptedFile { public static class TL_inputEncryptedFile extends InputEncryptedFile {
public static int constructor = 0x5a17b5e5; public static int constructor = 0x5a17b5e5;
...@@ -8144,6 +8136,9 @@ public class TLRPC { ...@@ -8144,6 +8136,9 @@ public class TLRPC {
@Override @Override
public void freeResources() { public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) { if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes); BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null; bytes = null;
...@@ -8295,6 +8290,9 @@ public class TLRPC { ...@@ -8295,6 +8290,9 @@ public class TLRPC {
@Override @Override
public void freeResources() { public void freeResources() {
if (disableFree) {
return;
}
if (result != null) { if (result != null) {
result.freeResources(); result.freeResources();
} }
...@@ -8834,7 +8832,7 @@ public class TLRPC { ...@@ -8834,7 +8832,7 @@ public class TLRPC {
} }
} }
public static class TL_documentEncrypted extends Document { public static class TL_documentEncrypted extends TL_document {
public static int constructor = 0x55555556; public static int constructor = 0x55555556;
...@@ -8868,7 +8866,7 @@ public class TLRPC { ...@@ -8868,7 +8866,7 @@ public class TLRPC {
} }
} }
public static class TL_videoEncrypted extends Video { public static class TL_videoEncrypted extends TL_video {
public static int constructor = 0x55555553; public static int constructor = 0x55555553;
...@@ -9179,6 +9177,9 @@ public class TLRPC { ...@@ -9179,6 +9177,9 @@ public class TLRPC {
@Override @Override
public void freeResources() { public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) { if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes); BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null; bytes = null;
...@@ -9206,10 +9207,23 @@ public class TLRPC { ...@@ -9206,10 +9207,23 @@ public class TLRPC {
@Override @Override
public void freeResources() { public void freeResources() {
if (disableFree) {
return;
}
if (bytes != null) { if (bytes != null) {
BuffersStorage.getInstance().reuseFreeBuffer(bytes); BuffersStorage.getInstance().reuseFreeBuffer(bytes);
bytes = null; bytes = null;
} }
} }
} }
public static class InputEncryptedFile extends TLObject {
public long id;
public long access_hash;
public int parts;
public int key_fingerprint;
public String md5_checksum;
public byte[] key;
public byte[] iv;
}
} }
...@@ -135,7 +135,7 @@ public class TcpConnection extends ConnectionContext { ...@@ -135,7 +135,7 @@ public class TcpConnection extends ConnectionContext {
client.addListener(TcpConnection.this); client.addListener(TcpConnection.this);
if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) { if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
if (isNextPort) { if (isNextPort) {
client.setTimeout(15000); client.setTimeout(20000);
} else { } else {
client.setTimeout(30000); client.setTimeout(30000);
} }
...@@ -424,7 +424,7 @@ public class TcpConnection extends ConnectionContext { ...@@ -424,7 +424,7 @@ public class TcpConnection extends ConnectionContext {
datacenter.storeCurrentAddressAndPortNum(); datacenter.storeCurrentAddressAndPortNum();
isNextPort = false; isNextPort = false;
if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) { if ((transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
client.setTimeout(40000); client.setTimeout(60000 * 3 + 20000);
} else { } else {
client.setTimeout(25000); client.setTimeout(25000);
} }
......
...@@ -17,9 +17,7 @@ import org.telegram.ui.ApplicationLoader; ...@@ -17,9 +17,7 @@ import org.telegram.ui.ApplicationLoader;
import java.io.File; import java.io.File;
public class UserConfig { public class UserConfig {
public static TLRPC.User currentUser; private static TLRPC.User currentUser;
public static int clientUserId = 0;
public static boolean clientActivated = false;
public static boolean registeredForPush = false; public static boolean registeredForPush = false;
public static boolean registeredForInternalPush = false; public static boolean registeredForInternalPush = false;
public static String pushString = ""; public static String pushString = "";
...@@ -62,8 +60,6 @@ public class UserConfig { ...@@ -62,8 +60,6 @@ public class UserConfig {
if (withFile) { if (withFile) {
SerializedData data = new SerializedData(); SerializedData data = new SerializedData();
currentUser.serializeToStream(data); currentUser.serializeToStream(data);
clientUserId = currentUser.id;
clientActivated = true;
String userString = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT); String userString = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
editor.putString("user", userString); editor.putString("user", userString);
} }
...@@ -80,6 +76,30 @@ public class UserConfig { ...@@ -80,6 +76,30 @@ public class UserConfig {
} }
} }
public static boolean isClientActivated() {
synchronized (sync) {
return currentUser != null;
}
}
public static int getClientUserId() {
synchronized (sync) {
return currentUser != null ? currentUser.id : 0;
}
}
public static TLRPC.User getCurrentUser() {
synchronized (sync) {
return currentUser;
}
}
public static void setCurrentUser(TLRPC.User user) {
synchronized (sync) {
currentUser = user;
}
}
public static void loadConfig() { public static void loadConfig() {
synchronized (sync) { synchronized (sync) {
final File configFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "user.dat"); final File configFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "user.dat");
...@@ -90,8 +110,6 @@ public class UserConfig { ...@@ -90,8 +110,6 @@ public class UserConfig {
if (ver == 1) { if (ver == 1) {
int constructor = data.readInt32(); int constructor = data.readInt32();
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor); currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor);
clientUserId = currentUser.id;
clientActivated = true;
MessagesStorage.lastDateValue = data.readInt32(); MessagesStorage.lastDateValue = data.readInt32();
MessagesStorage.lastPtsValue = data.readInt32(); MessagesStorage.lastPtsValue = data.readInt32();
MessagesStorage.lastSeqValue = data.readInt32(); MessagesStorage.lastSeqValue = data.readInt32();
...@@ -119,8 +137,6 @@ public class UserConfig { ...@@ -119,8 +137,6 @@ public class UserConfig {
} else if (ver == 2) { } else if (ver == 2) {
int constructor = data.readInt32(); int constructor = data.readInt32();
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor); currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, constructor);
clientUserId = currentUser.id;
clientActivated = true;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
registeredForPush = preferences.getBoolean("registeredForPush", false); registeredForPush = preferences.getBoolean("registeredForPush", false);
...@@ -164,21 +180,13 @@ public class UserConfig { ...@@ -164,21 +180,13 @@ public class UserConfig {
if (userBytes != null) { if (userBytes != null) {
SerializedData data = new SerializedData(userBytes); SerializedData data = new SerializedData(userBytes);
currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, data.readInt32()); currentUser = (TLRPC.TL_userSelf)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
clientUserId = currentUser.id;
clientActivated = true;
}
} }
if (currentUser == null) {
clientActivated = false;
clientUserId = 0;
} }
} }
} }
} }
public static void clearConfig() { public static void clearConfig() {
clientUserId = 0;
clientActivated = false;
currentUser = null; currentUser = null;
registeredForInternalPush = false; registeredForInternalPush = false;
registeredForPush = false; registeredForPush = false;
......
...@@ -15,8 +15,8 @@ import android.content.Context; ...@@ -15,8 +15,8 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.ActivityInfo; import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor; import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.net.Uri; import android.net.Uri;
...@@ -34,6 +34,7 @@ import android.view.WindowManager; ...@@ -34,6 +34,7 @@ import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import net.hockeyapp.android.CrashManager; import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.UpdateManager; import net.hockeyapp.android.UpdateManager;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
...@@ -87,6 +88,8 @@ public class Utilities { ...@@ -87,6 +88,8 @@ public class Utilities {
public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue"); public static volatile DispatchQueue stageQueue = new DispatchQueue("stageQueue");
public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue"); public static volatile DispatchQueue globalQueue = new DispatchQueue("globalQueue");
public static volatile DispatchQueue searchQueue = new DispatchQueue("searchQueue");
public static volatile DispatchQueue photoBookQueue = new DispatchQueue("photoBookQueue");
public static int[] arrColors = {0xffee4928, 0xff41a903, 0xffe09602, 0xff0f94ed, 0xff8f3bf7, 0xfffc4380, 0xff00a1c4, 0xffeb7002}; public static int[] arrColors = {0xffee4928, 0xff41a903, 0xffe09602, 0xff0f94ed, 0xff8f3bf7, 0xfffc4380, 0xff00a1c4, 0xffeb7002};
public static int[] arrUsersAvatars = { public static int[] arrUsersAvatars = {
...@@ -153,7 +156,7 @@ public class Utilities { ...@@ -153,7 +156,7 @@ public class Utilities {
public native static long doPQNative(long _what); public native static long doPQNative(long _what);
public native static byte[] aesIgeEncryption(byte[] _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len); public native static byte[] aesIgeEncryption(byte[] _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void aesIgeEncryption2(ByteBuffer _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len); public native static void aesIgeEncryption2(ByteBuffer _what, byte[] _key, byte[] _iv, boolean encrypt, boolean changeIv, int len);
public native static void loadBitmap(String path, Bitmap bitmap, int scale); public native static void loadBitmap(String path, int[] bitmap, int scale, int format, int width, int height);
public static void lockOrientation(Activity activity) { public static void lockOrientation(Activity activity) {
if (prevOrientation != -10) { if (prevOrientation != -10) {
...@@ -164,19 +167,47 @@ public class Utilities { ...@@ -164,19 +167,47 @@ public class Utilities {
WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE); WindowManager manager = (WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
if (manager != null && manager.getDefaultDisplay() != null) { if (manager != null && manager.getDefaultDisplay() != null) {
int rotation = manager.getDefaultDisplay().getRotation(); int rotation = manager.getDefaultDisplay().getRotation();
int orientation = activity.getResources().getConfiguration().orientation;
if (rotation == Surface.ROTATION_270) { if (rotation == Surface.ROTATION_270) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
if (Build.VERSION.SDK_INT >= 9) { if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else { } else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} }
}
} else if (rotation == Surface.ROTATION_90) { } else if (rotation == Surface.ROTATION_90) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_0) { } else if (rotation == Surface.ROTATION_0) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else { } else {
if (Build.VERSION.SDK_INT >= 9) { if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} }
} }
} }
...@@ -231,10 +262,17 @@ public class Utilities { ...@@ -231,10 +262,17 @@ public class Utilities {
public static File getCacheDir() { public static File getCacheDir() {
if (externalCacheNotAvailableState == 1 || externalCacheNotAvailableState == 0 && Environment.getExternalStorageState().startsWith(Environment.MEDIA_MOUNTED)) { if (externalCacheNotAvailableState == 1 || externalCacheNotAvailableState == 0 && Environment.getExternalStorageState().startsWith(Environment.MEDIA_MOUNTED)) {
externalCacheNotAvailableState = 1; externalCacheNotAvailableState = 1;
return ApplicationLoader.applicationContext.getExternalCacheDir(); File file = ApplicationLoader.applicationContext.getExternalCacheDir();
if (file != null) {
return file;
}
} }
externalCacheNotAvailableState = 2; externalCacheNotAvailableState = 2;
return ApplicationLoader.applicationContext.getCacheDir(); File file = ApplicationLoader.applicationContext.getCacheDir();
if (file != null) {
return file;
}
return new File("");
} }
public static String bytesToHex(byte[] bytes) { public static String bytesToHex(byte[] bytes) {
...@@ -668,7 +706,7 @@ public class Utilities { ...@@ -668,7 +706,7 @@ public class Utilities {
try { try {
String str; String str;
if (id >= 0) { if (id >= 0) {
str = String.format(Locale.US, "%d%d", id, UserConfig.clientUserId); str = String.format(Locale.US, "%d%d", id, UserConfig.getClientUserId());
} else { } else {
str = String.format(Locale.US, "%d", id); str = String.format(Locale.US, "%d", id);
} }
...@@ -707,6 +745,9 @@ public class Utilities { ...@@ -707,6 +745,9 @@ public class Utilities {
} }
public static String MD5(String md5) { public static String MD5(String md5) {
if (md5 == null) {
return null;
}
try { try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes()); byte[] array = md.digest(md5.getBytes());
...@@ -949,7 +990,12 @@ public class Utilities { ...@@ -949,7 +990,12 @@ public class Utilities {
} }
public static void checkForCrashes(Activity context) { public static void checkForCrashes(Activity context) {
CrashManager.register(context, BuildVars.HOCKEY_APP_HASH); CrashManager.register(context, BuildVars.HOCKEY_APP_HASH, new CrashManagerListener() {
@Override
public boolean includeDeviceData() {
return true;
}
});
} }
public static void checkForUpdates(Activity context) { public static void checkForUpdates(Activity context) {
...@@ -957,4 +1003,8 @@ public class Utilities { ...@@ -957,4 +1003,8 @@ public class Utilities {
UpdateManager.register(context, BuildVars.HOCKEY_APP_HASH); UpdateManager.register(context, BuildVars.HOCKEY_APP_HASH);
} }
} }
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
} }
...@@ -107,7 +107,7 @@ public class MessageObject { ...@@ -107,7 +107,7 @@ public class MessageObject {
if (who != null && fromUser != null) { if (who != null && fromUser != null) {
if (isFromMe()) { if (isFromMe()) {
messageText = LocaleController.getString("ActionYouKickUser", R.string.ActionYouKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name)); messageText = LocaleController.getString("ActionYouKickUser", R.string.ActionYouKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name));
} else if (message.action.user_id == UserConfig.clientUserId) { } else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = LocaleController.getString("ActionKickUserYou", R.string.ActionKickUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = LocaleController.getString("ActionKickUserYou", R.string.ActionKickUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else { } else {
messageText = LocaleController.getString("ActionKickUser", R.string.ActionKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = LocaleController.getString("ActionKickUser", R.string.ActionKickUser).replace("un2", Utilities.formatName(who.first_name, who.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
...@@ -124,7 +124,7 @@ public class MessageObject { ...@@ -124,7 +124,7 @@ public class MessageObject {
if (whoUser != null && fromUser != null) { if (whoUser != null && fromUser != null) {
if (isFromMe()) { if (isFromMe()) {
messageText = LocaleController.getString("ActionYouAddUser", R.string.ActionYouAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)); messageText = LocaleController.getString("ActionYouAddUser", R.string.ActionYouAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name));
} else if (message.action.user_id == UserConfig.clientUserId) { } else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = LocaleController.getString("ActionAddUserYou", R.string.ActionAddUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = LocaleController.getString("ActionAddUserYou", R.string.ActionAddUserYou).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
} else { } else {
messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", Utilities.formatName(whoUser.first_name, whoUser.last_name)).replace("un1", Utilities.formatName(fromUser.first_name, fromUser.last_name));
...@@ -206,7 +206,7 @@ public class MessageObject { ...@@ -206,7 +206,7 @@ public class MessageObject {
} }
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { } else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)message.date) * 1000)); String date = String.format("%s %s %s", LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.getString("OtherAt", R.string.OtherAt), LocaleController.formatterDay.format(((long)message.date) * 1000));
messageText = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.currentUser.first_name, date, message.action.title, message.action.address); messageText = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, message.action.title, message.action.address);
} else if (message.action instanceof TLRPC.TL_messageActionUserJoined) { } else if (message.action instanceof TLRPC.TL_messageActionUserJoined) {
if (fromUser != null) { if (fromUser != null) {
messageText = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(fromUser.first_name, fromUser.last_name)); messageText = LocaleController.formatString("NotificationContactJoined", R.string.NotificationContactJoined, Utilities.formatName(fromUser.first_name, fromUser.last_name));
...@@ -537,6 +537,6 @@ public class MessageObject { ...@@ -537,6 +537,6 @@ public class MessageObject {
} }
public boolean isFromMe() { public boolean isFromMe() {
return messageOwner.from_id == UserConfig.clientUserId; return messageOwner.from_id == UserConfig.getClientUserId();
} }
} }
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
package org.telegram.ui.Adapters; package org.telegram.ui.Adapters;
import android.database.DataSetObserver;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.BaseAdapter; import android.widget.BaseAdapter;
...@@ -38,4 +39,11 @@ public class BaseFragmentAdapter extends BaseAdapter { ...@@ -38,4 +39,11 @@ public class BaseFragmentAdapter extends BaseAdapter {
public View getView(int i, View view, ViewGroup viewGroup) { public View getView(int i, View view, ViewGroup viewGroup) {
return null; return null;
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }
...@@ -72,7 +72,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { ...@@ -72,7 +72,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter {
public void run() { public void run() {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>(); final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>();
contactsCopy.addAll(ContactsController.getInstance().contacts); contactsCopy.addAll(ContactsController.getInstance().contacts);
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.searchQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
String q = query.trim().toLowerCase(); String q = query.trim().toLowerCase();
...@@ -87,7 +87,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter { ...@@ -87,7 +87,7 @@ public class ContactsActivitySearchAdapter extends BaseFragmentAdapter {
for (TLRPC.TL_contact contact : contactsCopy) { for (TLRPC.TL_contact contact : contactsCopy) {
TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id); TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id);
if (user.first_name != null && user.first_name.toLowerCase().startsWith(q) || user.last_name != null && user.last_name.toLowerCase().startsWith(q)) { if (user.first_name != null && user.first_name.toLowerCase().startsWith(q) || user.last_name != null && user.last_name.toLowerCase().startsWith(q)) {
if (user.id == UserConfig.clientUserId) { if (user.id == UserConfig.getClientUserId()) {
continue; continue;
} }
resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q)); resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q));
......
...@@ -20,7 +20,7 @@ import android.content.SharedPreferences; ...@@ -20,7 +20,7 @@ import android.content.SharedPreferences;
import android.content.pm.PackageInfo; import android.content.pm.PackageInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.graphics.Bitmap; import android.graphics.drawable.Drawable;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Handler; import android.os.Handler;
import android.os.PowerManager; import android.os.PowerManager;
...@@ -29,7 +29,6 @@ import com.google.android.gms.common.ConnectionResult; ...@@ -29,7 +29,6 @@ import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.NotificationsService; import org.telegram.messenger.NotificationsService;
import org.telegram.messenger.BuildVars; import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
...@@ -41,7 +40,6 @@ import org.telegram.messenger.ScreenReceiver; ...@@ -41,7 +40,6 @@ import org.telegram.messenger.ScreenReceiver;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class ApplicationLoader extends Application { public class ApplicationLoader extends Application {
...@@ -52,12 +50,12 @@ public class ApplicationLoader extends Application { ...@@ -52,12 +50,12 @@ public class ApplicationLoader extends Application {
public static final String PROPERTY_REG_ID = "registration_id"; public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static long lastPauseTime; public static Drawable cachedWallpaper = null;
public static Bitmap cachedWallpaper = null;
public static volatile Context applicationContext = null; public static volatile Context applicationContext = null;
public static volatile Handler applicationHandler = null; public static volatile Handler applicationHandler = null;
private static volatile boolean applicationInited = false; private static volatile boolean applicationInited = false;
public static volatile boolean isScreenOn = false; public static volatile boolean isScreenOn = false;
public static void postInitApplication() { public static void postInitApplication() {
...@@ -93,7 +91,7 @@ public class ApplicationLoader extends Application { ...@@ -93,7 +91,7 @@ public class ApplicationLoader extends Application {
} }
UserConfig.loadConfig(); UserConfig.loadConfig();
if (UserConfig.currentUser != null) { if (UserConfig.getCurrentUser() != null) {
boolean changed = false; boolean changed = false;
SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE); SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);
int v = preferences.getInt("v", 0); int v = preferences.getInt("v", 0);
...@@ -122,8 +120,8 @@ public class ApplicationLoader extends Application { ...@@ -122,8 +120,8 @@ public class ApplicationLoader extends Application {
editor.commit(); editor.commit();
} }
MessagesController.getInstance().users.put(UserConfig.clientUserId, UserConfig.currentUser); MessagesController.getInstance().users.put(UserConfig.getClientUserId(), UserConfig.getCurrentUser());
ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.currentUser.phone); ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
ConnectionsManager.getInstance().initPushConnection(); ConnectionsManager.getInstance().initPushConnection();
} }
...@@ -135,7 +133,6 @@ public class ApplicationLoader extends Application { ...@@ -135,7 +133,6 @@ public class ApplicationLoader extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
lastPauseTime = System.currentTimeMillis();
applicationContext = getApplicationContext(); applicationContext = getApplicationContext();
applicationHandler = new Handler(applicationContext.getMainLooper()); applicationHandler = new Handler(applicationContext.getMainLooper());
...@@ -153,10 +150,14 @@ public class ApplicationLoader extends Application { ...@@ -153,10 +150,14 @@ public class ApplicationLoader extends Application {
applicationContext.startService(new Intent(applicationContext, NotificationsService.class)); applicationContext.startService(new Intent(applicationContext, NotificationsService.class));
if (android.os.Build.VERSION.SDK_INT >= 19) { if (android.os.Build.VERSION.SDK_INT >= 19) {
Calendar cal = Calendar.getInstance(); // Calendar cal = Calendar.getInstance();
// PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);
// AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
// alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent);
PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0); PendingIntent pintent = PendingIntent.getService(applicationContext, 0, new Intent(applicationContext, NotificationsService.class), 0);
AlarmManager alarm = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE); AlarmManager alarm = (AlarmManager)applicationContext.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30000, pintent); alarm.cancel(pintent);
} }
} else { } else {
stopPushService(); stopPushService();
...@@ -182,14 +183,6 @@ public class ApplicationLoader extends Application { ...@@ -182,14 +183,6 @@ public class ApplicationLoader extends Application {
} }
} }
public static void resetLastPauseTime() {
if (lastPauseTime != 0 && System.currentTimeMillis() - lastPauseTime > 5000) {
ContactsController.getInstance().checkContacts();
}
lastPauseTime = 0;
ConnectionsManager.getInstance().applicationMovedToForeground();
}
private void initPlayServices() { private void initPlayServices() {
if (checkPlayServices()) { if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this); gcm = GoogleCloudMessaging.getInstance(this);
...@@ -294,6 +287,7 @@ public class ApplicationLoader extends Application { ...@@ -294,6 +287,7 @@ public class ApplicationLoader extends Application {
UserConfig.pushString = regid; UserConfig.pushString = regid;
UserConfig.registeredForPush = !isNew; UserConfig.registeredForPush = !isNew;
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
if (UserConfig.getClientUserId() != 0) {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -301,6 +295,7 @@ public class ApplicationLoader extends Application { ...@@ -301,6 +295,7 @@ public class ApplicationLoader extends Application {
} }
}); });
} }
}
}); });
} }
......
...@@ -233,7 +233,7 @@ public class ChatBaseCell extends BaseCell { ...@@ -233,7 +233,7 @@ public class ChatBaseCell extends BaseCell {
newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.fwd_from_id); newUser = MessagesController.getInstance().users.get(currentMessageObject.messageOwner.fwd_from_id);
newNameString = null; newNameString = null;
if (drawForwardedName && currentMessageObject.messageOwner instanceof TLRPC.TL_messageForwarded) { if (newUser != null && drawForwardedName && currentMessageObject.messageOwner instanceof TLRPC.TL_messageForwarded) {
newNameString = Utilities.formatName(newUser.first_name, newUser.last_name); newNameString = Utilities.formatName(newUser.first_name, newUser.last_name);
} }
return currentForwardNameString == null && newNameString != null || currentForwardNameString != null && newNameString == null || currentForwardNameString != null && newNameString != null && !currentForwardNameString.equals(newNameString); return currentForwardNameString == null && newNameString != null || currentForwardNameString != null && newNameString == null || currentForwardNameString != null && newNameString != null && !currentForwardNameString.equals(newNameString);
......
...@@ -16,7 +16,6 @@ import android.text.Layout; ...@@ -16,7 +16,6 @@ import android.text.Layout;
import android.text.StaticLayout; import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.View;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
...@@ -28,8 +27,6 @@ import org.telegram.messenger.UserConfig; ...@@ -28,8 +27,6 @@ import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ImageReceiver; import org.telegram.ui.Views.ImageReceiver;
import java.lang.ref.WeakReference;
public class ChatOrUserCell extends BaseCell { public class ChatOrUserCell extends BaseCell {
private static TextPaint namePaint; private static TextPaint namePaint;
private static TextPaint nameEncryptedPaint; private static TextPaint nameEncryptedPaint;
...@@ -347,7 +344,7 @@ public class ChatOrUserCell extends BaseCell { ...@@ -347,7 +344,7 @@ public class ChatOrUserCell extends BaseCell {
onlineString = subLabel; onlineString = subLabel;
} else { } else {
onlineString = LocaleController.formatUserStatus(user); onlineString = LocaleController.formatUserStatus(user);
if (user != null && (user.id == UserConfig.clientUserId || user.status != null && user.status.expires > ConnectionsManager.getInstance().getCurrentTime())) { if (user != null && (user.id == UserConfig.getClientUserId() || user.status != null && user.status.expires > ConnectionsManager.getInstance().getCurrentTime())) {
currentOnlinePaint = onlinePaint; currentOnlinePaint = onlinePaint;
onlineString = LocaleController.getString("Online", R.string.Online); onlineString = LocaleController.getString("Online", R.string.Online);
} }
......
...@@ -423,7 +423,7 @@ public class DialogCell extends BaseCell { ...@@ -423,7 +423,7 @@ public class DialogCell extends BaseCell {
} else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) { } else if (encryptedChat instanceof TLRPC.TL_encryptedChatDiscarded) {
messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected); messageString = LocaleController.getString("EncryptionRejected", R.string.EncryptionRejected);
} else if (encryptedChat instanceof TLRPC.TL_encryptedChat) { } else if (encryptedChat instanceof TLRPC.TL_encryptedChat) {
if (encryptedChat.admin_id == UserConfig.clientUserId) { if (encryptedChat.admin_id == UserConfig.getClientUserId()) {
if (user != null && user.first_name != null) { if (user != null && user.first_name != null) {
messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, user.first_name); messageString = LocaleController.formatString("EncryptedChatStartedOutgoing", R.string.EncryptedChatStartedOutgoing, user.first_name);
} else { } else {
...@@ -546,8 +546,8 @@ public class DialogCell extends BaseCell { ...@@ -546,8 +546,8 @@ public class DialogCell extends BaseCell {
if (chat != null) { if (chat != null) {
nameString = chat.title; nameString = chat.title;
} else if (user != null) { } else if (user != null) {
if (user.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(user.id) == null) { if (user.id / 1000 != 777 && user.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(user.id) == null) {
if (ContactsController.getInstance().contactsDict.size() == 0 && (!ContactsController.getInstance().contactsLoaded || ContactsController.getInstance().loadingContacts)) { if (ContactsController.getInstance().contactsDict.size() == 0 && (!ContactsController.getInstance().contactsLoaded || ContactsController.getInstance().isLoadingContacts())) {
nameString = Utilities.formatName(user.first_name, user.last_name); nameString = Utilities.formatName(user.first_name, user.last_name);
} else { } else {
if (user.phone != null && user.phone.length() != 0) { if (user.phone != null && user.phone.length() != 0) {
......
...@@ -102,6 +102,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent ...@@ -102,6 +102,7 @@ public class ContactAddActivity extends BaseFragment implements NotificationCent
onlineText = (TextView)fragmentView.findViewById(R.id.settings_online); onlineText = (TextView)fragmentView.findViewById(R.id.settings_online);
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image); avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.processDetach = false;
phoneText = (TextView)fragmentView.findViewById(R.id.settings_name); phoneText = (TextView)fragmentView.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf"); Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
phoneText.setTypeface(typeface); phoneText.setTypeface(typeface);
......
...@@ -146,6 +146,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -146,6 +146,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
searchWas = false; searchWas = false;
ViewGroup group = (ViewGroup) listView.getParent(); ViewGroup group = (ViewGroup) listView.getParent();
listView.setAdapter(listViewAdapter); listView.setAdapter(listViewAdapter);
listViewAdapter.notifyDataSetChanged();
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(30), listView.getPaddingBottom()); listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(30), listView.getPaddingBottom());
} else { } else {
...@@ -171,6 +172,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -171,6 +172,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (listView != null) { if (listView != null) {
listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom()); listView.setPadding(Utilities.dp(16), listView.getPaddingTop(), Utilities.dp(16), listView.getPaddingBottom());
listView.setAdapter(searchListViewAdapter); listView.setAdapter(searchListViewAdapter);
searchListViewAdapter.notifyDataSetChanged();
if(android.os.Build.VERSION.SDK_INT >= 11) { if(android.os.Build.VERSION.SDK_INT >= 11) {
listView.setFastScrollAlwaysVisible(false); listView.setFastScrollAlwaysVisible(false);
} }
...@@ -205,7 +207,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -205,7 +207,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (searching && searchWas) { if (searching && searchWas) {
TLRPC.User user = searchListViewAdapter.getItem(i); TLRPC.User user = searchListViewAdapter.getItem(i);
if (user == null || user.id == UserConfig.clientUserId) { if (user == null || user.id == UserConfig.getClientUserId()) {
return; return;
} }
if (returnAsResult) { if (returnAsResult) {
...@@ -263,7 +265,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -263,7 +265,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
} }
if (user != null) { if (user != null) {
if (user.id == UserConfig.clientUserId) { if (user.id == UserConfig.getClientUserId()) {
return; return;
} }
if (returnAsResult) { if (returnAsResult) {
...@@ -288,7 +290,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -288,7 +290,7 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
if (!contact.phones.isEmpty()) { if (!contact.phones.isEmpty()) {
usePhone = contact.phones.get(0); usePhone = contact.phones.get(0);
} }
if (usePhone == null) { if (usePhone == null || getParentActivity() == null) {
return; return;
} }
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
...@@ -337,6 +339,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter ...@@ -337,6 +339,9 @@ public class ContactsActivity extends BaseFragment implements NotificationCenter
private void didSelectResult(final TLRPC.User user, boolean useAlert) { private void didSelectResult(final TLRPC.User user, boolean useAlert) {
if (useAlert && selectAlertString != null) { if (useAlert && selectAlertString != null) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name))); builder.setMessage(LocaleController.formatStringSimple(selectAlertString, Utilities.formatName(user.first_name, user.last_name)));
......
...@@ -22,6 +22,7 @@ import org.telegram.messenger.FileLog; ...@@ -22,6 +22,7 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
...@@ -85,7 +86,7 @@ public class CountrySelectActivity extends BaseFragment { ...@@ -85,7 +86,7 @@ public class CountrySelectActivity extends BaseFragment {
} }
arr.add(c); arr.add(c);
} }
reader.close();//TODO reader.close();
stream.close(); stream.close();
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
...@@ -280,7 +281,7 @@ public class CountrySelectActivity extends BaseFragment { ...@@ -280,7 +281,7 @@ public class CountrySelectActivity extends BaseFragment {
} }
private void processSearch(final String query) { private void processSearch(final String query) {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.searchQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -321,7 +322,7 @@ public class CountrySelectActivity extends BaseFragment { ...@@ -321,7 +322,7 @@ public class CountrySelectActivity extends BaseFragment {
}); });
} }
private class SearchAdapter extends BaseAdapter { private class SearchAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public SearchAdapter(Context context) { public SearchAdapter(Context context) {
......
...@@ -20,7 +20,6 @@ import android.view.LayoutInflater; ...@@ -20,7 +20,6 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
...@@ -28,7 +27,10 @@ import org.telegram.messenger.FileLog; ...@@ -28,7 +27,10 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ActionBar.BaseFragment; import org.telegram.ui.Views.ActionBar.BaseFragment;
...@@ -43,7 +45,8 @@ import java.util.HashMap; ...@@ -43,7 +45,8 @@ import java.util.HashMap;
public class DocumentSelectActivity extends BaseFragment { public class DocumentSelectActivity extends BaseFragment {
public static abstract interface DocumentSelectActivityDelegate { public static abstract interface DocumentSelectActivityDelegate {
public void didSelectFile(DocumentSelectActivity activity, String path, String name, String ext, long size); public void didSelectFile(DocumentSelectActivity activity, String path);
public void startDocumentSelectActivity();
} }
private ListView listView; private ListView listView;
...@@ -134,9 +137,16 @@ public class DocumentSelectActivity extends BaseFragment { ...@@ -134,9 +137,16 @@ public class DocumentSelectActivity extends BaseFragment {
public void onItemClick(int id) { public void onItemClick(int id) {
if (id == -1) { if (id == -1) {
finishFragment(); finishFragment();
} else if (id == 1) {
if (delegate != null) {
delegate.startDocumentSelectActivity();
}
finishFragment(false);
} }
} }
}); });
ActionBarMenu menu = actionBarLayer.createMenu();
ActionBarMenuItem item = menu.addItem(1, R.drawable.ic_ab_other);
fragmentView = inflater.inflate(R.layout.document_select_layout, container, false); fragmentView = inflater.inflate(R.layout.document_select_layout, container, false);
listAdapter = new ListAdapter(getParentActivity()); listAdapter = new ListAdapter(getParentActivity());
...@@ -176,7 +186,7 @@ public class DocumentSelectActivity extends BaseFragment { ...@@ -176,7 +186,7 @@ public class DocumentSelectActivity extends BaseFragment {
return; return;
} }
if (delegate != null) { if (delegate != null) {
delegate.didSelectFile(DocumentSelectActivity.this, file.getAbsolutePath(), item.title, item.ext, file.length()); delegate.didSelectFile(DocumentSelectActivity.this, file.getAbsolutePath());
} }
} }
} }
...@@ -290,7 +300,10 @@ public class DocumentSelectActivity extends BaseFragment { ...@@ -290,7 +300,10 @@ public class DocumentSelectActivity extends BaseFragment {
return true; return true;
} }
private void showErrorBox(String error){ private void showErrorBox(String error) {
if (getParentActivity() == null) {
return;
}
new AlertDialog.Builder(getParentActivity()) new AlertDialog.Builder(getParentActivity())
.setTitle(LocaleController.getString("AppName", R.string.AppName)) .setTitle(LocaleController.getString("AppName", R.string.AppName))
.setMessage(error) .setMessage(error)
...@@ -374,7 +387,7 @@ public class DocumentSelectActivity extends BaseFragment { ...@@ -374,7 +387,7 @@ public class DocumentSelectActivity extends BaseFragment {
return LocaleController.formatString("FreeOfTotal", R.string.FreeOfTotal, Utilities.formatFileSize(free), Utilities.formatFileSize(total)); return LocaleController.formatString("FreeOfTotal", R.string.FreeOfTotal, Utilities.formatFileSize(free), Utilities.formatFileSize(total));
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {
......
...@@ -382,7 +382,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -382,7 +382,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
public void run() { public void run() {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>(); final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>();
contactsCopy.addAll(ContactsController.getInstance().contacts); contactsCopy.addAll(ContactsController.getInstance().contacts);
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.searchQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (query.length() == 0) { if (query.length() == 0) {
...@@ -397,7 +397,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -397,7 +397,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
for (TLRPC.TL_contact contact : contactsCopy) { for (TLRPC.TL_contact contact : contactsCopy) {
TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id); TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id);
if (user.first_name.toLowerCase().startsWith(q) || user.last_name.toLowerCase().startsWith(q)) { if (user.first_name.toLowerCase().startsWith(q) || user.last_name.toLowerCase().startsWith(q)) {
if (user.id == UserConfig.clientUserId) { if (user.id == UserConfig.getClientUserId()) {
continue; continue;
} }
resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q)); resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q));
......
...@@ -176,7 +176,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -176,7 +176,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
button2.setOnClickListener(new View.OnClickListener() { button2.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items; CharSequence[] items;
...@@ -206,6 +208,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -206,6 +208,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
}); });
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image); avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.setImageResource(R.drawable.group_blue);
nameTextView = (EditText)fragmentView.findViewById(R.id.bubble_input_text); nameTextView = (EditText)fragmentView.findViewById(R.id.bubble_input_text);
nameTextView.setHint(LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder)); nameTextView.setHint(LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder));
...@@ -302,7 +305,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -302,7 +305,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
} }
Bundle args2 = new Bundle(); Bundle args2 = new Bundle();
args2.putInt("chat_id", (Integer)args[0]); args2.putInt("chat_id", (Integer)args[0]);
presentFragment(new ChatActivity(args2)); presentFragment(new ChatActivity(args2), true);
} }
}); });
} }
......
...@@ -10,6 +10,7 @@ package org.telegram.ui; ...@@ -10,6 +10,7 @@ package org.telegram.ui;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle; import android.os.Bundle;
import android.os.Parcelable; import android.os.Parcelable;
import android.support.v4.view.PagerAdapter; import android.support.v4.view.PagerAdapter;
...@@ -283,5 +284,12 @@ public class IntroActivity extends Activity { ...@@ -283,5 +284,12 @@ public class IntroActivity extends Activity {
@Override @Override
public void startUpdate(View arg0) { public void startUpdate(View arg0) {
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }
} }
...@@ -16,7 +16,6 @@ import android.view.View; ...@@ -16,7 +16,6 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AbsListView; import android.widget.AbsListView;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
...@@ -25,6 +24,7 @@ import org.telegram.messenger.FileLog; ...@@ -25,6 +24,7 @@ import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu; import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
...@@ -35,11 +35,11 @@ import java.util.Timer; ...@@ -35,11 +35,11 @@ import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
public class LanguageSelectActivity extends BaseFragment { public class LanguageSelectActivity extends BaseFragment {
private BaseAdapter listAdapter; private BaseFragmentAdapter listAdapter;
private ListView listView; private ListView listView;
private boolean searchWas; private boolean searchWas;
private boolean searching; private boolean searching;
private BaseAdapter searchListViewAdapter; private BaseFragmentAdapter searchListViewAdapter;
private TextView emptyTextView; private TextView emptyTextView;
private Timer searchTimer; private Timer searchTimer;
...@@ -143,7 +143,7 @@ public class LanguageSelectActivity extends BaseFragment { ...@@ -143,7 +143,7 @@ public class LanguageSelectActivity extends BaseFragment {
localeInfo = LocaleController.getInstance().sortedLanguages.get(i); localeInfo = LocaleController.getInstance().sortedLanguages.get(i);
} }
} }
if (localeInfo == null || localeInfo.pathToFile == null) { if (localeInfo == null || localeInfo.pathToFile == null || getParentActivity() == null) {
return false; return false;
} }
final LocaleController.LocaleInfo finalLocaleInfo = localeInfo; final LocaleController.LocaleInfo finalLocaleInfo = localeInfo;
...@@ -232,7 +232,7 @@ public class LanguageSelectActivity extends BaseFragment { ...@@ -232,7 +232,7 @@ public class LanguageSelectActivity extends BaseFragment {
} }
private void processSearch(final String query) { private void processSearch(final String query) {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.searchQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -265,7 +265,7 @@ public class LanguageSelectActivity extends BaseFragment { ...@@ -265,7 +265,7 @@ public class LanguageSelectActivity extends BaseFragment {
}); });
} }
private class SearchAdapter extends BaseAdapter { private class SearchAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public SearchAdapter(Context context) { public SearchAdapter(Context context) {
...@@ -341,7 +341,7 @@ public class LanguageSelectActivity extends BaseFragment { ...@@ -341,7 +341,7 @@ public class LanguageSelectActivity extends BaseFragment {
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment