Merge branch 'dev'

This commit is contained in:
DrKLO 2014-06-22 13:49:42 +04:00
commit 2cb6bb3e62
115 changed files with 4213 additions and 2396 deletions

View File

@ -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"
} }
} }

View File

@ -1,12 +1,13 @@
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 \

View File

@ -1,7 +1,6 @@
#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) {
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
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
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
} 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);
} else {
throwException(env, "AndroidBitmap_lockPixels() failed ! error=%d", i);
}
jpeg_finish_decompress(&cinfo); jpeg_finish_decompress(&cinfo);
} else {
throwException(env, "can't get bitmap buff");
}
} 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
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);
}
} }

View File

@ -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)

View File

@ -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 {
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 {
} }
} }
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 {
} }
} }
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 {
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 {
} }
public void commitTransaction() { public void commitTransaction() {
if (!inTransaction) {
return;
}
inTransaction = false; inTransaction = false;
commitTransaction(sqliteHandle); commitTransaction(sqliteHandle);
} }

View File

@ -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 {
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 {
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 {
} }
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);
}
}
}
} }
} }

View File

@ -44,6 +44,11 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
private ArrayList<RPCRequest> runningRequests = new ArrayList<RPCRequest>(); private ArrayList<RPCRequest> runningRequests = new ArrayList<RPCRequest>();
private ArrayList<Action> actionQueue = new ArrayList<Action>(); private ArrayList<Action> actionQueue = new ArrayList<Action>();
private ArrayList<Integer> unknownDatacenterIds = new ArrayList<Integer>();
private ArrayList<Integer> neededDatacenterIds = new ArrayList<Integer>();
private ArrayList<Integer> unauthorizedDatacenterIds = new ArrayList<Integer>();
final HashMap<Integer, ArrayList<NetworkMessage>> genericMessagesToDatacenters = new HashMap<Integer, ArrayList<NetworkMessage>>();
private TLRPC.TL_auth_exportedAuthorization movingAuthorization; private TLRPC.TL_auth_exportedAuthorization movingAuthorization;
public static final int DEFAULT_DATACENTER_ID = Integer.MAX_VALUE; public static final int DEFAULT_DATACENTER_ID = Integer.MAX_VALUE;
public static final int DC_UPDATE_TIME = 60 * 60; public static final int DC_UPDATE_TIME = 60 * 60;
@ -63,8 +68,13 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
private boolean paused = false; private boolean paused = false;
private long lastPingTime = System.currentTimeMillis(); private long lastPingTime = System.currentTimeMillis();
private long lastPushPingTime = System.currentTimeMillis(); private long lastPushPingTime = 0;
private boolean sendingPushPing = false;
private int nextSleepTimeout = 30000; private int nextSleepTimeout = 30000;
private long nextPingId = 0;
public static long lastPauseTime = System.currentTimeMillis();
public static boolean appPaused = true;
private static volatile ConnectionsManager Instance = null; private static volatile ConnectionsManager Instance = null;
public static ConnectionsManager getInstance() { public static ConnectionsManager getInstance() {
@ -87,7 +97,11 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
Utilities.stageQueue.handler.removeCallbacks(stageRunnable); Utilities.stageQueue.handler.removeCallbacks(stageRunnable);
t = System.currentTimeMillis(); t = System.currentTimeMillis();
if (datacenters != null) { if (datacenters != null) {
if (lastPushPingTime < System.currentTimeMillis() - 29000) { if (sendingPushPing && lastPushPingTime < System.currentTimeMillis() - 30000 || Math.abs(lastPushPingTime - System.currentTimeMillis()) > 60000 * 4) {
lastPushPingTime = 0;
sendingPushPing = false;
}
if (lastPushPingTime < System.currentTimeMillis() - 60000 * 3) {
lastPushPingTime = System.currentTimeMillis(); lastPushPingTime = System.currentTimeMillis();
Datacenter datacenter = datacenterWithId(currentDatacenterId); Datacenter datacenter = datacenterWithId(currentDatacenterId);
if (datacenter != null) { if (datacenter != null) {
@ -97,7 +111,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (ApplicationLoader.lastPauseTime != 0 && ApplicationLoader.lastPauseTime < currentTime - nextSleepTimeout) { if (lastPauseTime != 0 && lastPauseTime < currentTime - nextSleepTimeout) {
boolean dontSleep = false; boolean dontSleep = false;
for (RPCRequest request : runningRequests) { for (RPCRequest request : runningRequests) {
if (request.retryCount < 10 && (request.runningStartTime + 60 > (int)(currentTime / 1000)) && ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0)) { if (request.retryCount < 10 && (request.runningStartTime + 60 > (int)(currentTime / 1000)) && ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0)) {
@ -117,15 +131,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (!paused) { if (!paused) {
FileLog.e("tmessages", "pausing network and timers by sleep time = " + nextSleepTimeout); FileLog.e("tmessages", "pausing network and timers by sleep time = " + nextSleepTimeout);
for (Datacenter datacenter : datacenters.values()) { for (Datacenter datacenter : datacenters.values()) {
if (datacenter.connection != null) { datacenter.suspendConnections();
datacenter.connection.suspendConnection(true);
}
if (datacenter.uploadConnection != null) {
datacenter.uploadConnection.suspendConnection(true);
}
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.suspendConnection(true);
}
} }
} }
try { try {
@ -136,7 +142,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} else { } else {
ApplicationLoader.lastPauseTime += 30 * 1000; lastPauseTime += 30 * 1000;
FileLog.e("tmessages", "don't sleep 30 seconds because of upload or download request"); FileLog.e("tmessages", "don't sleep 30 seconds because of upload or download request");
} }
} }
@ -200,12 +206,12 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
@Override @Override
public void run() { public void run() {
if (paused) { if (paused) {
ApplicationLoader.lastPauseTime = System.currentTimeMillis(); lastPauseTime = System.currentTimeMillis();
nextSleepTimeout = 30000; nextSleepTimeout = 30000;
FileLog.e("tmessages", "wakeup network in background by received push"); FileLog.e("tmessages", "wakeup network in background");
} else if (ApplicationLoader.lastPauseTime != 0) { } else if (lastPauseTime != 0) {
ApplicationLoader.lastPauseTime = System.currentTimeMillis(); lastPauseTime = System.currentTimeMillis();
FileLog.e("tmessages", "reset sleep timeout by received push"); FileLog.e("tmessages", "reset sleep timeout");
} }
} }
}); });
@ -224,6 +230,28 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
}); });
} }
public static void resetLastPauseTime() {
if (appPaused) {
return;
}
FileLog.e("tmessages", "reset app pause time");
if (lastPauseTime != 0 && System.currentTimeMillis() - lastPauseTime > 5000) {
ContactsController.getInstance().checkContacts();
}
lastPauseTime = 0;
ConnectionsManager.getInstance().applicationMovedToForeground();
}
public static void setAppPaused(boolean value) {
appPaused = value;
FileLog.e("tmessages", "app paused = " + value);
if (!appPaused) {
resetLastPauseTime();
} else {
lastPauseTime = System.currentTimeMillis();
}
}
//================================================================================ //================================================================================
// Config and session manage // Config and session manage
//================================================================================ //================================================================================
@ -334,7 +362,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
} }
if (currentDatacenterId != 0 && UserConfig.clientActivated) { if (currentDatacenterId != 0 && UserConfig.isClientActivated()) {
Datacenter datacenter = datacenterWithId(currentDatacenterId); Datacenter datacenter = datacenterWithId(currentDatacenterId);
if (datacenter.authKey == null) { if (datacenter.authKey == null) {
currentDatacenterId = 0; currentDatacenterId = 0;
@ -441,15 +469,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
editor.putLong("pushSessionId", pushSessionId); editor.putLong("pushSessionId", pushSessionId);
ArrayList<Long> sessions = new ArrayList<Long>(); ArrayList<Long> sessions = new ArrayList<Long>();
if (currentDatacenter.connection != null) { currentDatacenter.getSessions(sessions);
sessions.add(currentDatacenter.connection.getSissionId());
}
if (currentDatacenter.downloadConnection != null) {
sessions.add(currentDatacenter.downloadConnection.getSissionId());
}
if (currentDatacenter.uploadConnection != null) {
sessions.add(currentDatacenter.uploadConnection.getSissionId());
}
if (!sessions.isEmpty()) { if (!sessions.isEmpty()) {
SerializedData data = new SerializedData(sessions.size() * 8 + 4); SerializedData data = new SerializedData(sessions.size() * 8 + 4);
@ -507,20 +527,36 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
Datacenter datacenter = datacenterWithId(currentDatacenterId); while (requestQueue.size() != 0) {
if (datacenter.connection != null) { RPCRequest request = requestQueue.get(0);
datacenter.connection.recreateSession(); requestQueue.remove(0);
if (request.completionBlock != null) {
TLRPC.TL_error implicitError = new TLRPC.TL_error();
implicitError.code = -1000;
implicitError.text = "";
request.completionBlock.run(null, implicitError);
} }
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.recreateSession();
} }
if (datacenter.uploadConnection != null) { while (runningRequests.size() != 0) {
datacenter.uploadConnection.recreateSession(); RPCRequest request = runningRequests.get(0);
runningRequests.remove(0);
if (request.completionBlock != null) {
TLRPC.TL_error implicitError = new TLRPC.TL_error();
implicitError.code = -1000;
implicitError.text = "";
request.completionBlock.run(null, implicitError);
}
}
pingIdToDate.clear();
quickAckIdToRequestIds.clear();
for (Datacenter datacenter : datacenters.values()) {
datacenter.recreateSessions();
datacenter.authorized = false;
} }
clearRequestsForRequestClass(RPCRequest.RPCRequestClassGeneric, datacenter); sessionsToDestroy.clear();
clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, datacenter); saveSession();
clearRequestsForRequestClass(RPCRequest.RPCRequestClassUploadMedia, datacenter);
} }
}); });
} }
@ -601,18 +637,8 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
addresses.add(ip_address); addresses.add(ip_address);
ports.put(ip_address, port); ports.put(ip_address, port);
exist.replaceAddressesAndPorts(addresses, ports); exist.replaceAddressesAndPorts(addresses, ports);
if (exist.connection != null) { exist.suspendConnections();
exist.connection.suspendConnection(true); updateDcSettings(dc);
}
if (exist.uploadConnection != null) {
exist.uploadConnection.suspendConnection(true);
}
if (exist.downloadConnection != null) {
exist.downloadConnection.suspendConnection(true);
}
if (dc == 1) {
updateDcSettings(1);
}
} }
} }
}); });
@ -632,7 +658,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
datacenter.pushConnection.connect(); datacenter.pushConnection.connect();
generatePing(datacenter, true); generatePing(datacenter, true);
} else { } else {
if (UserConfig.clientActivated && !UserConfig.registeredForInternalPush) { if (UserConfig.isClientActivated() && !UserConfig.registeredForInternalPush) {
registerForPush(); registerForPush();
} }
} }
@ -652,15 +678,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
for (HashMap.Entry<Integer, Datacenter> entry : datacenters.entrySet()) { for (HashMap.Entry<Integer, Datacenter> entry : datacenters.entrySet()) {
Datacenter datacenter = entry.getValue(); Datacenter datacenter = entry.getValue();
datacenter.overridePort = 8888; datacenter.overridePort = 8888;
if (datacenter.connection != null) { datacenter.suspendConnections();
datacenter.connection.suspendConnection(true);
}
if (datacenter.uploadConnection != null) {
datacenter.uploadConnection.suspendConnection(true);
}
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.suspendConnection(true);
}
} }
} else { } else {
for (HashMap.Entry<Integer, Datacenter> entry : datacenters.entrySet()) { for (HashMap.Entry<Integer, Datacenter> entry : datacenters.entrySet()) {
@ -722,7 +740,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
updatingDcSettings = false; updatingDcSettings = false;
} }
}, null, true, RPCRequest.RPCRequestClassEnableUnauthorized | RPCRequest.RPCRequestClassGeneric, dcNum == 0 ? currentDatacenterId : dcNum); }, null, true, RPCRequest.RPCRequestClassEnableUnauthorized | RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin, dcNum == 0 ? currentDatacenterId : dcNum);
} }
public long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCProgressDelegate progressBlock, boolean requiresCompletion, int requestClass) { public long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCProgressDelegate progressBlock, boolean requiresCompletion, int requestClass) {
@ -748,7 +766,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
invoke.device_model = "Android unknown"; invoke.device_model = "Android unknown";
} }
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
invoke.app_version = pInfo.versionName; invoke.app_version = pInfo.versionName + " (" + pInfo.versionCode + ")";
if (invoke.app_version == null) { if (invoke.app_version == null) {
invoke.app_version = "App version unknown"; invoke.app_version = "App version unknown";
} }
@ -782,8 +800,12 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
return object; return object;
} }
public static volatile long nextCallToken = 0; public static volatile long nextCallToken = 1;
long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCProgressDelegate progressBlock, final RPCRequest.RPCQuickAckDelegate quickAckBlock, final boolean requiresCompletion, final int requestClass, final int datacenterId) { long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCProgressDelegate progressBlock, final RPCRequest.RPCQuickAckDelegate quickAckBlock, final boolean requiresCompletion, final int requestClass, final int datacenterId) {
if (!UserConfig.isClientActivated() && (requestClass & RPCRequest.RPCRequestClassWithoutLogin) == 0) {
FileLog.e("tmessages", "can't do request without login " + rpc);
return 0;
}
final long requestToken = nextCallToken++; final long requestToken = nextCallToken++;
@ -806,7 +828,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
requestQueue.add(request); requestQueue.add(request);
if (paused && ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0)) { if (paused && ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0 || (request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0)) {
ApplicationLoader.lastPauseTime = System.currentTimeMillis(); lastPauseTime = System.currentTimeMillis();
nextSleepTimeout = 30000; nextSleepTimeout = 30000;
FileLog.e("tmessages", "wakeup by download or upload request"); FileLog.e("tmessages", "wakeup by download or upload request");
} }
@ -819,6 +841,13 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
public void cancelRpc(final long token, final boolean notifyServer) { public void cancelRpc(final long token, final boolean notifyServer) {
cancelRpc(token, notifyServer, false);
}
public void cancelRpc(final long token, final boolean notifyServer, final boolean ifNotSent) {
if (token == 0) {
return;
}
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -835,6 +864,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
} }
if (!ifNotSent) {
for (int i = 0; i < runningRequests.size(); i++) { for (int i = 0; i < runningRequests.size(); i++) {
RPCRequest request = runningRequests.get(i); RPCRequest request = runningRequests.get(i);
if (request.token == token) { if (request.token == token) {
@ -861,6 +891,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
FileLog.d("tmessages", "***** Warning: cancelling unknown request"); FileLog.d("tmessages", "***** Warning: cancelling unknown request");
} }
} }
}
}); });
} }
@ -868,20 +899,17 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
try { try {
ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager cm = (ConnectivityManager)ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo(); NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) { if (netInfo != null && (netInfo.isConnectedOrConnecting() || netInfo.isRoaming() || netInfo.isAvailable())) {
return true; return true;
} }
netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (netInfo.isConnected()) {
return true;
}
if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { if (netInfo != null && (netInfo.isConnectedOrConnecting() || netInfo.isRoaming())) {
return true; return true;
} else { } else {
netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { if(netInfo != null && (netInfo.isConnectedOrConnecting() || netInfo.isRoaming())) {
return true; return true;
} }
} }
@ -911,123 +939,25 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
private void processRequestQueue(int requestClass, int _datacenterId) { private void processRequestQueue(int requestClass, int _datacenterId) {
final HashMap<Integer, Integer> activeTransportTokens = new HashMap<Integer, Integer>(); boolean haveNetwork = true;//isNetworkOnline();
final ArrayList<Integer> transportsToResume = new ArrayList<Integer>();
final HashMap<Integer, Integer> activeDownloadTransportTokens = new HashMap<Integer, Integer>(); genericMessagesToDatacenters.clear();
final ArrayList<Integer> downloadTransportsToResume = new ArrayList<Integer>(); unknownDatacenterIds.clear();
neededDatacenterIds.clear();
unauthorizedDatacenterIds.clear();
final HashMap<Integer, Integer> activeUploadTransportTokens = new HashMap<Integer, Integer>(); TcpConnection genericConnection = null;
final ArrayList<Integer> uploadTransportsToResume = new ArrayList<Integer>(); Datacenter defaultDatacenter = datacenterWithId(currentDatacenterId);
if (defaultDatacenter != null) {
for (Datacenter datacenter : datacenters.values()) { genericConnection = defaultDatacenter.getGenericConnection(this);
if (datacenter.connection != null) {
int channelToken = datacenter.connection.channelToken;
if (channelToken != 0) {
activeTransportTokens.put(datacenter.datacenterId, channelToken);
} }
}
if (datacenter.downloadConnection != null) {
int channelToken = datacenter.downloadConnection.channelToken;
if (channelToken != 0) {
activeDownloadTransportTokens.put(datacenter.datacenterId, channelToken);
}
}
if (datacenter.uploadConnection != null) {
int channelToken = datacenter.uploadConnection.channelToken;
if (channelToken != 0) {
activeUploadTransportTokens.put(datacenter.datacenterId, channelToken);
}
}
}
for (RPCRequest request : runningRequests) {
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeTransportTokens.containsKey(requestDatacenter.datacenterId) && !transportsToResume.contains(requestDatacenter.datacenterId)) {
transportsToResume.add(requestDatacenter.datacenterId);
}
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeDownloadTransportTokens.containsKey(requestDatacenter.datacenterId) && !downloadTransportsToResume.contains(requestDatacenter.datacenterId)) {
downloadTransportsToResume.add(requestDatacenter.datacenterId);
}
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeUploadTransportTokens.containsKey(requestDatacenter.datacenterId) && !uploadTransportsToResume.contains(requestDatacenter.datacenterId)) {
uploadTransportsToResume.add(requestDatacenter.datacenterId);
}
}
}
for (RPCRequest request : requestQueue) {
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeTransportTokens.containsKey(requestDatacenter.datacenterId) && !transportsToResume.contains(requestDatacenter.datacenterId)) {
transportsToResume.add(requestDatacenter.datacenterId);
}
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeDownloadTransportTokens.containsKey(requestDatacenter.datacenterId) && !downloadTransportsToResume.contains(requestDatacenter.datacenterId)) {
downloadTransportsToResume.add(requestDatacenter.datacenterId);
}
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
Datacenter requestDatacenter = datacenterWithId(request.runningDatacenterId);
if (requestDatacenter != null && !activeUploadTransportTokens.containsKey(requestDatacenter.datacenterId) && !uploadTransportsToResume.contains(requestDatacenter.datacenterId)) {
uploadTransportsToResume.add(requestDatacenter.datacenterId);
}
}
}
boolean haveNetwork = true;//activeTransportTokens.size() != 0 || isNetworkOnline();
if (!activeTransportTokens.containsKey(currentDatacenterId) && !transportsToResume.contains(currentDatacenterId)) {
transportsToResume.add(currentDatacenterId);
}
for (int it : transportsToResume) {
Datacenter datacenter = datacenterWithId(it);
if (datacenter.authKey != null) {
if (datacenter.connection == null) {
datacenter.connection = new TcpConnection(datacenter.datacenterId);
datacenter.connection.delegate = this;
datacenter.connection.transportRequestClass = RPCRequest.RPCRequestClassGeneric;
}
datacenter.connection.connect();
}
}
for (int it : downloadTransportsToResume) {
Datacenter datacenter = datacenterWithId(it);
if (datacenter.authKey != null) {
if (datacenter.downloadConnection == null) {
datacenter.downloadConnection = new TcpConnection(datacenter.datacenterId);
datacenter.downloadConnection.delegate = this;
datacenter.downloadConnection.transportRequestClass = RPCRequest.RPCRequestClassDownloadMedia;
}
datacenter.downloadConnection.connect();
}
}
for (int it : uploadTransportsToResume) {
Datacenter datacenter = datacenterWithId(it);
if (datacenter.authKey != null) {
if (datacenter.uploadConnection == null) {
datacenter.uploadConnection = new TcpConnection(datacenter.datacenterId);
datacenter.uploadConnection.delegate = this;
datacenter.uploadConnection.transportRequestClass = RPCRequest.RPCRequestClassUploadMedia;
}
datacenter.uploadConnection.connect();
}
}
final HashMap<Integer, ArrayList<NetworkMessage>> genericMessagesToDatacenters = new HashMap<Integer, ArrayList<NetworkMessage>>();
final ArrayList<Integer> unknownDatacenterIds = new ArrayList<Integer>();
final ArrayList<Integer> neededDatacenterIds = new ArrayList<Integer>();
final ArrayList<Integer> unauthorizedDatacenterIds = new ArrayList<Integer>();
int currentTime = (int)(System.currentTimeMillis() / 1000); int currentTime = (int)(System.currentTimeMillis() / 1000);
for (int i = 0; i < runningRequests.size(); i++) { for (int i = 0; i < runningRequests.size(); i++) {
RPCRequest request = runningRequests.get(i); RPCRequest request = runningRequests.get(i);
if (updatingDcSettings && datacenters.size() > 1 && request.rawRequest instanceof TLRPC.TL_help_getConfig) { if (datacenters.size() > 1) {
if (updatingDcSettings && request.rawRequest instanceof TLRPC.TL_help_getConfig) {
if (updatingDcStartTime < currentTime - 60) { if (updatingDcStartTime < currentTime - 60) {
FileLog.e("tmessages", "move TL_help_getConfig to requestQueue"); FileLog.e("tmessages", "move TL_help_getConfig to requestQueue");
requestQueue.add(request); requestQueue.add(request);
@ -1035,6 +965,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
i--; i--;
continue; continue;
} }
} else if (request.rawRequest instanceof TLRPC.TL_auth_sendCode || request.rawRequest instanceof TLRPC.TL_auth_signIn || request.rawRequest instanceof TLRPC.TL_auth_signUp) {
}
} }
int datacenterId = request.runningDatacenterId; int datacenterId = request.runningDatacenterId;
@ -1070,48 +1003,27 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
continue; continue;
} }
Integer tokenIt = activeTransportTokens.get(requestDatacenter.datacenterId); float maxTimeout = 8.0f;
int datacenterTransportToken = tokenIt != null ? tokenIt : 0;
Integer uploadTokenIt = activeUploadTransportTokens.get(requestDatacenter.datacenterId);
int datacenterUploadTransportToken = uploadTokenIt != null ? uploadTokenIt : 0;
Integer downloadTokenIt = activeDownloadTransportTokens.get(requestDatacenter.datacenterId);
int datacenterDownloadTransportToken = downloadTokenIt != null ? downloadTokenIt : 0;
double maxTimeout = 8.0;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
if (datacenterTransportToken == 0) {
continue;
}
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
if (!haveNetwork) {
FileLog.d("tmessages", "Don't have any network connection, skipping download request");
continue;
}
if (datacenterDownloadTransportToken == 0) {
continue;
}
maxTimeout = 40.0;
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
if (!haveNetwork) {
FileLog.d("tmessages", "Don't have any network connection, skipping upload request");
continue;
}
if (datacenterUploadTransportToken == 0) {
continue;
}
maxTimeout = 30.0;
}
TcpConnection connection = null; TcpConnection connection = null;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
connection = requestDatacenter.connection; connection = requestDatacenter.getGenericConnection(this);
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
connection = requestDatacenter.downloadConnection; int num = (request.flags & RPCRequest.RPCRequestClassDownloadMedia2) != 0 ? 1 : 0;
connection = requestDatacenter.getDownloadConnection(num, this);
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0 ) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0 ) {
connection = requestDatacenter.uploadConnection; connection = requestDatacenter.getUploadConnection(this);
}
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
if (connection.channelToken == 0) {
continue;
}
} else {
if (!haveNetwork || connection.channelToken == 0) {
continue;
}
maxTimeout = 30.0f;
} }
boolean forceThisRequest = (request.flags & requestClass) != 0 && (_datacenterId == Integer.MIN_VALUE || requestDatacenter.datacenterId == _datacenterId); boolean forceThisRequest = (request.flags & requestClass) != 0 && (_datacenterId == Integer.MIN_VALUE || requestDatacenter.datacenterId == _datacenterId);
@ -1128,19 +1040,14 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (((Math.abs(currentTime - request.runningStartTime) > maxTimeout) && (currentTime > request.runningMinStartTime || Math.abs(currentTime - request.runningMinStartTime) > 60.0)) || forceThisRequest) { if (((Math.abs(currentTime - request.runningStartTime) > maxTimeout) && (currentTime > request.runningMinStartTime || Math.abs(currentTime - request.runningMinStartTime) > 60.0)) || forceThisRequest) {
if (!forceThisRequest && request.transportChannelToken > 0) { if (!forceThisRequest && request.transportChannelToken > 0) {
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0 && datacenterTransportToken == request.transportChannelToken) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0 && request.transportChannelToken == connection.channelToken) {
FileLog.d("tmessages", "Request token is valid, not retrying " + request.rawRequest); FileLog.d("tmessages", "Request token is valid, not retrying " + request.rawRequest);
continue; continue;
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) { } else {
if (datacenterDownloadTransportToken != 0 && request.transportChannelToken == datacenterDownloadTransportToken) { if (connection.channelToken != 0 && request.transportChannelToken == connection.channelToken) {
FileLog.d("tmessages", "Request download token is valid, not retrying " + request.rawRequest); FileLog.d("tmessages", "Request download token is valid, not retrying " + request.rawRequest);
continue; continue;
} }
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
if (datacenterUploadTransportToken != 0 && request.transportChannelToken == datacenterUploadTransportToken) {
FileLog.d("tmessages", "Request upload token is valid, not retrying " + request.rawRequest);
continue;
}
} }
} }
@ -1162,15 +1069,15 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
request.runningStartTime = currentTime; request.runningStartTime = currentTime;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
request.transportChannelToken = datacenterTransportToken; request.transportChannelToken = connection.channelToken;
addMessageToDatacenter(genericMessagesToDatacenters, requestDatacenter.datacenterId, networkMessage); addMessageToDatacenter(requestDatacenter.datacenterId, networkMessage);
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
request.transportChannelToken = datacenterDownloadTransportToken; request.transportChannelToken = connection.channelToken;
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>(); ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage); arr.add(networkMessage);
proceedToSendingMessages(arr, connection, false); proceedToSendingMessages(arr, connection, false);
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
request.transportChannelToken = datacenterUploadTransportToken; request.transportChannelToken = connection.channelToken;
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>(); ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage); arr.add(networkMessage);
proceedToSendingMessages(arr, connection, false); proceedToSendingMessages(arr, connection, false);
@ -1180,7 +1087,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
boolean updatingState = MessagesController.getInstance().updatingState; boolean updatingState = MessagesController.getInstance().updatingState;
if (activeTransportTokens.get(currentDatacenterId) != null) { if (genericConnection != null && genericConnection.channelToken != 0) {
if (!updatingState) { if (!updatingState) {
Datacenter currentDatacenter = datacenterWithId(currentDatacenterId); Datacenter currentDatacenter = datacenterWithId(currentDatacenterId);
@ -1197,7 +1104,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
NetworkMessage networkMessage = new NetworkMessage(); NetworkMessage networkMessage = new NetworkMessage();
networkMessage.protoMessage = wrapMessage(destroySession, currentDatacenter.connection, false); networkMessage.protoMessage = wrapMessage(destroySession, currentDatacenter.connection, false);
if (networkMessage.protoMessage != null) { if (networkMessage.protoMessage != null) {
addMessageToDatacenter(genericMessagesToDatacenters, currentDatacenter.datacenterId, networkMessage); addMessageToDatacenter(currentDatacenter.datacenterId, networkMessage);
} }
} }
} }
@ -1266,7 +1173,17 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
continue; continue;
} }
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0 && activeTransportTokens.get(requestDatacenter.datacenterId) == null) { TcpConnection connection = null;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
connection = requestDatacenter.getGenericConnection(this);
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
int num = (request.flags & RPCRequest.RPCRequestClassDownloadMedia2) != 0 ? 1 : 0;
connection = requestDatacenter.getDownloadConnection(num, this);
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
connection = requestDatacenter.getUploadConnection(this);
}
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0 && connection.channelToken == 0) {
continue; continue;
} }
@ -1276,40 +1193,19 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (request.requiresCompletion) { if (request.requiresCompletion) {
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
if (genericRunningRequestCount >= 60) if (genericRunningRequestCount >= 60) {
continue; continue;
}
genericRunningRequestCount++; genericRunningRequestCount++;
Integer tokenIt = activeTransportTokens.get(requestDatacenter.datacenterId);
request.transportChannelToken = tokenIt != null ? tokenIt : 0;
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
if (!haveNetwork) { if (!haveNetwork || uploadRunningRequestCount >= 5) {
FileLog.d("tmessages", "Don't have any network connection, skipping upload request");
continue; continue;
} }
if (uploadRunningRequestCount >= 5) {
continue;
}
Integer uploadTokenIt = activeUploadTransportTokens.get(requestDatacenter.datacenterId);
request.transportChannelToken = uploadTokenIt != null ? uploadTokenIt : 0;
uploadRunningRequestCount++; uploadRunningRequestCount++;
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) { } else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
if (!haveNetwork) { if (!haveNetwork || downloadRunningRequestCount >= 5) {
FileLog.d("tmessages", "Don't have any network connection, skipping download request");
continue; continue;
} }
if (downloadRunningRequestCount >= 5) {
continue;
}
Integer downloadTokenIt = activeDownloadTransportTokens.get(requestDatacenter.datacenterId);
request.transportChannelToken = downloadTokenIt != null ? downloadTokenIt : 0;
downloadRunningRequestCount++; downloadRunningRequestCount++;
} }
} }
@ -1323,15 +1219,6 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
int requestLength = os.length(); int requestLength = os.length();
if (requestLength != 0) { if (requestLength != 0) {
TcpConnection connection = null;
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
connection = requestDatacenter.connection;
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
connection = requestDatacenter.downloadConnection;
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
connection = requestDatacenter.uploadConnection;
}
if (canCompress) { if (canCompress) {
try { try {
byte[] data = Utilities.compress(os.toByteArray()); byte[] data = Utilities.compress(os.toByteArray());
@ -1361,22 +1248,17 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
request.runningMessageSeqNo = networkMessage.protoMessage.seqno; request.runningMessageSeqNo = networkMessage.protoMessage.seqno;
request.serializedLength = requestLength; request.serializedLength = requestLength;
request.runningStartTime = (int)(System.currentTimeMillis() / 1000); request.runningStartTime = (int)(System.currentTimeMillis() / 1000);
request.transportChannelToken = connection.channelToken;
if (request.requiresCompletion) { if (request.requiresCompletion) {
runningRequests.add(request); runningRequests.add(request);
} }
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
addMessageToDatacenter(genericMessagesToDatacenters, requestDatacenter.datacenterId, networkMessage); addMessageToDatacenter(requestDatacenter.datacenterId, networkMessage);
} else if ((request.flags & RPCRequest.RPCRequestClassDownloadMedia) != 0) {
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage);
proceedToSendingMessages(arr, requestDatacenter.downloadConnection, false);
} else if ((request.flags & RPCRequest.RPCRequestClassUploadMedia) != 0) {
ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage);
proceedToSendingMessages(arr, requestDatacenter.uploadConnection, false);
} else { } else {
FileLog.e("tmessages", "***** Error: request " + request.rawRequest + " has undefined session"); ArrayList<NetworkMessage> arr = new ArrayList<NetworkMessage>();
arr.add(networkMessage);
proceedToSendingMessages(arr, connection, false);
} }
} else { } else {
FileLog.e("tmessages", "***** Couldn't serialize " + request.rawRequest); FileLog.e("tmessages", "***** Couldn't serialize " + request.rawRequest);
@ -1510,7 +1392,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
for (int num : unauthorizedDatacenterIds) { for (int num : unauthorizedDatacenterIds) {
if (num != currentDatacenterId && num != movingToDatacenterId && UserConfig.clientUserId != 0) { if (num != currentDatacenterId && num != movingToDatacenterId && UserConfig.isClientActivated()) {
boolean notFound = true; boolean notFound = true;
for (Action actor : actionQueue) { for (Action actor : actionQueue) {
if (actor instanceof ExportAuthorizationAction) { if (actor instanceof ExportAuthorizationAction) {
@ -1530,11 +1412,11 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
} }
void addMessageToDatacenter(HashMap<Integer, ArrayList<NetworkMessage>> pMap, int datacenterId, NetworkMessage message) { void addMessageToDatacenter(int datacenterId, NetworkMessage message) {
ArrayList<NetworkMessage> arr = pMap.get(datacenterId); ArrayList<NetworkMessage> arr = genericMessagesToDatacenters.get(datacenterId);
if (arr == null) { if (arr == null) {
arr = new ArrayList<NetworkMessage>(); arr = new ArrayList<NetworkMessage>();
pMap.put(datacenterId, arr); genericMessagesToDatacenters.put(datacenterId, arr);
} }
arr.add(message); arr.add(message);
} }
@ -1786,7 +1668,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
saveSession(); saveSession();
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric, datacenter.datacenterId); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin, datacenter.datacenterId);
} }
void messagesConfirmed(final long requestMsgId) { void messagesConfirmed(final long requestMsgId) {
@ -1839,7 +1721,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
req.system_version = "SDK " + Build.VERSION.SDK_INT; req.system_version = "SDK " + Build.VERSION.SDK_INT;
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
req.app_version = pInfo.versionName; req.app_version = pInfo.versionName + " (" + pInfo.versionCode + ")";
if (req.app_version == null) { if (req.app_version == null) {
req.app_version = "App version unknown"; req.app_version = "App version unknown";
} }
@ -1918,11 +1800,11 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
saveSession(); saveSession();
if (datacenter.datacenterId == currentDatacenterId && UserConfig.clientActivated) { if (datacenter.datacenterId == currentDatacenterId && UserConfig.isClientActivated()) {
if ((connection.transportRequestClass & RPCRequest.RPCRequestClassGeneric) != 0) { if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
MessagesController.getInstance().getDifference();
} else if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
registerForPush(); registerForPush();
} else if ((connection.transportRequestClass & RPCRequest.RPCRequestClassGeneric) != 0) {
MessagesController.getInstance().getDifference();
} }
} }
connection.addProcessedSession(newSession.unique_id); connection.addProcessedSession(newSession.unique_id);
@ -1947,17 +1829,18 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
connection.addProcessedMessageId(innerMessageId); connection.addProcessedMessageId(innerMessageId);
} }
} else if (message instanceof TLRPC.TL_pong) { } else if (message instanceof TLRPC.TL_pong) {
if (UserConfig.clientActivated && !UserConfig.registeredForInternalPush && (connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) { if (UserConfig.isClientActivated() && !UserConfig.registeredForInternalPush && (connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
registerForPush(); registerForPush();
} }
TLRPC.TL_pong pong = (TLRPC.TL_pong)message; if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) == 0) {
TLRPC.TL_pong pong = (TLRPC.TL_pong) message;
long pingId = pong.ping_id; long pingId = pong.ping_id;
ArrayList<Long> itemsToDelete = new ArrayList<Long>(); ArrayList<Long> itemsToDelete = new ArrayList<Long>();
for (Long pid : pingIdToDate.keySet()) { for (Long pid : pingIdToDate.keySet()) {
if (pid == pingId) { if (pid == pingId) {
int time = pingIdToDate.get(pid); int time = pingIdToDate.get(pid);
int pingTime = (int)(System.currentTimeMillis() / 1000) - time; int pingTime = (int) (System.currentTimeMillis() / 1000) - time;
if (Math.abs(pingTime) < 10) { if (Math.abs(pingTime) < 10) {
currentPingTime = (pingTime + currentPingTime) / 2; currentPingTime = (pingTime + currentPingTime) / 2;
@ -1965,7 +1848,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (messageId != 0) { if (messageId != 0) {
long timeMessage = getTimeFromMsgId(messageId); long timeMessage = getTimeFromMsgId(messageId);
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
timeDifference = (int)((timeMessage - currentTime) / 1000 - currentPingTime / 2.0); timeDifference = (int) ((timeMessage - currentTime) / 1000 - currentPingTime / 2.0);
} }
} }
itemsToDelete.add(pid); itemsToDelete.add(pid);
@ -1976,6 +1859,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
for (Long pid : itemsToDelete) { for (Long pid : itemsToDelete) {
pingIdToDate.remove(pid); pingIdToDate.remove(pid);
} }
} else {
sendingPushPing = false;
}
} else if (message instanceof TLRPC.TL_futuresalts) { } else if (message instanceof TLRPC.TL_futuresalts) {
TLRPC.TL_futuresalts futureSalts = (TLRPC.TL_futuresalts)message; TLRPC.TL_futuresalts futureSalts = (TLRPC.TL_futuresalts)message;
long requestMid = futureSalts.req_msg_id; long requestMid = futureSalts.req_msg_id;
@ -2143,6 +2029,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
implicitError = new TLRPC.TL_error(); implicitError = new TLRPC.TL_error();
implicitError.code = -1000; implicitError.code = -1000;
implicitError.text = "";
} }
} }
@ -2159,7 +2046,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
isError = true; isError = true;
if (datacenter.datacenterId == currentDatacenterId || datacenter.datacenterId == movingToDatacenterId) { if (datacenter.datacenterId == currentDatacenterId || datacenter.datacenterId == movingToDatacenterId) {
if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) { if ((request.flags & RPCRequest.RPCRequestClassGeneric) != 0) {
if (UserConfig.clientActivated) { if (UserConfig.isClientActivated()) {
UserConfig.clearConfig(); UserConfig.clearConfig();
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
@ -2237,16 +2124,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
timeDifference = (int)((time - currentTime) / 1000 - currentPingTime / 2.0); timeDifference = (int)((time - currentTime) / 1000 - currentPingTime / 2.0);
} }
if (datacenter.connection != null) { datacenter.recreateSessions();
datacenter.connection.recreateSession();
}
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.recreateSession();
}
if (datacenter.uploadConnection != null) {
datacenter.uploadConnection.recreateSession();
}
saveSession(); saveSession();
lastOutgoingMessageId = 0; lastOutgoingMessageId = 0;
@ -2333,7 +2211,6 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
} }
static long nextPingId = 0;
private ByteBufferDesc generatePingData(TcpConnection connection) { private ByteBufferDesc generatePingData(TcpConnection connection) {
if (connection == null) { if (connection == null) {
return null; return null;
@ -2341,8 +2218,23 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
TLRPC.TL_ping_delay_disconnect ping = new TLRPC.TL_ping_delay_disconnect(); TLRPC.TL_ping_delay_disconnect ping = new TLRPC.TL_ping_delay_disconnect();
ping.ping_id = nextPingId++; ping.ping_id = nextPingId++;
if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
ping.disconnect_delay = 60 * 7;
} else {
ping.disconnect_delay = 35; ping.disconnect_delay = 35;
pingIdToDate.put(ping.ping_id, (int)(System.currentTimeMillis() / 1000)); pingIdToDate.put(ping.ping_id, (int) (System.currentTimeMillis() / 1000));
if (pingIdToDate.size() > 20) {
ArrayList<Long> itemsToDelete = new ArrayList<Long>();
for (Long pid : pingIdToDate.keySet()) {
if (pid < nextPingId - 10) {
itemsToDelete.add(pid);
}
}
for (Long pid : itemsToDelete) {
pingIdToDate.remove(pid);
}
}
}
NetworkMessage networkMessage = new NetworkMessage(); NetworkMessage networkMessage = new NetworkMessage();
networkMessage.protoMessage = wrapMessage(ping, connection, false); networkMessage.protoMessage = wrapMessage(ping, connection, false);
@ -2362,6 +2254,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (connection != null && (push || !push && connection.channelToken != 0)) { if (connection != null && (push || !push && connection.channelToken != 0)) {
ByteBufferDesc transportData = generatePingData(connection); ByteBufferDesc transportData = generatePingData(connection);
if (transportData != null) { if (transportData != null) {
if (push) {
sendingPushPing = true;
}
connection.sendData(null, transportData, false); connection.sendData(null, transportData, false);
} }
} }
@ -2543,6 +2438,9 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
NotificationCenter.getInstance().postNotificationName(703, stateCopy); NotificationCenter.getInstance().postNotificationName(703, stateCopy);
} }
}); });
} else if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
sendingPushPing = false;
lastPushPingTime = System.currentTimeMillis() - 60000 * 3 + 5000;
} }
} }
@ -2550,9 +2448,17 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
public void tcpConnectionConnected(TcpConnection connection) { public void tcpConnectionConnected(TcpConnection connection) {
Datacenter datacenter = datacenterWithId(connection.getDatacenterId()); Datacenter datacenter = datacenterWithId(connection.getDatacenterId());
if (datacenter.authKey != null) { if (datacenter.authKey != null) {
if ((connection.transportRequestClass & RPCRequest.RPCRequestClassPush) != 0) {
sendingPushPing = false;
lastPushPingTime = System.currentTimeMillis() - 60000 * 3 + 10000;
} else {
if (paused && connection.getDatacenterId() == currentDatacenterId && (connection.transportRequestClass & RPCRequest.RPCRequestClassGeneric) != 0) {
resumeNetworkMaybe();
}
processRequestQueue(connection.transportRequestClass, connection.getDatacenterId()); processRequestQueue(connection.transportRequestClass, connection.getDatacenterId());
} }
} }
}
@Override @Override
public void tcpConnectionQuiackAckReceived(TcpConnection connection, int ack) { public void tcpConnectionQuiackAckReceived(TcpConnection connection, int ack) {
@ -2598,6 +2504,13 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
}); });
} }
} }
if (length == 4) {
int error = data.readInt32();
FileLog.e("tmessages", "mtproto error = " + error);
connection.suspendConnection(true);
connection.connect();
return;
}
Datacenter datacenter = datacenterWithId(connection.getDatacenterId()); Datacenter datacenter = datacenterWithId(connection.getDatacenterId());
long keyId = data.readInt64(); long keyId = data.readInt64();
@ -2721,7 +2634,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, currentDatacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, currentDatacenter);
clearRequestsForRequestClass(RPCRequest.RPCRequestClassUploadMedia, currentDatacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassUploadMedia, currentDatacenter);
if (UserConfig.clientUserId != 0) { if (UserConfig.isClientActivated()) {
TLRPC.TL_auth_exportAuthorization exportAuthorization = new TLRPC.TL_auth_exportAuthorization(); TLRPC.TL_auth_exportAuthorization exportAuthorization = new TLRPC.TL_auth_exportAuthorization();
exportAuthorization.dc_id = datacenterId; exportAuthorization.dc_id = datacenterId;
@ -2732,7 +2645,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
movingAuthorization = (TLRPC.TL_auth_exportedAuthorization)response; movingAuthorization = (TLRPC.TL_auth_exportedAuthorization)response;
authorizeOnMovingDatacenter(); authorizeOnMovingDatacenter();
} else { } else {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
moveToDatacenter(datacenterId); moveToDatacenter(datacenterId);
@ -2740,7 +2653,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
}, 1000); }, 1000);
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric, currentDatacenterId); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin, currentDatacenterId);
} else { } else {
authorizeOnMovingDatacenter(); authorizeOnMovingDatacenter();
} }
@ -2755,15 +2668,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
return; return;
} }
if (datacenter.connection != null) { datacenter.recreateSessions();
datacenter.connection.recreateSession();
}
if (datacenter.downloadConnection != null) {
datacenter.downloadConnection.recreateSession();
}
if (datacenter.uploadConnection != null) {
datacenter.uploadConnection.recreateSession();
}
clearRequestsForRequestClass(RPCRequest.RPCRequestClassGeneric, datacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassGeneric, datacenter);
clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, datacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, datacenter);
@ -2778,7 +2683,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (movingAuthorization != null) { if (movingAuthorization != null) {
TLRPC.TL_auth_importAuthorization importAuthorization = new TLRPC.TL_auth_importAuthorization(); TLRPC.TL_auth_importAuthorization importAuthorization = new TLRPC.TL_auth_importAuthorization();
importAuthorization.id = UserConfig.clientUserId; importAuthorization.id = UserConfig.getClientUserId();
importAuthorization.bytes = movingAuthorization.bytes; importAuthorization.bytes = movingAuthorization.bytes;
performRpc(importAuthorization, new RPCRequest.RPCRequestDelegate() { performRpc(importAuthorization, new RPCRequest.RPCRequestDelegate() {
@Override @Override
@ -2790,7 +2695,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
moveToDatacenter(movingToDatacenterId); moveToDatacenter(movingToDatacenterId);
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric, datacenter.datacenterId); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin, datacenter.datacenterId);
} else { } else {
authorizedOnMovingDatacenter(); authorizedOnMovingDatacenter();
} }
@ -2828,16 +2733,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
if (eactor.datacenter.datacenterId == currentDatacenterId || eactor.datacenter.datacenterId == movingToDatacenterId) { if (eactor.datacenter.datacenterId == currentDatacenterId || eactor.datacenter.datacenterId == movingToDatacenterId) {
timeDifference = (Integer)params.get("timeDifference"); timeDifference = (Integer)params.get("timeDifference");
eactor.datacenter.recreateSessions();
if (eactor.datacenter.connection != null) {
eactor.datacenter.connection.recreateSession();
}
if (eactor.datacenter.downloadConnection != null) {
eactor.datacenter.downloadConnection.recreateSession();
}
if (eactor.datacenter.uploadConnection != null) {
eactor.datacenter.uploadConnection.recreateSession();
}
clearRequestsForRequestClass(RPCRequest.RPCRequestClassGeneric, eactor.datacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassGeneric, eactor.datacenter);
clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, eactor.datacenter); clearRequestsForRequestClass(RPCRequest.RPCRequestClassDownloadMedia, eactor.datacenter);

View File

@ -30,7 +30,8 @@ import java.util.concurrent.ConcurrentHashMap;
public class ContactsController { public class ContactsController {
private Account currentAccount; private Account currentAccount;
public boolean loadingContacts = false; private boolean loadingContacts = false;
private static final Integer loadContactsSync = 1;
private boolean ignoreChanges = false; private boolean ignoreChanges = false;
private boolean contactsSyncInProgress = false; private boolean contactsSyncInProgress = false;
private final Integer observerLock = 1; private final Integer observerLock = 1;
@ -118,10 +119,10 @@ public class ContactsController {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext); AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
Account[] accounts = am.getAccountsByType("org.telegram.account"); Account[] accounts = am.getAccountsByType("org.telegram.account");
boolean recreateAccount = false; boolean recreateAccount = false;
if (UserConfig.currentUser != null) { if (UserConfig.isClientActivated()) {
if (accounts.length == 1) { if (accounts.length == 1) {
Account acc = accounts[0]; Account acc = accounts[0];
if (!acc.name.equals(UserConfig.currentUser.phone)) { if (!acc.name.equals(UserConfig.getCurrentUser().phone)) {
recreateAccount = true; recreateAccount = true;
} else { } else {
currentAccount = acc; currentAccount = acc;
@ -139,9 +140,9 @@ public class ContactsController {
for (Account c : accounts) { for (Account c : accounts) {
am.removeAccount(c, null, null); am.removeAccount(c, null, null);
} }
if (UserConfig.currentUser != null) { if (UserConfig.isClientActivated()) {
try { try {
currentAccount = new Account(UserConfig.currentUser.phone, "org.telegram.account"); currentAccount = new Account(UserConfig.getCurrentUser().phone, "org.telegram.account");
am.addAccountExplicitly(currentAccount, "", null); am.addAccountExplicitly(currentAccount, "", null);
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -180,6 +181,10 @@ public class ContactsController {
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
} }
try { try {
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone._COUNT}, null, null, null); pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone._COUNT}, null, null, null);
@ -194,6 +199,10 @@ public class ContactsController {
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
} }
try { try {
pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._COUNT}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, null); pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._COUNT}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, null);
@ -208,6 +217,10 @@ public class ContactsController {
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
} }
try { try {
pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, ContactsContract.Data._ID + " desc LIMIT 1"); pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, ContactsContract.Data._ID + " desc LIMIT 1");
@ -222,6 +235,10 @@ public class ContactsController {
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -230,13 +247,20 @@ public class ContactsController {
} }
public void readContacts() { public void readContacts() {
synchronized (loadContactsSync) {
if (loadingContacts) { if (loadingContacts) {
return; return;
} }
loadingContacts = true;
}
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!contacts.isEmpty() || contactsLoaded) { if (!contacts.isEmpty() || contactsLoaded) {
synchronized (loadContactsSync) {
loadingContacts = false;
}
return; return;
} }
loadContacts(true, false); loadContacts(true, false);
@ -423,15 +447,15 @@ public class ContactsController {
public void run() { public void run() {
boolean disableDeletion = true; //disable contacts deletion, because phone numbers can't be compared due to different numbers format boolean disableDeletion = true; //disable contacts deletion, because phone numbers can't be compared due to different numbers format
if (schedule) { /*if (schedule) {
try { try {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext); AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
Account[] accounts = am.getAccountsByType("org.telegram.account"); Account[] accounts = am.getAccountsByType("org.telegram.account");
boolean recreateAccount = false; boolean recreateAccount = false;
if (UserConfig.currentUser != null) { if (UserConfig.isClientActivated()) {
if (accounts.length != 1) { if (accounts.length != 1) {
FileLog.e("tmessages", "detected account deletion!"); FileLog.e("tmessages", "detected account deletion!");
currentAccount = new Account(UserConfig.currentUser.phone, "org.telegram.account"); currentAccount = new Account(UserConfig.getCurrentUser().phone, "org.telegram.account");
am.addAccountExplicitly(currentAccount, "", null); am.addAccountExplicitly(currentAccount, "", null);
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
@ -444,7 +468,7 @@ public class ContactsController {
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }*/
boolean request = requ; boolean request = requ;
if (request && first) { if (request && first) {
@ -748,13 +772,16 @@ public class ContactsController {
}); });
} }
public boolean isLoadingContacts() {
synchronized (loadContactsSync) {
return loadingContacts;
}
}
public void loadContacts(boolean fromCache, boolean cacheEmpty) { public void loadContacts(boolean fromCache, boolean cacheEmpty) {
Utilities.RunOnUIThread(new Runnable() { synchronized (loadContactsSync) {
@Override
public void run() {
loadingContacts = true; loadingContacts = true;
} }
});
if (fromCache) { if (fromCache) {
FileLog.e("tmessages", "load contacts from cache"); FileLog.e("tmessages", "load contacts from cache");
MessagesStorage.getInstance().getContacts(); MessagesStorage.getInstance().getContacts();
@ -776,7 +803,9 @@ public class ContactsController {
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
synchronized (loadContactsSync) {
loadingContacts = false; loadingContacts = false;
}
NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded); NotificationCenter.getInstance().postNotificationName(MessagesController.contactsDidLoaded);
} }
}); });
@ -800,8 +829,8 @@ public class ContactsController {
MessagesController.getInstance().users.putIfAbsent(user.id, user); MessagesController.getInstance().users.putIfAbsent(user.id, user);
} else { } else {
MessagesController.getInstance().users.put(user.id, user); MessagesController.getInstance().users.put(user.id, user);
if (user.id == UserConfig.clientUserId) { if (user.id == UserConfig.getClientUserId()) {
UserConfig.currentUser = user; UserConfig.setCurrentUser(user);
} }
} }
} }
@ -840,7 +869,7 @@ public class ContactsController {
} }
for (TLRPC.TL_contact contact : contactsArr) { for (TLRPC.TL_contact contact : contactsArr) {
if (usersDict.get(contact.user_id) == null && contact.user_id != UserConfig.clientUserId) { if (usersDict.get(contact.user_id) == null && contact.user_id != UserConfig.getClientUserId()) {
loadContacts(false, true); loadContacts(false, true);
FileLog.e("tmessages", "contacts are broken, load from server"); FileLog.e("tmessages", "contacts are broken, load from server");
return; return;
@ -953,8 +982,10 @@ public class ContactsController {
usersSectionsDict = sectionsDict; usersSectionsDict = sectionsDict;
sortedUsersSectionsArray = sortedSectionsArray; sortedUsersSectionsArray = sortedSectionsArray;
if (from != 2) { if (from != 2) {
synchronized (loadContactsSync) {
loadingContacts = false; loadingContacts = false;
} }
}
performWriteContactsToPhoneBook(); performWriteContactsToPhoneBook();
updateUnregisteredContacts(contactsArr); updateUnregisteredContacts(contactsArr);
@ -1180,7 +1211,7 @@ public class ContactsController {
private void performWriteContactsToPhoneBook() { private void performWriteContactsToPhoneBook() {
final ArrayList<TLRPC.TL_contact> contactsArray = new ArrayList<TLRPC.TL_contact>(); final ArrayList<TLRPC.TL_contact> contactsArray = new ArrayList<TLRPC.TL_contact>();
contactsArray.addAll(contacts); contactsArray.addAll(contacts);
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
performWriteContactsToPhoneBookInternal(contactsArray); performWriteContactsToPhoneBookInternal(contactsArray);
@ -1237,7 +1268,7 @@ public class ContactsController {
} }
for (final Integer uid : contactsTD) { for (final Integer uid : contactsTD) {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
deleteContactFromPhoneBook(uid); deleteContactFromPhoneBook(uid);
@ -1467,7 +1498,7 @@ public class ContactsController {
// } // }
for (final TLRPC.User u : res.users) { for (final TLRPC.User u : res.users) {
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
addContactToPhoneBook(u, true); addContactToPhoneBook(u, true);
@ -1533,7 +1564,7 @@ public class ContactsController {
return; return;
} }
MessagesStorage.getInstance().deleteContacts(uids); MessagesStorage.getInstance().deleteContacts(uids);
Utilities.globalQueue.postRunnable(new Runnable() { Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
for (TLRPC.User user : users) { for (TLRPC.User user : users) {

View File

@ -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 {
} }
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;
}
} }

View File

@ -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 {
} }
} }
public void cleanupQueue() {
if (handler != null) {
handler.removeCallbacksAndMessages(null);
}
}
public void run() { public void run() {
Looper.prepare(); Looper.prepare();
synchronized (handlerSyncObject) { synchronized (handlerSyncObject) {

View File

@ -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 {
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 {
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 {
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 {
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 {
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 {
@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 {
} }
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 {
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 {
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;
} }
} }

View File

@ -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);
} }
} }

View File

@ -12,7 +12,6 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.os.Build; import android.os.Build;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Log;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
@ -26,7 +25,7 @@ import java.nio.channels.FileChannel;
import java.util.Scanner; import java.util.Scanner;
public class FileLoadOperation { public class FileLoadOperation {
private int downloadChunkSize = 1024 * 32; private int downloadChunkSize = 1024 * 256;
public int datacenter_id; public int datacenter_id;
public TLRPC.InputFileLocation location; public TLRPC.InputFileLocation location;
@ -39,6 +38,13 @@ public class FileLoadOperation {
private byte[] key; private byte[] key;
private byte[] iv; private byte[] iv;
private long requestToken = 0; private long requestToken = 0;
private long requestToken2 = 0;
private int requestProgress = 0;
private int requestProgress2 = 0;
private int nextDownloadOffset = 0;
private TLRPC.TL_upload_file delayedRes = null;
private int delayedResOffset = 0;
private int delayedResTokenNum = 0;
private File cacheFileTemp; private File cacheFileTemp;
private File cacheFileFinal; private File cacheFileFinal;
@ -79,12 +85,7 @@ public class FileLoadOperation {
} }
public FileLoadOperation(TLRPC.Video videoLocation) { public FileLoadOperation(TLRPC.Video videoLocation) {
if (videoLocation instanceof TLRPC.TL_video) { if (videoLocation instanceof TLRPC.TL_videoEncrypted) {
location = new TLRPC.TL_inputVideoFileLocation();
datacenter_id = videoLocation.dc_id;
location.id = videoLocation.id;
location.access_hash = videoLocation.access_hash;
} else if (videoLocation instanceof TLRPC.TL_videoEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation(); location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = videoLocation.id; location.id = videoLocation.id;
location.access_hash = videoLocation.access_hash; location.access_hash = videoLocation.access_hash;
@ -92,6 +93,11 @@ public class FileLoadOperation {
iv = new byte[32]; iv = new byte[32];
System.arraycopy(videoLocation.iv, 0, iv, 0, iv.length); System.arraycopy(videoLocation.iv, 0, iv, 0, iv.length);
key = videoLocation.key; key = videoLocation.key;
} else if (videoLocation instanceof TLRPC.TL_video) {
location = new TLRPC.TL_inputVideoFileLocation();
datacenter_id = videoLocation.dc_id;
location.id = videoLocation.id;
location.access_hash = videoLocation.access_hash;
} }
ext = ".mp4"; ext = ".mp4";
} }
@ -115,12 +121,7 @@ public class FileLoadOperation {
} }
public FileLoadOperation(TLRPC.Document documentLocation) { public FileLoadOperation(TLRPC.Document documentLocation) {
if (documentLocation instanceof TLRPC.TL_document) { if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location = new TLRPC.TL_inputDocumentFileLocation();
datacenter_id = documentLocation.dc_id;
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
} else if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation(); location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = documentLocation.id; location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash; location.access_hash = documentLocation.access_hash;
@ -128,6 +129,11 @@ public class FileLoadOperation {
iv = new byte[32]; iv = new byte[32];
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length); System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
key = documentLocation.key; key = documentLocation.key;
} else if (documentLocation instanceof TLRPC.TL_document) {
location = new TLRPC.TL_inputDocumentFileLocation();
datacenter_id = documentLocation.dc_id;
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
} }
ext = documentLocation.file_name; ext = documentLocation.file_name;
int idx = -1; int idx = -1;
@ -336,7 +342,7 @@ public class FileLoadOperation {
cacheFileTemp = new File(Utilities.getCacheDir(), fileNameTemp); cacheFileTemp = new File(Utilities.getCacheDir(), fileNameTemp);
if (cacheFileTemp.exists()) { if (cacheFileTemp.exists()) {
downloadedBytes = (int)cacheFileTemp.length(); downloadedBytes = (int)cacheFileTemp.length();
downloadedBytes = downloadedBytes / 1024 * 1024; nextDownloadOffset = downloadedBytes = downloadedBytes / 1024 * 1024;
} }
if (fileNameIv != null) { if (fileNameIv != null) {
cacheIvTemp = new File(Utilities.getCacheDir(), fileNameIv); cacheIvTemp = new File(Utilities.getCacheDir(), fileNameIv);
@ -377,6 +383,11 @@ public class FileLoadOperation {
if (httpUrl != null) { if (httpUrl != null) {
startDownloadHTTPRequest(); startDownloadHTTPRequest();
} else { } else {
if (totalBytesCount >= 1024 * 1024) {
downloadChunkSize = 1024 * 256;
} else {
downloadChunkSize = 1024 * 32;
}
startDownloadRequest(); startDownloadRequest();
} }
} }
@ -388,8 +399,9 @@ public class FileLoadOperation {
} }
state = 2; state = 2;
cleanup(); cleanup();
if (httpUrl == null && requestToken != 0) { if (httpUrl == null) {
ConnectionsManager.getInstance().cancelRpc(requestToken, true); ConnectionsManager.getInstance().cancelRpc(requestToken, true);
ConnectionsManager.getInstance().cancelRpc(requestToken2, true);
} }
delegate.didFailedLoadingFile(FileLoadOperation.this); delegate.didFailedLoadingFile(FileLoadOperation.this);
} }
@ -423,6 +435,12 @@ public class FileLoadOperation {
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
if (delayedRes != null) {
delayedRes.disableFree = false;
delayedRes.freeResources();
delayedRes = null;
}
} }
} }
@ -594,26 +612,26 @@ public class FileLoadOperation {
} }
} }
private void startDownloadRequest() { private void processRequestResult(TLRPC.TL_upload_file res, TLRPC.TL_error error, int dowloadOffset, int tokenNum) {
if (state != 1) {
return;
}
TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
//if (totalBytesCount == -1) {
// req.offset = 0;
// req.limit = 0;
//} else {
req.offset = downloadedBytes;
req.limit = downloadChunkSize;
//}
requestToken = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
requestToken = 0;
if (error == null) { if (error == null) {
TLRPC.TL_upload_file res = (TLRPC.TL_upload_file)response;
try { try {
if (downloadedBytes != dowloadOffset) {
if (delayedRes != null) {
FileLog.e("tmessages", "something went wrong!");
}
delayedRes = res;
delayedRes.disableFree = true;
delayedResOffset = dowloadOffset;
delayedResTokenNum = tokenNum;
return;
} else {
if (tokenNum == 0) {
requestToken = 0;
} else if (tokenNum == 1) {
requestToken2 = 0;
}
}
if (res.bytes.limit() == 0) { if (res.bytes.limit() == 0) {
onFinishLoadingFile(); onFinishLoadingFile();
return; return;
@ -630,9 +648,20 @@ public class FileLoadOperation {
fiv.write(iv); fiv.write(iv);
} }
downloadedBytes += res.bytes.limit(); downloadedBytes += res.bytes.limit();
if (totalBytesCount > 0) { if (totalBytesCount > 0 && state == 1) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount)); delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)downloadedBytes / (float)totalBytesCount));
} }
if(delayedRes != null && res != delayedRes) {
TLRPC.TL_upload_file temp = delayedRes;
processRequestResult(temp, null, delayedResOffset, delayedResTokenNum);
if (delayedRes != null) {
delayedRes.disableFree = false;
delayedRes.freeResources();
delayedRes = null;
}
}
if (downloadedBytes % downloadChunkSize == 0 || totalBytesCount > 0 && totalBytesCount != downloadedBytes) { if (downloadedBytes % downloadChunkSize == 0 || totalBytesCount > 0 && totalBytesCount != downloadedBytes) {
startDownloadRequest(); startDownloadRequest();
} else { } else {
@ -659,6 +688,7 @@ public class FileLoadOperation {
delegate.didFailedLoadingFile(FileLoadOperation.this); delegate.didFailedLoadingFile(FileLoadOperation.this);
} else { } else {
datacenter_id = val; datacenter_id = val;
nextDownloadOffset = 0;
startDownloadRequest(); startDownloadRequest();
} }
} else if (error.text.contains("OFFSET_INVALID")) { } else if (error.text.contains("OFFSET_INVALID")) {
@ -675,20 +705,78 @@ public class FileLoadOperation {
delegate.didFailedLoadingFile(FileLoadOperation.this); delegate.didFailedLoadingFile(FileLoadOperation.this);
} }
} else { } else {
if (location != null) {
FileLog.e("tmessages", "" + location + " id = " + location.id + " access_hash = " + location.access_hash + " volume_id = " + location.local_id + " secret = " + location.secret);
}
cleanup(); cleanup();
delegate.didFailedLoadingFile(FileLoadOperation.this); delegate.didFailedLoadingFile(FileLoadOperation.this);
} }
} }
} }
private void processRequestProgress() {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) (downloadedBytes + requestProgress + requestProgress2) / (float) totalBytesCount));
}
private void startDownloadRequest() {
if (state != 1) {
return;
}
if (requestToken == 0) {
requestProgress = 0;
if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) {
return;
}
final TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = nextDownloadOffset;
req.limit = downloadChunkSize;
nextDownloadOffset += downloadChunkSize;
final long time = System.currentTimeMillis();
requestToken = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
processRequestResult((TLRPC.TL_upload_file) response, error, req.offset, 0);
}
}, new RPCRequest.RPCProgressDelegate() { }, new RPCRequest.RPCProgressDelegate() {
@Override @Override
public void progress(int length, int progress) { public void progress(int length, int progress) {
if (totalBytesCount > 0) { if (state == 1) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)(downloadedBytes + progress) / (float)totalBytesCount)); requestProgress = progress;
} else if (totalBytesCount == -1) { if (totalBytesCount == -1) {
delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float)(progress) / (float)length)); delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) (progress) / (float) length));
} else if (totalBytesCount > 0) {
processRequestProgress();
}
} }
} }
}, null, true, RPCRequest.RPCRequestClassDownloadMedia, datacenter_id); }, null, true, RPCRequest.RPCRequestClassDownloadMedia, datacenter_id);
} }
if (totalBytesCount > 0 && requestToken2 == 0) {
requestProgress2 = 0;
if (totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount) {
return;
}
final long time = System.currentTimeMillis();
final TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile();
req.location = location;
req.offset = nextDownloadOffset;
req.limit = downloadChunkSize;
nextDownloadOffset += downloadChunkSize;
requestToken2 = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
processRequestResult((TLRPC.TL_upload_file) response, error, req.offset, 1);
}
}, new RPCRequest.RPCProgressDelegate() {
@Override
public void progress(int length, int progress) {
if (state == 1) {
requestProgress2 = progress;
processRequestProgress();
}
}
}, null, true, RPCRequest.RPCRequestClassDownloadMedia | RPCRequest.RPCRequestClassDownloadMedia2, datacenter_id);
}
}
} }

View File

@ -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 {
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 {
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 {
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 {
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);
} }
}); });
} }

View File

@ -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 {
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 {
} }
} }
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;
} }

View File

@ -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 {
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 {
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 {
} }
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 {
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 {
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 {
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 {

View File

@ -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;
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 {
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() {

View File

@ -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
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
} }
}); });
} }
}); }).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
} }
@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
@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)) {

View File

@ -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
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
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
}); });
} }
} }
}); }).start();
} }
} }
@ -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
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);

View File

@ -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 {
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 {
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 {
} }
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 {
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 {
cacheFile.delete(); cacheFile.delete();
cacheFile = null; cacheFile = null;
} }
storageQueue.cleanupQueue();
openDatabase(); openDatabase();
} }
}); });
@ -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 {
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 {
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 {
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 {
} }
} }
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 {
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 {
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));

View File

@ -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 {
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 {
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 {
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 {
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);
}
} }
} }

View File

@ -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);

View File

@ -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;
} }
} }

View File

@ -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 () {
} }

View File

@ -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 {
@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 {
@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 {
} }
} }
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 {
} }
} }
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 {
@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 {
@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;
}
} }

View File

@ -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 {
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);
} }

View File

@ -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 {
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 {
} }
} }
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 {
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 {
} 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 {
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;

View File

@ -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;
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 {
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 {
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 {
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) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); if (orientation == Configuration.ORIENTATION_PORTRAIT) {
} else if (rotation == Surface.ROTATION_0) { if (Build.VERSION.SDK_INT >= 9) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (rotation == Surface.ROTATION_0) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
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 {
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 {
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 {
} }
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 {
} }
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 {
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;
}
} }

View File

@ -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 {
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 {
} }
} 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 {
} }
public boolean isFromMe() { public boolean isFromMe() {
return messageOwner.from_id == UserConfig.clientUserId; return messageOwner.from_id == UserConfig.getClientUserId();
} }
} }

View File

@ -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 {
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);
}
}
} }

View File

@ -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 {
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));

View File

@ -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;
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;
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 {
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 {
} }
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 {
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 {
@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 {
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 {
} }
} }
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 {
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 {
} }
}); });
} }
}
}); });
} }

View File

@ -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);

View File

@ -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;
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 {
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);
} }

View File

@ -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 {
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) {

View File

@ -21,7 +21,7 @@ import android.content.res.Configuration;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable;
import android.media.MediaPlayer; import android.media.MediaPlayer;
import android.media.ThumbnailUtils; import android.media.ThumbnailUtils;
import android.net.Uri; import android.net.Uri;
@ -50,7 +50,6 @@ import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap; import android.webkit.MimeTypeMap;
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.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageButton; import android.widget.ImageButton;
@ -60,6 +59,7 @@ import android.widget.PopupWindow;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import org.telegram.PhoneFormat.PhoneFormat; import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
@ -78,6 +78,7 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.ChatAudioCell; import org.telegram.ui.Cells.ChatAudioCell;
import org.telegram.ui.Cells.ChatBaseCell; import org.telegram.ui.Cells.ChatBaseCell;
import org.telegram.ui.Cells.ChatMediaCell; import org.telegram.ui.Cells.ChatMediaCell;
@ -511,7 +512,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (str.length() != 0) { if (str.length() != 0) {
str += "\n"; str += "\n";
} }
if (messageObject.messageOwner.message != null) {
str += messageObject.messageOwner.message; str += messageObject.messageOwner.message;
} else {
str += messageObject.messageText;
}
} }
if (str.length() != 0) { if (str.length() != 0) {
if (android.os.Build.VERSION.SDK_INT < 11) { if (android.os.Build.VERSION.SDK_INT < 11) {
@ -643,34 +648,42 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
updateContactStatus(); updateContactStatus();
ImageView backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int selectedBackground = preferences.getInt("selectedBackground", 1000001); int selectedBackground = preferences.getInt("selectedBackground", 1000001);
int selectedColor = preferences.getInt("selectedColor", 0); int selectedColor = preferences.getInt("selectedColor", 0);
if (selectedColor != 0) { if (selectedColor != 0) {
backgroundImage.setBackgroundColor(selectedColor); contentView.setBackgroundColor(selectedColor);
chatListView.setCacheColorHint(selectedColor); chatListView.setCacheColorHint(selectedColor);
} else { } else {
chatListView.setCacheColorHint(0); chatListView.setCacheColorHint(0);
try {
if (selectedBackground == 1000001) { if (selectedBackground == 1000001) {
backgroundImage.setImageResource(R.drawable.background_hd); ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd);
} else { } else {
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
if (toFile.exists()) { if (toFile.exists()) {
if (ApplicationLoader.cachedWallpaper != null) { if (ApplicationLoader.cachedWallpaper != null) {
backgroundImage.setImageBitmap(ApplicationLoader.cachedWallpaper); ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(ApplicationLoader.cachedWallpaper);
} else { } else {
backgroundImage.setImageURI(Uri.fromFile(toFile)); Drawable drawable = Drawable.createFromPath(toFile.getAbsolutePath());
if (backgroundImage.getDrawable() instanceof BitmapDrawable) { if (drawable != null) {
ApplicationLoader.cachedWallpaper = ((BitmapDrawable)backgroundImage.getDrawable()).getBitmap(); ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(drawable);
ApplicationLoader.cachedWallpaper = drawable;
} else {
contentView.setBackgroundColor(-2693905);
chatListView.setCacheColorHint(-2693905);
} }
} }
isCustomTheme = true; isCustomTheme = true;
} else { } else {
backgroundImage.setImageResource(R.drawable.background_hd); ((SizeNotifierRelativeLayout) contentView).setBackgroundImage(R.drawable.background_hd);
} }
} }
} catch (Exception e) {
contentView.setBackgroundColor(-2693905);
chatListView.setCacheColorHint(-2693905);
FileLog.e("tmessages", e);
}
} }
if (currentEncryptedChat != null) { if (currentEncryptedChat != null) {
@ -686,7 +699,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
View v = contentView.findViewById(R.id.secret_placeholder); View v = contentView.findViewById(R.id.secret_placeholder);
v.setVisibility(View.VISIBLE); v.setVisibility(View.VISIBLE);
if (currentEncryptedChat.admin_id == UserConfig.clientUserId) { if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
if (currentUser.first_name.length() > 0) { if (currentUser.first_name.length() > 0) {
secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name)); secretViewStatusTextView.setText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing", R.string.EncryptedPlaceholderTitleOutgoing, currentUser.first_name));
} else { } else {
@ -979,6 +992,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
bottomOverlayChat.setOnClickListener(new View.OnClickListener() { bottomOverlayChat.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());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -1252,6 +1268,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
timerButton.setOnClickListener(new View.OnClickListener() { timerButton.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());
builder.setTitle(LocaleController.getString("MessageLifetime", R.string.MessageLifetime)); builder.setTitle(LocaleController.getString("MessageLifetime", R.string.MessageLifetime));
builder.setItems(new CharSequence[]{ builder.setItems(new CharSequence[]{
@ -1337,7 +1356,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
int currentTime = ConnectionsManager.getInstance().getCurrentTime(); int currentTime = ConnectionsManager.getInstance().getCurrentTime();
for (TLRPC.TL_chatParticipant participant : info.participants) { for (TLRPC.TL_chatParticipant participant : info.participants) {
TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id); TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id);
if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.clientUserId) && user.status.expires > 10000) { if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.getClientUserId()) && user.status.expires > 10000) {
onlineCount++; onlineCount++;
} }
} }
@ -1495,7 +1514,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (currentChat != null) { if (currentChat != null) {
actionBarLayer.setTitle(currentChat.title); actionBarLayer.setTitle(currentChat.title);
} else if (currentUser != null) { } else if (currentUser != null) {
if (currentUser.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(currentUser.id) == null && (ContactsController.getInstance().contactsDict.size() != 0 || !ContactsController.getInstance().loadingContacts)) { if (currentUser.id / 1000 != 777 && currentUser.id / 1000 != 333 && ContactsController.getInstance().contactsDict.get(currentUser.id) == null && (ContactsController.getInstance().contactsDict.size() != 0 || !ContactsController.getInstance().isLoadingContacts())) {
if (currentUser.phone != null && currentUser.phone.length() != 0) { if (currentUser.phone != null && currentUser.phone.length() != 0) {
actionBarLayer.setTitle(PhoneFormat.getInstance().format("+" + currentUser.phone)); actionBarLayer.setTitle(PhoneFormat.getInstance().format("+" + currentUser.phone));
} else { } else {
@ -1625,25 +1644,10 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
currentPicturePath = null; currentPicturePath = null;
} else if (requestCode == 1) { } else if (requestCode == 1) {
if (data == null || data.getData() == null) { if (data == null || data.getData() == null) {
showAttachmentError();
return; return;
} }
String tempPath = Utilities.getPath(data.getData());
boolean isGif = false;
if (tempPath != null && tempPath.endsWith(".gif")) {
isGif = true;
} else if (tempPath == null) {
isGif = MediaController.isGif(data.getData());
if (isGif) {
tempPath = MediaController.copyDocumentToCache(data.getData());
}
}
if (tempPath != null && isGif) {
processSendingDocument(tempPath);
} else {
processSendingPhoto(null, data.getData()); processSendingPhoto(null, data.getData());
}
} else if (requestCode == 2) { } else if (requestCode == 2) {
String videoPath = null; String videoPath = null;
if (data != null) { if (data != null) {
@ -1678,10 +1682,34 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
currentPicturePath = null; currentPicturePath = null;
} }
processSendingVideo(videoPath); processSendingVideo(videoPath);
} else if (requestCode == 21) {
if (data == null || data.getData() == null) {
showAttachmentError();
return;
}
String tempPath = Utilities.getPath(data.getData());
String originalPath = tempPath;
if (tempPath == null) {
originalPath = data.toString();
tempPath = MediaController.copyDocumentToCache(data.getData(), "file");
}
if (tempPath == null) {
showAttachmentError();
return;
}
processSendingDocument(tempPath, originalPath);
} }
} }
} }
private void showAttachmentError() {
if (getParentActivity() == null) {
return;
}
Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("UnsupportedAttachment", R.string.UnsupportedAttachment), Toast.LENGTH_SHORT);
toast.show();
}
@Override @Override
public void saveSelfArgs(Bundle args) { public void saveSelfArgs(Bundle args) {
if (currentPicturePath != null) { if (currentPicturePath != null) {
@ -1708,17 +1736,17 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
public void processSendingPhoto(String imageFilePath, Uri imageUri) { public void processSendingPhoto(String imageFilePath, Uri imageUri) {
if ((imageFilePath == null || imageFilePath.length() == 0) && imageUri == null) { ArrayList<String> paths = null;
return; ArrayList<Uri> uris = null;
if (imageFilePath != null && imageFilePath.length() != 0) {
paths = new ArrayList<String>();
paths.add(imageFilePath);
} }
TLRPC.TL_photo photo = MessagesController.getInstance().generatePhotoSizes(imageFilePath, imageUri); if (imageUri != null) {
if (photo != null) { uris = new ArrayList<Uri>();
MessagesController.getInstance().sendMessage(photo, dialog_id); uris.add(imageUri);
if (chatListView != null) {
chatListView.setSelection(messages.size() + 1);
}
scrollToTopOnResume = true;
} }
processSendingPhotos(paths, uris);
} }
public void processSendingPhotos(ArrayList<String> paths, ArrayList<Uri> uris) { public void processSendingPhotos(ArrayList<String> paths, ArrayList<Uri> uris) {
@ -1736,6 +1764,8 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
new Thread(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
ArrayList<String> sendAsDocuments = null;
ArrayList<String> sendAsDocumentsOriginal = null;
int count = !pathsCopy.isEmpty() ? pathsCopy.size() : urisCopy.size(); int count = !pathsCopy.isEmpty() ? pathsCopy.size() : urisCopy.size();
String path = null; String path = null;
Uri uri = null; Uri uri = null;
@ -1745,49 +1775,101 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} else if (!urisCopy.isEmpty()) { } else if (!urisCopy.isEmpty()) {
uri = urisCopy.get(a); uri = urisCopy.get(a);
} }
final TLRPC.TL_photo photo = MessagesController.getInstance().generatePhotoSizes(path, uri);
String originalPath = path;
String tempPath = path;
if (tempPath == null && uri != null) {
tempPath = Utilities.getPath(uri);
originalPath = uri.toString();
}
boolean isGif = false;
if (tempPath != null && tempPath.endsWith(".gif")) {
isGif = true;
} else if (tempPath == null && uri != null) {
isGif = MediaController.isGif(uri);
if (isGif) {
originalPath = uri.toString();
tempPath = MediaController.copyDocumentToCache(uri, "gif");
}
}
if (isGif) {
if (sendAsDocuments == null) {
sendAsDocuments = new ArrayList<String>();
sendAsDocumentsOriginal = new ArrayList<String>();
}
sendAsDocuments.add(tempPath);
sendAsDocumentsOriginal.add(originalPath);
} else {
TLRPC.TL_photo photo = (TLRPC.TL_photo)MessagesStorage.getInstance().getSentFile(originalPath, currentEncryptedChat == null ? 0 : 3);
if (photo == null && uri != null) {
photo = (TLRPC.TL_photo)MessagesStorage.getInstance().getSentFile(Utilities.getPath(uri), currentEncryptedChat == null ? 0 : 3);
}
if (photo == null) {
photo = MessagesController.getInstance().generatePhotoSizes(path, uri);
}
if (photo != null) {
final String originalPathFinal = originalPath;
final TLRPC.TL_photo photoFinal = photo;
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
if (photo != null) { MessagesController.getInstance().sendMessage(photoFinal, originalPathFinal, dialog_id);
MessagesController.getInstance().sendMessage(photo, dialog_id);
if (chatListView != null) { if (chatListView != null) {
chatListView.setSelection(messages.size() + 1); chatListView.setSelection(messages.size() + 1);
} }
if (paused) {
scrollToTopOnResume = true; scrollToTopOnResume = true;
} }
} }
}); });
} }
} }
}
if (sendAsDocuments != null && !sendAsDocuments.isEmpty()) {
for (int a = 0; a < sendAsDocuments.size(); a++) {
processSendingDocumentInternal(sendAsDocuments.get(a), sendAsDocumentsOriginal.get(a));
}
}
}
}).start(); }).start();
} }
public void processSendingDocument(String documentFilePath) { private void processSendingDocumentInternal(String path, String originalPath) {
if (documentFilePath == null || documentFilePath.length() == 0) { if (path == null || path.length() == 0) {
return; return;
} }
File f = new File(documentFilePath); final File f = new File(path);
if (!f.exists() || f.length() == 0) { if (!f.exists() || f.length() == 0) {
return; return;
} }
String name = f.getName(); String name = f.getName();
if (name == null) { if (name == null) {
name = "noname"; name = "noname";
} }
String ext = ""; String ext = "";
int idx = documentFilePath.lastIndexOf("."); int idx = path.lastIndexOf(".");
if (idx != -1) { if (idx != -1) {
ext = documentFilePath.substring(idx + 1); ext = path.substring(idx + 1);
} }
TLRPC.TL_document document = new TLRPC.TL_document(); if (originalPath != null) {
originalPath += "" + f.length();
}
TLRPC.TL_document document = (TLRPC.TL_document)MessagesStorage.getInstance().getSentFile(originalPath, currentEncryptedChat == null ? 1 : 4);
if (document == null && !path.equals(originalPath)) {
document = (TLRPC.TL_document)MessagesStorage.getInstance().getSentFile(path + f.length(), currentEncryptedChat == null ? 1 : 4);
}
if (document == null) {
document = new TLRPC.TL_document();
document.id = 0; document.id = 0;
document.user_id = UserConfig.clientUserId; document.user_id = UserConfig.getClientUserId();
document.date = ConnectionsManager.getInstance().getCurrentTime(); document.date = ConnectionsManager.getInstance().getCurrentTime();
document.file_name = name; document.file_name = name;
document.size = (int)f.length(); document.size = (int)f.length();
document.dc_id = 0; document.dc_id = 0;
document.path = documentFilePath;
if (ext.length() != 0) { if (ext.length() != 0) {
MimeTypeMap myMime = MimeTypeMap.getSingleton(); MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase()); String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
@ -1814,27 +1896,72 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
document.thumb = new TLRPC.TL_photoSizeEmpty(); document.thumb = new TLRPC.TL_photoSizeEmpty();
document.thumb.type = "s"; document.thumb.type = "s";
} }
MessagesController.getInstance().sendMessage(document, dialog_id); }
document.path = path;
final TLRPC.TL_document documentFinal = document;
final String originalPathFinal = originalPath;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().sendMessage(documentFinal, originalPathFinal, dialog_id);
if (chatListView != null) {
chatListView.setSelection(messages.size() + 1);
}
if (paused) {
scrollToTopOnResume = true;
}
}
});
}
public void processSendingDocument(String path, String originalPath) {
if (path == null || originalPath == null) {
return;
}
ArrayList<String> paths = new ArrayList<String>();
ArrayList<String> originalPaths = new ArrayList<String>();
paths.add(path);
originalPaths.add(originalPath);
processSendingDocuments(paths, originalPaths);
}
public void processSendingDocuments(final ArrayList<String> paths, final ArrayList<String> originalPaths) {
if (paths == null && originalPaths == null || paths != null && originalPaths != null && paths.size() != originalPaths.size()) {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
for (int a = 0; a < paths.size(); a++) {
processSendingDocumentInternal(paths.get(a), originalPaths.get(a));
}
}
}).start();
} }
public void processSendingVideo(final String videoPath) { public void processSendingVideo(final String videoPath) {
if (videoPath == null || videoPath.length() == 0) { if (videoPath == null || videoPath.length() == 0) {
return; return;
} }
new Thread(new Runnable() {
@Override
public void run() {
TLRPC.TL_video video = (TLRPC.TL_video)MessagesStorage.getInstance().getSentFile(videoPath, currentEncryptedChat == null ? 2 : 5);
if (video == null) {
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND); Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null); TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null);
if (size == null) { if (size == null) {
return; return;
} }
size.type = "s"; size.type = "s";
TLRPC.TL_video video = new TLRPC.TL_video(); video = new TLRPC.TL_video();
video.thumb = size; video.thumb = size;
video.caption = ""; video.caption = "";
video.id = 0; video.id = 0;
video.path = videoPath;
File temp = new File(videoPath); File temp = new File(videoPath);
if (temp != null && temp.exists()) { if (temp != null && temp.exists()) {
video.size = (int)temp.length(); video.size = (int) temp.length();
} }
UserConfig.lastLocalId--; UserConfig.lastLocalId--;
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
@ -1843,18 +1970,29 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (mp == null) { if (mp == null) {
return; return;
} }
video.duration = (int)Math.ceil(mp.getDuration() / 1000.0f); video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f);
video.w = mp.getVideoWidth(); video.w = mp.getVideoWidth();
video.h = mp.getVideoHeight(); video.h = mp.getVideoHeight();
mp.release(); mp.release();
}
video.path = videoPath;
MediaStore.Video.Media media = new MediaStore.Video.Media(); final TLRPC.TL_video videoFinal = video;
MessagesController.getInstance().sendMessage(video, dialog_id); Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().sendMessage(videoFinal, videoPath, dialog_id);
if (chatListView != null) { if (chatListView != null) {
chatListView.setSelection(messages.size() + 1); chatListView.setSelection(messages.size() + 1);
} }
if (paused) {
scrollToTopOnResume = true; scrollToTopOnResume = true;
} }
}
});
}
}).start();
}
private void removeUnreadPlane(boolean reload) { private void removeUnreadPlane(boolean reload) {
if (unreadMessageObject != null) { if (unreadMessageObject != null) {
@ -2285,10 +2423,8 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
dayArr.remove(obj); dayArr.remove(obj);
if (dayArr.isEmpty()) { if (dayArr.isEmpty()) {
messagesByDays.remove(obj.dateKey); messagesByDays.remove(obj.dateKey);
if (index != -1) {
messages.remove(index); messages.remove(index);
} }
}
updated = true; updated = true;
} }
} }
@ -2514,10 +2650,11 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
if (currentEncryptedChat != null && !(currentEncryptedChat instanceof TLRPC.TL_encryptedChat) if (currentEncryptedChat != null && !(currentEncryptedChat instanceof TLRPC.TL_encryptedChat)
|| currentUser.id / 1000 == 333 || currentUser.id / 1000 == 333
|| currentUser.id / 1000 == 777
|| currentUser instanceof TLRPC.TL_userEmpty || currentUser instanceof TLRPC.TL_userDeleted || currentUser instanceof TLRPC.TL_userEmpty || currentUser instanceof TLRPC.TL_userDeleted
|| (currentUser.phone != null && currentUser.phone.length() != 0 && || (currentUser.phone != null && currentUser.phone.length() != 0 &&
ContactsController.getInstance().contactsDict.get(currentUser.id) != null && ContactsController.getInstance().contactsDict.get(currentUser.id) != null &&
(ContactsController.getInstance().contactsDict.size() != 0 || !ContactsController.getInstance().loadingContacts))) { (ContactsController.getInstance().contactsDict.size() != 0 || !ContactsController.getInstance().isLoadingContacts()))) {
topPanel.setVisibility(View.GONE); topPanel.setVisibility(View.GONE);
} else { } else {
topPanel.setVisibility(View.VISIBLE); topPanel.setVisibility(View.VISIBLE);
@ -2560,6 +2697,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
topPanel.setOnClickListener(new View.OnClickListener() { topPanel.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -2568,7 +2708,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().hidenAddToContacts.put(currentUser.id, currentUser); MessagesController.getInstance().hidenAddToContacts.put(currentUser.id, currentUser);
topPanel.setVisibility(View.GONE); topPanel.setVisibility(View.GONE);
MessagesController.getInstance().sendMessage(UserConfig.currentUser, dialog_id); MessagesController.getInstance().sendMessage(UserConfig.getCurrentUser(), dialog_id);
chatListView.post(new Runnable() { chatListView.post(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -2588,6 +2728,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
private void createEmojiPopup() { private void createEmojiPopup() {
if (getParentActivity() == null) {
return;
}
emojiView = new EmojiView(getParentActivity()); emojiView = new EmojiView(getParentActivity());
emojiView.setListener(new EmojiView.Listener() { emojiView.setListener(new EmojiView.Listener() {
public void onBackspace() { public void onBackspace() {
@ -2682,16 +2825,13 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
scrollToTopUnReadOnResume = false; scrollToTopUnReadOnResume = false;
scrollToTopOnResume = false; scrollToTopOnResume = false;
} }
if (emojiView != null) {
emojiView.loadRecents();
}
paused = false; paused = false;
if (readWhenResume && !messages.isEmpty()) { if (readWhenResume && !messages.isEmpty()) {
readWhenResume = false; readWhenResume = false;
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, readWithMid, 0, readWithDate, true); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, readWithMid, 0, readWithDate, true);
} }
fixLayout(); fixLayout(true);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
String lastMessageText = preferences.getString("dialog_" + dialog_id, null); String lastMessageText = preferences.getString("dialog_" + dialog_id, null);
if (lastMessageText != null) { if (lastMessageText != null) {
@ -2809,7 +2949,8 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
MediaController.getInstance().setLastEncryptedChatParams(chatEnterTime, chatLeaveTime, currentEncryptedChat, visibleMessages); MediaController.getInstance().setLastEncryptedChatParams(chatEnterTime, chatLeaveTime, currentEncryptedChat, visibleMessages);
} }
private void fixLayout() { private void fixLayout(final boolean resume) {
final int lastPos = chatListView.getLastVisiblePosition();
ViewTreeObserver obs = chatListView.getViewTreeObserver(); ViewTreeObserver obs = chatListView.getViewTreeObserver();
obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override @Override
@ -2821,7 +2962,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
return true; return true;
} }
int height = Utilities.dp(48); int height = Utilities.dp(48);
if (getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getParentActivity()) && getParentActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
height = Utilities.dp(40); height = Utilities.dp(40);
selectedMessagesCountTextView.setTextSize(16); selectedMessagesCountTextView.setTextSize(16);
} else { } else {
@ -2833,6 +2974,14 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
params.height = height; params.height = height;
avatarImageView.setLayoutParams(params); avatarImageView.setLayoutParams(params);
} }
if (!resume && lastPos >= messages.size() - 1) {
chatListView.post(new Runnable() {
@Override
public void run() {
chatListView.setSelectionFromTop(messages.size() - 1, -100000 - chatListView.getPaddingTop());
}
});
}
return false; return false;
} }
}); });
@ -2840,7 +2989,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
@Override @Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) { public void onConfigurationChanged(android.content.res.Configuration newConfig) {
fixLayout(); fixLayout(false);
} }
private View getRowParentView(View v) { private View getRowParentView(View v) {
@ -2866,10 +3015,6 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
return; return;
} }
selectedObject = null;
forwaringMessage = null;
selectedMessagesCanCopyIds.clear();
selectedMessagesIds.clear();
View parentView = getRowParentView(v); View parentView = getRowParentView(v);
if (parentView == null) { if (parentView == null) {
return; return;
@ -2882,9 +3027,18 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
message = holder.message; message = holder.message;
} }
final int type = getMessageType(message); final int type = getMessageType(message);
selectedObject = null;
forwaringMessage = null;
selectedMessagesCanCopyIds.clear();
selectedMessagesIds.clear();
if (single || type < 2) { if (single || type < 2) {
if (type >= 0) { if (type >= 0) {
selectedObject = message; selectedObject = message;
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items = null; CharSequence[] items = null;
@ -2924,6 +3078,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
builder.setItems(items, new DialogInterface.OnClickListener() { builder.setItems(items, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
if (selectedObject == null) {
return;
}
if (type == 0) { if (type == 0) {
if (i == 0) { if (i == 0) {
processSelectedOption(0); processSelectedOption(0);
@ -3020,6 +3177,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (LocaleController.getInstance().applyLanguageFile(locFile)) { if (LocaleController.getInstance().applyLanguageFile(locFile)) {
presentFragment(new LanguageSelectActivity()); presentFragment(new LanguageSelectActivity());
} else { } else {
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.getString("IncorrectLocalization", R.string.IncorrectLocalization)); builder.setMessage(LocaleController.getString("IncorrectLocalization", R.string.IncorrectLocalization));
@ -3059,7 +3219,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
MessagesController.getInstance().sendMessage(selectedObject, dialog_id); MessagesController.getInstance().sendMessage(selectedObject, dialog_id);
} else { } else {
TLRPC.TL_photo photo = (TLRPC.TL_photo)selectedObject.messageOwner.media.photo; TLRPC.TL_photo photo = (TLRPC.TL_photo)selectedObject.messageOwner.media.photo;
MessagesController.getInstance().sendMessage(photo, dialog_id); MessagesController.getInstance().sendMessage(photo, selectedObject.messageOwner.attachPath, dialog_id);
} }
} else if (selectedObject.type == 3) { } else if (selectedObject.type == 3) {
if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) { if (selectedObject.messageOwner instanceof TLRPC.TL_messageForwarded) {
@ -3067,7 +3227,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} else { } else {
TLRPC.TL_video video = (TLRPC.TL_video)selectedObject.messageOwner.media.video; TLRPC.TL_video video = (TLRPC.TL_video)selectedObject.messageOwner.media.video;
video.path = selectedObject.messageOwner.attachPath; video.path = selectedObject.messageOwner.attachPath;
MessagesController.getInstance().sendMessage(video, dialog_id); MessagesController.getInstance().sendMessage(video, video.path, dialog_id);
} }
} else if (selectedObject.type == 12 || selectedObject.type == 13) { } else if (selectedObject.type == 12 || selectedObject.type == 13) {
TLRPC.User user = MessagesController.getInstance().users.get(selectedObject.messageOwner.media.user_id); TLRPC.User user = MessagesController.getInstance().users.get(selectedObject.messageOwner.media.user_id);
@ -3075,7 +3235,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} else if (selectedObject.type == 8 || selectedObject.type == 9) { } else if (selectedObject.type == 8 || selectedObject.type == 9) {
TLRPC.TL_document document = (TLRPC.TL_document)selectedObject.messageOwner.media.document; TLRPC.TL_document document = (TLRPC.TL_document)selectedObject.messageOwner.media.document;
document.path = selectedObject.messageOwner.attachPath; document.path = selectedObject.messageOwner.attachPath;
MessagesController.getInstance().sendMessage(document, dialog_id); MessagesController.getInstance().sendMessage(document, document.path, dialog_id);
} else if (selectedObject.type == 2) { } else if (selectedObject.type == 2) {
TLRPC.TL_audio audio = (TLRPC.TL_audio)selectedObject.messageOwner.media.audio; TLRPC.TL_audio audio = (TLRPC.TL_audio)selectedObject.messageOwner.media.audio;
audio.path = selectedObject.messageOwner.attachPath; audio.path = selectedObject.messageOwner.attachPath;
@ -3133,44 +3293,21 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
@Override @Override
public void didSelectFile(DocumentSelectActivity activity, String path, String name, String ext, long size) { public void didSelectFile(DocumentSelectActivity activity, String path) {
activity.finishFragment(); activity.finishFragment();
TLRPC.TL_document document = new TLRPC.TL_document(); processSendingDocument(path, path);
document.id = 0;
document.user_id = UserConfig.clientUserId;
document.date = ConnectionsManager.getInstance().getCurrentTime();
document.file_name = name;
document.size = (int)size;
document.dc_id = 0;
document.path = path;
if (ext.length() != 0) {
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(ext.toLowerCase());
if (mimeType != null) {
document.mime_type = mimeType;
} else {
document.mime_type = "application/octet-stream";
} }
} else {
document.mime_type = "application/octet-stream"; @Override
} public void startDocumentSelectActivity() {
if (document.mime_type.equals("image/gif")) {
try { try {
Bitmap bitmap = FileLoader.loadBitmap(path, null, 90, 90); Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
if (bitmap != null) { photoPickerIntent.setType("*/*");
document.thumb = FileLoader.scaleAndSaveImage(bitmap, 90, 90, 80, currentEncryptedChat != null); getParentActivity().startActivityForResult(photoPickerIntent, 21);
document.thumb.type = "s";
}
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
if (document.thumb == null) {
document.thumb = new TLRPC.TL_photoSizeEmpty();
document.thumb.type = "s";
}
MessagesController.getInstance().sendMessage(document, dialog_id);
}
@Override @Override
public void didSelectDialog(MessagesActivity activity, long did) { public void didSelectDialog(MessagesActivity activity, long did) {
@ -3251,9 +3388,12 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
public boolean isGoogleMapsInstalled() { public boolean isGoogleMapsInstalled() {
try { try {
ApplicationInfo info = ApplicationLoader.applicationContext.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0 ); ApplicationInfo info = ApplicationLoader.applicationContext.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0);
return true; return true;
} catch(PackageManager.NameNotFoundException e) { } catch(PackageManager.NameNotFoundException e) {
if (getParentActivity() == null) {
return false;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage("Install Google Maps?"); builder.setMessage("Install Google Maps?");
builder.setCancelable(true); builder.setCancelable(true);
@ -3374,6 +3514,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
private void alertUserOpenError(MessageObject message) { private void alertUserOpenError(MessageObject message) {
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.setPositiveButton(R.string.OK, null); builder.setPositiveButton(R.string.OK, null);
@ -3451,7 +3594,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
@Override @Override
public int getSelectedCount() { return 0; } public int getSelectedCount() { return 0; }
private class ChatAdapter extends BaseAdapter { private class ChatAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
@ -3573,7 +3716,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
((ChatBaseCell)view).delegate = new ChatBaseCell.ChatBaseCellDelegate() { ((ChatBaseCell)view).delegate = new ChatBaseCell.ChatBaseCellDelegate() {
@Override @Override
public void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user) { public void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user) {
if (user != null && user.id != UserConfig.clientUserId) { if (user != null && user.id != UserConfig.getClientUserId()) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putInt("user_id", user.id); args.putInt("user_id", user.id);
presentFragment(new UserProfileActivity(args)); presentFragment(new UserProfileActivity(args));
@ -3756,11 +3899,15 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
photoImage.setImage(message.messageOwner.action.newUserPhoto.photo_small, "50_50", Utilities.getUserAvatarForId(currentUser.id)); photoImage.setImage(message.messageOwner.action.newUserPhoto.photo_small, "50_50", Utilities.getUserAvatarForId(currentUser.id));
} else { } else {
PhotoObject photo = PhotoObject.getClosestImageWithSize(message.photoThumbs, Utilities.dp(64), Utilities.dp(64)); PhotoObject photo = PhotoObject.getClosestImageWithSize(message.photoThumbs, Utilities.dp(64), Utilities.dp(64));
if (photo != null) {
if (photo.image != null) { if (photo.image != null) {
photoImage.setImageBitmap(photo.image); photoImage.setImageBitmap(photo.image);
} else { } else {
photoImage.setImage(photo.photoOwner.location, "50_50", Utilities.getGroupAvatarForId(currentChat.id)); photoImage.setImage(photo.photoOwner.location, "50_50", Utilities.getGroupAvatarForId(currentChat.id));
} }
} else {
photoImage.setImageResource(Utilities.getGroupAvatarForId(currentChat.id));
}
} }
photoImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false); photoImage.imageReceiver.setVisible(!PhotoViewer.getInstance().isShowingImage(message), false);
} }
@ -3784,7 +3931,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
} }
int placeHolderId = Utilities.getUserAvatarForId(contactUser.id); int placeHolderId = Utilities.getUserAvatarForId(contactUser.id);
contactAvatar.setImage(photo, "50_50", placeHolderId); contactAvatar.setImage(photo, "50_50", placeHolderId);
if (contactUser.id != UserConfig.clientUserId && ContactsController.getInstance().contactsDict.get(contactUser.id) == null) { if (contactUser.id != UserConfig.getClientUserId() && ContactsController.getInstance().contactsDict.get(contactUser.id) == null) {
addContactView.setVisibility(View.VISIBLE); addContactView.setVisibility(View.VISIBLE);
} else { } else {
addContactView.setVisibility(View.GONE); addContactView.setVisibility(View.GONE);
@ -3870,14 +4017,17 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (actionView != null) { if (actionView != null) {
actionView.setVisibility(View.VISIBLE); actionView.setVisibility(View.VISIBLE);
} }
Float progress = FileLoader.getInstance().fileProgresses.get(message.messageOwner.attachPath); Float progress = null;
if (message.messageOwner.attachPath != null && message.messageOwner.attachPath.length() != 0) {
progress = FileLoader.getInstance().fileProgresses.get(message.messageOwner.attachPath);
progressByTag.put((Integer)actionProgress.getTag(), message.messageOwner.attachPath);
progressBarMap.put(message.messageOwner.attachPath, actionProgress);
}
if (progress != null) { if (progress != null) {
actionProgress.setProgress((int)(progress * 100)); actionProgress.setProgress((int)(progress * 100));
} else { } else {
actionProgress.setProgress(0); actionProgress.setProgress(0);
} }
progressByTag.put((Integer)actionProgress.getTag(), message.messageOwner.attachPath);
progressBarMap.put(message.messageOwner.attachPath, actionProgress);
} }
if (actionAttachButton != null) { if (actionAttachButton != null) {
actionAttachButton.setVisibility(View.GONE); actionAttachButton.setVisibility(View.GONE);
@ -4090,7 +4240,7 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
processRowSelect(view); processRowSelect(view);
return; return;
} }
if (message.messageOwner.media.user_id != UserConfig.clientUserId) { if (message.messageOwner.media.user_id != UserConfig.getClientUserId()) {
TLRPC.User user = null; TLRPC.User user = null;
if (message.messageOwner.media.user_id != 0) { if (message.messageOwner.media.user_id != 0) {
user = MessagesController.getInstance().users.get(message.messageOwner.media.user_id); user = MessagesController.getInstance().users.get(message.messageOwner.media.user_id);
@ -4103,6 +4253,9 @@ public class ChatActivity extends BaseFragment implements SizeNotifierRelativeLa
if (message.messageOwner.media.phone_number == null || message.messageOwner.media.phone_number.length() == 0) { if (message.messageOwner.media.phone_number == null || message.messageOwner.media.phone_number.length() == 0) {
return; return;
} }
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setItems(new CharSequence[] {LocaleController.getString("Copy", R.string.Copy), LocaleController.getString("Call", R.string.Call)}, new DialogInterface.OnClickListener() { builder.setItems(new CharSequence[] {LocaleController.getString("Copy", R.string.Copy), LocaleController.getString("Call", R.string.Call)}, new DialogInterface.OnClickListener() {
@Override @Override

View File

@ -8,29 +8,22 @@
package org.telegram.ui; package org.telegram.ui;
import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings;
import android.text.Html; import android.text.Html;
import android.view.LayoutInflater; 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.ImageButton; import android.widget.ImageButton;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
@ -40,6 +33,7 @@ import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Cells.ChatOrUserCell;
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;
@ -51,6 +45,7 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.concurrent.Semaphore;
public class ChatProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate, PhotoViewer.PhotoViewerProvider { public class ChatProfileActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, ContactsActivity.ContactsActivityDelegate, PhotoViewer.PhotoViewerProvider {
private ListView listView; private ListView listView;
@ -63,15 +58,15 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
private int totalMediaCount = -1; private int totalMediaCount = -1;
private int onlineCount = -1; private int onlineCount = -1;
private ArrayList<Integer> sortedUsers = new ArrayList<Integer>(); private ArrayList<Integer> sortedUsers = new ArrayList<Integer>();
private TLRPC.Chat currentChat;
private int avatarRow; private int avatarRow;
private int settingsSectionRow; private int settingsSectionRow;
private int settingsNotificationsRow; private int settingsNotificationsRow;
private int settingsVibrateRow;
private int settingsSoundRow;
private int sharedMediaSectionRow; private int sharedMediaSectionRow;
private int sharedMediaRow; private int sharedMediaRow;
private int membersSectionRow; private int membersSectionRow;
private int membersEndRow;
private int addMemberRow; private int addMemberRow;
private int leaveGroupRow; private int leaveGroupRow;
private int rowCount = 0; private int rowCount = 0;
@ -85,12 +80,35 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
super.onFragmentCreate(); super.onFragmentCreate();
chat_id = getArguments().getInt("chat_id", 0);
currentChat = MessagesController.getInstance().chats.get(chat_id);
if (currentChat == null) {
final Semaphore semaphore = new Semaphore(0);
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
currentChat = MessagesStorage.getInstance().getChat(chat_id);
semaphore.release();
}
});
try {
semaphore.acquire();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (currentChat != null) {
MessagesController.getInstance().chats.put(currentChat.id, currentChat);
} else {
return false;
}
}
NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, MessagesController.chatInfoDidLoaded); NotificationCenter.getInstance().addObserver(this, MessagesController.chatInfoDidLoaded);
NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded); NotificationCenter.getInstance().addObserver(this, MessagesController.mediaCountDidLoaded);
NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats);
chat_id = getArguments().getInt("chat_id", 0);
updateOnlineCount(); updateOnlineCount();
MessagesController.getInstance().getMediaCount(-chat_id, classGuid, true); MessagesController.getInstance().getMediaCount(-chat_id, classGuid, true);
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() { avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
@ -113,19 +131,19 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
avatarRow = rowCount++; avatarRow = rowCount++;
settingsSectionRow = rowCount++; settingsSectionRow = rowCount++;
settingsNotificationsRow = rowCount++; settingsNotificationsRow = rowCount++;
settingsVibrateRow = rowCount++;
settingsSoundRow = rowCount++;
sharedMediaSectionRow = rowCount++; sharedMediaSectionRow = rowCount++;
sharedMediaRow = rowCount++; sharedMediaRow = rowCount++;
if (info != null && !(info instanceof TLRPC.TL_chatParticipantsForbidden)) { if (info != null && !(info instanceof TLRPC.TL_chatParticipantsForbidden)) {
membersSectionRow = rowCount++; membersSectionRow = rowCount++;
rowCount += info.participants.size(); rowCount += info.participants.size();
membersEndRow = rowCount;
if (info.participants.size() < 200) { if (info.participants.size() < 200) {
addMemberRow = rowCount++; addMemberRow = rowCount++;
} else { } else {
addMemberRow = -1; addMemberRow = -1;
} }
} else { } else {
membersEndRow = -1;
addMemberRow = -1; addMemberRow = -1;
membersSectionRow = -1; membersSectionRow = -1;
} }
@ -171,12 +189,16 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override @Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i > membersSectionRow && i < addMemberRow) { if (i > membersSectionRow && i < membersEndRow) {
TLRPC.TL_chatParticipant user = info.participants.get(sortedUsers.get(i - membersSectionRow - 1)); if (getParentActivity() == null) {
if (user.user_id == UserConfig.clientUserId) {
return false; return false;
} }
if (info.admin_id != UserConfig.clientUserId && user.inviter_id != UserConfig.clientUserId) {
TLRPC.TL_chatParticipant user = info.participants.get(sortedUsers.get(i - membersSectionRow - 1));
if (user.user_id == UserConfig.getClientUserId()) {
return false;
}
if (info.admin_id != UserConfig.getClientUserId() && user.inviter_id != UserConfig.getClientUserId()) {
return false; return false;
} }
selectedUser = user; selectedUser = user;
@ -203,74 +225,24 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == settingsSoundRow) { if (i == sharedMediaRow) {
try {
Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
Uri currentSound = null;
String defaultPath = null;
Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
String path = preferences.getString("sound_chat_path_" + chat_id, defaultPath);
if (path != null && !path.equals("NoSound")) {
if (path.equals(defaultPath)) {
currentSound = defaultUri;
} else {
currentSound = Uri.parse(path);
}
}
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
getParentActivity().startActivityForResult(tmpIntent, 3);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else if (i == sharedMediaRow) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putLong("dialog_id", -chat_id); args.putLong("dialog_id", -chat_id);
presentFragment(new MediaActivity(args)); presentFragment(new MediaActivity(args));
} else if (i == addMemberRow) { } else if (i == addMemberRow) {
openAddMenu(); openAddMenu();
} else if (i > membersSectionRow && i < addMemberRow) { } else if (i > membersSectionRow && i < membersEndRow) {
int user_id = info.participants.get(sortedUsers.get(i - membersSectionRow - 1)).user_id; int user_id = info.participants.get(sortedUsers.get(i - membersSectionRow - 1)).user_id;
if (user_id == UserConfig.clientUserId) { if (user_id == UserConfig.getClientUserId()) {
return; return;
} }
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putInt("user_id", user_id); args.putInt("user_id", user_id);
presentFragment(new UserProfileActivity(args)); presentFragment(new UserProfileActivity(args));
} else if (i == settingsVibrateRow || i == settingsNotificationsRow) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setItems(new CharSequence[] {
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("Enabled", R.string.Enabled),
LocaleController.getString("Disabled", R.string.Disabled)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == settingsVibrateRow) {
editor.putInt("vibrate_" + (-chat_id), which);
} else if (i == settingsNotificationsRow) { } else if (i == settingsNotificationsRow) {
editor.putInt("notify2_" + (-chat_id), which); Bundle args = new Bundle();
} args.putLong("dialog_id", -chat_id);
editor.commit(); presentFragment(new ProfileNotificationsActivity(args));
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
} }
} }
}); });
@ -288,41 +260,6 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
MessagesController.getInstance().addUserToChat(chat_id, user, info); MessagesController.getInstance().addUserToChat(chat_id, user, info);
} }
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
avatarUpdater.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 3) {
Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
String name = null;
if (ringtone != null) {
Ringtone rng = RingtoneManager.getRingtone(getParentActivity(), ringtone);
if (rng != null) {
if(ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
name = LocaleController.getString("Default", R.string.Default);
} else {
name = rng.getTitle(getParentActivity());
}
rng.stop();
}
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (name != null && ringtone != null) {
editor.putString("sound_chat_" + chat_id, name);
editor.putString("sound_chat_path_" + chat_id, ringtone.toString());
} else {
editor.putString("sound_chat_" + chat_id, "NoSound");
editor.putString("sound_chat_path_" + chat_id, "NoSound");
}
editor.commit();
listView.invalidateViews();
}
}
}
@Override @Override
public void saveSelfArgs(Bundle args) { public void saveSelfArgs(Bundle args) {
if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) { if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) {
@ -458,7 +395,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
int i = 0; int i = 0;
for (TLRPC.TL_chatParticipant participant : info.participants) { for (TLRPC.TL_chatParticipant participant : info.participants) {
TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id); TLRPC.User user = MessagesController.getInstance().users.get(participant.user_id);
if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.clientUserId) && user.status.expires > 10000) { if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.getClientUserId()) && user.status.expires > 10000) {
onlineCount++; onlineCount++;
} }
sortedUsers.add(i); sortedUsers.add(i);
@ -473,14 +410,14 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
Integer status1 = 0; Integer status1 = 0;
Integer status2 = 0; Integer status2 = 0;
if (user1 != null && user1.status != null) { if (user1 != null && user1.status != null) {
if (user1.id == UserConfig.clientUserId) { if (user1.id == UserConfig.getClientUserId()) {
status1 = ConnectionsManager.getInstance().getCurrentTime() + 50000; status1 = ConnectionsManager.getInstance().getCurrentTime() + 50000;
} else { } else {
status1 = user1.status.expires; status1 = user1.status.expires;
} }
} }
if (user2 != null && user2.status != null) { if (user2 != null && user2.status != null) {
if (user2.id == UserConfig.clientUserId) { if (user2.id == UserConfig.getClientUserId()) {
status2 = ConnectionsManager.getInstance().getCurrentTime() + 50000; status2 = ConnectionsManager.getInstance().getCurrentTime() + 50000;
} else { } else {
status2 = user2.status.expires; status2 = user2.status.expires;
@ -535,13 +472,13 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
} else { } else {
NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats); NotificationCenter.getInstance().removeObserver(this, MessagesController.closeChats);
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().users.get(UserConfig.clientUserId), info); MessagesController.getInstance().deleteUserFromChat(chat_id, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), info);
MessagesController.getInstance().deleteDialog(-chat_id, 0, false); MessagesController.getInstance().deleteDialog(-chat_id, 0, false);
finishFragment(); finishFragment();
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {
@ -555,7 +492,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public boolean isEnabled(int i) { public boolean isEnabled(int i) {
return i == settingsNotificationsRow || i == settingsSoundRow || i == sharedMediaRow || i > membersSectionRow && i <= addMemberRow || i == settingsVibrateRow; return i == settingsNotificationsRow || i == sharedMediaRow || i == addMemberRow || i > membersSectionRow && i < membersEndRow;
} }
@Override @Override
@ -604,6 +541,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
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;
int type; int type;
@ -700,30 +640,6 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
detailTextView.setText(String.format("%d", totalMediaCount)); detailTextView.setText(String.format("%d", totalMediaCount));
} }
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} else if (i == settingsVibrateRow) {
textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("vibrate_" + (-chat_id), 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} else if (i == settingsNotificationsRow) {
textView.setText(LocaleController.getString("Notifications", R.string.Notifications));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("notify2_" + (-chat_id), 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} }
} else if (type == 3) { } else if (type == 3) {
TLRPC.TL_chatParticipant part = info.participants.get(sortedUsers.get(i - membersSectionRow - 1)); TLRPC.TL_chatParticipant part = info.participants.get(sortedUsers.get(i - membersSectionRow - 1));
@ -736,12 +652,6 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
} }
((ChatOrUserCell)view).setData(user, null, null, null, null); ((ChatOrUserCell)view).setData(user, null, null, null, null);
// if (info.admin_id != UserConfig.clientUserId && part.inviter_id != UserConfig.clientUserId && part.user_id != UserConfig.clientUserId) {
//
// } else {
//
// }
} else if (type == 4) { } else if (type == 4) {
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
@ -758,6 +668,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
textView.setOnClickListener(new View.OnClickListener() { textView.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());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -775,20 +688,12 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
} else if (type == 6) { } else if (type == 6) {
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_detail_layout, viewGroup, false); view = li.inflate(R.layout.settings_row_button_layout, viewGroup, false);
} }
TextView textView = (TextView)view.findViewById(R.id.settings_row_text); TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider); View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsSoundRow) { if (i == settingsNotificationsRow) {
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); textView.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds));
String name = preferences.getString("sound_chat_" + chat_id, LocaleController.getString("Default", R.string.Default));
if (name.equals("NoSound")) {
detailTextView.setText(LocaleController.getString("NoSound", R.string.NoSound));
} else {
detailTextView.setText(name);
}
textView.setText(LocaleController.getString("Sound", R.string.Sound));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} }
} }
@ -801,16 +706,16 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
return 0; return 0;
} else if (i == settingsSectionRow || i == sharedMediaSectionRow || i == membersSectionRow) { } else if (i == settingsSectionRow || i == sharedMediaSectionRow || i == membersSectionRow) {
return 1; return 1;
} else if (i == sharedMediaRow || i == settingsVibrateRow || i == settingsNotificationsRow) { } else if (i == sharedMediaRow) {
return 2; return 2;
} else if (i == settingsSoundRow) {
return 6;
} else if (i == addMemberRow) { } else if (i == addMemberRow) {
return 4; return 4;
} else if (i == leaveGroupRow) { } else if (i == leaveGroupRow) {
return 5; return 5;
} else if (i > membersSectionRow && i < addMemberRow) { } else if (i > membersSectionRow && i < membersEndRow) {
return 3; return 3;
} else if (i == settingsNotificationsRow) {
return 6;
} }
return 0; return 0;
} }

View File

@ -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);

View File

@ -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
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
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
} }
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
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
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)));

View File

@ -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 {
} }
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 {
} }
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 {
}); });
} }
private class SearchAdapter extends BaseAdapter { private class SearchAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public SearchAdapter(Context context) { public SearchAdapter(Context context) {

View File

@ -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;
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;
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 {
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 {
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 {
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 {
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) {

View File

@ -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
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));

View File

@ -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
}); });
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
} }
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);
} }
}); });
} }

View File

@ -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 {
@Override @Override
public void startUpdate(View arg0) { public void startUpdate(View arg0) {
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }
} }

View File

@ -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;
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;
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 {
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 {
} }
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 {
}); });
} }
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 {
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {

View File

@ -30,7 +30,6 @@ import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
@ -51,12 +50,11 @@ import java.util.Map;
public class LaunchActivity extends ActionBarActivity implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate { public class LaunchActivity extends ActionBarActivity implements NotificationCenter.NotificationCenterDelegate, MessagesActivity.MessagesActivityDelegate {
private boolean finished = false; private boolean finished = false;
private NotificationView notificationView; private NotificationView notificationView;
private Uri photoPath = null;
private String videoPath = null; private String videoPath = null;
private String sendingText = null; private String sendingText = null;
private String documentPath = null; private ArrayList<Uri> photoPathsArray = null;
private ArrayList<Uri> imagesPathArray = null; private ArrayList<String> documentsPathsArray = null;
private ArrayList<String> documentsPathArray = null; private ArrayList<String> documentsOriginalPathsArray = null;
private ArrayList<TLRPC.User> contactsToSend = null; private ArrayList<TLRPC.User> contactsToSend = null;
private int currentConnectionState; private int currentConnectionState;
@ -64,7 +62,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication(); ApplicationLoader.postInitApplication();
if (!UserConfig.clientActivated) { if (!UserConfig.isClientActivated()) {
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) { if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreateFinish(savedInstanceState); super.onCreateFinish(savedInstanceState);
@ -101,7 +99,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
NotificationCenter.getInstance().addObserver(this, 703); NotificationCenter.getInstance().addObserver(this, 703);
if (fragmentsStack.isEmpty()) { if (fragmentsStack.isEmpty()) {
if (!UserConfig.clientActivated) { if (!UserConfig.isClientActivated()) {
addFragmentToStack(new LoginActivity()); addFragmentToStack(new LoginActivity());
} else { } else {
addFragmentToStack(new MessagesActivity(null)); addFragmentToStack(new MessagesActivity(null));
@ -162,15 +160,14 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
Integer push_enc_id = 0; Integer push_enc_id = 0;
Integer open_settings = 0; Integer open_settings = 0;
photoPath = null; photoPathsArray = null;
videoPath = null; videoPath = null;
sendingText = null; sendingText = null;
documentPath = null; documentsPathsArray = null;
imagesPathArray = null; documentsOriginalPathsArray = null;
documentsPathArray = null; contactsToSend = null;
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (intent != null && intent.getAction() != null && !restore) { if (intent != null && intent.getAction() != null && !restore) {
if (Intent.ACTION_SEND.equals(intent.getAction())) { if (Intent.ACTION_SEND.equals(intent.getAction())) {
boolean error = false; boolean error = false;
@ -273,19 +270,10 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
Uri uri = (Uri) parcelable; Uri uri = (Uri) parcelable;
if (uri != null && type != null && type.startsWith("image/")) { if (uri != null && type != null && type.startsWith("image/")) {
String tempPath = Utilities.getPath(uri); String tempPath = Utilities.getPath(uri);
boolean isGif = false; if (photoPathsArray == null) {
if (tempPath != null && tempPath.endsWith(".gif")) { photoPathsArray = new ArrayList<Uri>();
isGif = true;
documentPath = tempPath;
} else if (tempPath == null) {
isGif = MediaController.isGif(uri);
if (isGif) {
documentPath = MediaController.copyDocumentToCache(uri);
}
}
if (!isGif || documentPath == null) {
photoPath = uri;
} }
photoPathsArray.add(uri);
} else { } else {
path = Utilities.getPath(uri); path = Utilities.getPath(uri);
if (path != null) { if (path != null) {
@ -295,7 +283,12 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
if (type != null && type.startsWith("video/")) { if (type != null && type.startsWith("video/")) {
videoPath = path; videoPath = path;
} else { } else {
documentPath = path; if (documentsPathsArray == null) {
documentsPathsArray = new ArrayList<String>();
documentsOriginalPathsArray = new ArrayList<String>();
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(uri.toString());
} }
} else { } else {
error = true; error = true;
@ -317,32 +310,10 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
parcelable = Uri.parse(parcelable.toString()); parcelable = Uri.parse(parcelable.toString());
} }
Uri uri = (Uri) parcelable; Uri uri = (Uri) parcelable;
String tempPath = Utilities.getPath(uri); if (photoPathsArray == null) {
photoPathsArray = new ArrayList<Uri>();
boolean isGif = false;
if (tempPath != null && tempPath.endsWith(".gif")) {
isGif = true;
} else if (tempPath == null) {
isGif = MediaController.isGif(uri);
if (isGif) {
tempPath = MediaController.copyDocumentToCache(uri);
}
}
if (isGif && tempPath != null) {
if (documentsPathArray == null) {
documentsPathArray = new ArrayList<String>();
}
try {
documentsPathArray.add(tempPath);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else {
if (imagesPathArray == null) {
imagesPathArray = new ArrayList<Uri>();
}
imagesPathArray.add(uri);
} }
photoPathsArray.add(uri);
} }
} else { } else {
for (Parcelable parcelable : uris) { for (Parcelable parcelable : uris) {
@ -350,14 +321,20 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
parcelable = Uri.parse(parcelable.toString()); parcelable = Uri.parse(parcelable.toString());
} }
String path = Utilities.getPath((Uri) parcelable); String path = Utilities.getPath((Uri) parcelable);
String originalPath = parcelable.toString();
if (originalPath == null) {
originalPath = path;
}
if (path != null) { if (path != null) {
if (path.startsWith("file:")) { if (path.startsWith("file:")) {
path = path.replace("file://", ""); path = path.replace("file://", "");
} }
if (documentsPathArray == null) { if (documentsPathsArray == null) {
documentsPathArray = new ArrayList<String>(); documentsPathsArray = new ArrayList<String>();
documentsOriginalPathsArray = new ArrayList<String>();
} }
documentsPathArray.add(path); documentsPathsArray.add(path);
documentsOriginalPathsArray.add(originalPath);
} }
} }
} }
@ -417,7 +394,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
} }
if (push_user_id != 0) { if (push_user_id != 0) {
if (push_user_id == UserConfig.clientUserId) { if (push_user_id == UserConfig.getClientUserId()) {
open_settings = 1; open_settings = 1;
} else { } else {
Bundle args = new Bundle(); Bundle args = new Bundle();
@ -442,7 +419,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
pushOpened = true; pushOpened = true;
} }
} }
if (videoPath != null || photoPath != null || sendingText != null || documentPath != null || documentsPathArray != null || imagesPathArray != null || contactsToSend != null) { if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null) {
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putBoolean("onlySelect", true); args.putBoolean("onlySelect", true);
@ -488,37 +465,29 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
} }
ChatActivity fragment = new ChatActivity(args); ChatActivity fragment = new ChatActivity(args);
presentFragment(fragment, true); presentFragment(fragment, true);
if (photoPath != null) {
fragment.processSendingPhoto(null, photoPath);
}
if (videoPath != null) { if (videoPath != null) {
fragment.processSendingVideo(videoPath); fragment.processSendingVideo(videoPath);
} }
if (sendingText != null) { if (sendingText != null) {
fragment.processSendingText(sendingText); fragment.processSendingText(sendingText);
} }
if (documentPath != null) { if (photoPathsArray != null) {
fragment.processSendingDocument(documentPath); fragment.processSendingPhotos(null, photoPathsArray);
}
if (imagesPathArray != null) {
fragment.processSendingPhotos(null, imagesPathArray);
}
if (documentsPathArray != null) {
for (String path : documentsPathArray) {
fragment.processSendingDocument(path);
} }
if (documentsPathsArray != null) {
fragment.processSendingDocuments(documentsPathsArray, documentsOriginalPathsArray);
} }
if (contactsToSend != null && !contactsToSend.isEmpty()) { if (contactsToSend != null && !contactsToSend.isEmpty()) {
for (TLRPC.User user : contactsToSend) { for (TLRPC.User user : contactsToSend) {
MessagesController.getInstance().sendMessage(user, dialog_id); MessagesController.getInstance().sendMessage(user, dialog_id);
} }
} }
photoPath = null;
photoPathsArray = null;
videoPath = null; videoPath = null;
sendingText = null; sendingText = null;
documentPath = null; documentsPathsArray = null;
imagesPathArray = null; documentsOriginalPathsArray = null;
documentsPathArray = null;
contactsToSend = null; contactsToSend = null;
} }
} }
@ -535,7 +504,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
ApplicationLoader.lastPauseTime = System.currentTimeMillis(); ConnectionsManager.setAppPaused(true);
if (notificationView != null) { if (notificationView != null) {
notificationView.hide(false); notificationView.hide(false);
} }
@ -559,7 +528,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
} }
Utilities.checkForCrashes(this); Utilities.checkForCrashes(this);
Utilities.checkForUpdates(this); Utilities.checkForUpdates(this);
ApplicationLoader.resetLastPauseTime(); ConnectionsManager.setAppPaused(false);
actionBar.setBackOverlayVisible(currentConnectionState != 0); actionBar.setBackOverlayVisible(currentConnectionState != 0);
try { try {
NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
@ -602,7 +571,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
int rotation = manager.getDefaultDisplay().getRotation(); int rotation = manager.getDefaultDisplay().getRotation();
int height = Utilities.dp(48); int height = Utilities.dp(48);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(this) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
height = Utilities.dp(40); height = Utilities.dp(40);
} }
notificationView.applyOrientationPaddings(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90, height); notificationView.applyOrientationPaddings(rotation == Surface.ROTATION_270 || rotation == Surface.ROTATION_90, height);

View File

@ -60,6 +60,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
super.onFragmentCreate(); super.onFragmentCreate();
swipeBackEnabled = false;
NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats);
if (messageObject != null) { if (messageObject != null) {
NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces); NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
@ -314,7 +315,11 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
public void onPause() { public void onPause() {
super.onPause(); super.onPause();
if (mapView != null) { if (mapView != null) {
try {
mapView.onPause(); mapView.onPause();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
} }

View File

@ -10,6 +10,7 @@ package org.telegram.ui;
import android.animation.Animator; import android.animation.Animator;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
@ -17,6 +18,8 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
@ -34,6 +37,7 @@ import java.util.Set;
public class LoginActivity extends BaseFragment implements SlideView.SlideViewDelegate { public class LoginActivity extends BaseFragment implements SlideView.SlideViewDelegate {
private int currentViewNum = 0; private int currentViewNum = 0;
private SlideView[] views = new SlideView[3]; private SlideView[] views = new SlideView[3];
private ProgressDialog progressDialog;
private final static int done_button = 1; private final static int done_button = 1;
@ -79,6 +83,19 @@ public class LoginActivity extends BaseFragment implements SlideView.SlideViewDe
views[1] = (SlideView)fragmentView.findViewById(R.id.login_page2); views[1] = (SlideView)fragmentView.findViewById(R.id.login_page2);
views[2] = (SlideView)fragmentView.findViewById(R.id.login_page3); views[2] = (SlideView)fragmentView.findViewById(R.id.login_page3);
try {
if (views[0] == null || views[1] == null || views[2] == null) {
FrameLayout parent = (FrameLayout)((ScrollView) fragmentView).getChildAt(0);
for (int a = 0; a < views.length; a++) {
if (views[a] == null) {
views[a] = (SlideView)parent.getChildAt(a);
}
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
actionBarLayer.setTitle(views[0].getHeaderName()); actionBarLayer.setTitle(views[0].getHeaderName());
Bundle savedInstanceState = loadCurrentState(); Bundle savedInstanceState = loadCurrentState();
@ -205,29 +222,38 @@ public class LoginActivity extends BaseFragment implements SlideView.SlideViewDe
@Override @Override
public void needShowAlert(final String text) { public void needShowAlert(final String text) {
if (text == null) { if (text == null || getParentActivity() == null) {
return; return;
} }
getParentActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
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(text); builder.setMessage(text);
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showAlertDialog(builder); showAlertDialog(builder);
} }
});
}
@Override @Override
public void needShowProgress() { public void needShowProgress() {
Utilities.ShowProgressDialog(getParentActivity(), LocaleController.getString("Loading", R.string.Loading)); if (getParentActivity() == null || getParentActivity().isFinishing() || progressDialog != null) {
return;
}
progressDialog = new ProgressDialog(getParentActivity());
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
} }
@Override @Override
public void needHideProgress() { public void needHideProgress() {
Utilities.HideProgressDialog(getParentActivity()); if (progressDialog == null) {
return;
}
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
public void setPage(int page, boolean animated, Bundle params, boolean back) { public void setPage(int page, boolean animated, Bundle params, boolean back) {

View File

@ -57,6 +57,7 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
private boolean ignoreSelection = false; private boolean ignoreSelection = false;
private boolean ignoreOnTextChange = false; private boolean ignoreOnTextChange = false;
private boolean ignoreOnPhoneChange = false; private boolean ignoreOnPhoneChange = false;
private boolean nextPressed = false;
public LoginActivityPhoneView(Context context) { public LoginActivityPhoneView(Context context) {
super(context); super(context);
@ -319,6 +320,9 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
@Override @Override
public void onNextPressed() { public void onNextPressed() {
if (nextPressed) {
return;
}
if (countryState == 1) { if (countryState == 1) {
delegate.needShowAlert(LocaleController.getString("ChooseCountry", R.string.ChooseCountry)); delegate.needShowAlert(LocaleController.getString("ChooseCountry", R.string.ChooseCountry));
return; return;
@ -345,11 +349,15 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
final Bundle params = new Bundle(); final Bundle params = new Bundle();
params.putString("phone", "+" + codeField.getText() + phoneField.getText()); params.putString("phone", "+" + codeField.getText() + phoneField.getText());
params.putString("phoneFormated", phone); params.putString("phoneFormated", phone);
nextPressed = true;
delegate.needShowProgress(); delegate.needShowProgress();
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(final TLObject response, final TLRPC.TL_error error) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
nextPressed = false;
if (error == null) { if (error == null) {
final TLRPC.TL_auth_sentCode res = (TLRPC.TL_auth_sentCode)response; final TLRPC.TL_auth_sentCode res = (TLRPC.TL_auth_sentCode)response;
params.putString("phoneHash", res.phone_code_hash); params.putString("phoneHash", res.phone_code_hash);
@ -357,36 +365,31 @@ public class LoginActivityPhoneView extends SlideView implements AdapterView.OnI
if (res.phone_registered) { if (res.phone_registered) {
params.putString("registered", "true"); params.putString("registered", "true");
} }
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (delegate != null) { if (delegate != null) {
delegate.setPage(1, true, params, false); delegate.setPage(1, true, params, false);
} }
}
});
} else { } else {
if (delegate != null) { if (delegate != null && error.text != null) {
if (error.text != null) {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (error.text.contains("PHONE_NUMBER_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); delegate.needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode));
} else if (error.text.contains("PHONE_CODE_EXPIRED")) { } else if (error.text.contains("PHONE_CODE_EXPIRED")) {
delegate.needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); delegate.needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired));
} else if (error.text.contains("FLOOD_WAIT")) { } else if (error.text.startsWith("FLOOD_WAIT")) {
delegate.needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait)); delegate.needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else { } else {
delegate.needShowAlert(error.text); delegate.needShowAlert(error.text);
} }
} }
} }
}
if (delegate != null) { if (delegate != null) {
delegate.needHideProgress(); delegate.needHideProgress();
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); });
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
} }
@Override @Override

View File

@ -39,6 +39,7 @@ public class LoginActivityRegisterView extends SlideView {
private String phoneHash; private String phoneHash;
private String phoneCode; private String phoneCode;
private Bundle currentParams; private Bundle currentParams;
private boolean nextPressed = false;
public LoginActivityRegisterView(Context context) { public LoginActivityRegisterView(Context context) {
super(context); super(context);
@ -122,32 +123,36 @@ public class LoginActivityRegisterView extends SlideView {
@Override @Override
public void onNextPressed() { public void onNextPressed() {
if (nextPressed) {
return;
}
nextPressed = true;
TLRPC.TL_auth_signUp req = new TLRPC.TL_auth_signUp(); TLRPC.TL_auth_signUp req = new TLRPC.TL_auth_signUp();
req.phone_code = phoneCode; req.phone_code = phoneCode;
req.phone_code_hash = phoneHash; req.phone_code_hash = phoneHash;
req.phone_number = requestPhone; req.phone_number = requestPhone;
req.first_name = firstNameField.getText().toString(); req.first_name = firstNameField.getText().toString();
req.last_name = lastNameField.getText().toString(); req.last_name = lastNameField.getText().toString();
if (delegate != null) {
delegate.needShowProgress(); delegate.needShowProgress();
}
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(final TLObject response, final TLRPC.TL_error error) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
nextPressed = false;
if (delegate != null) { if (delegate != null) {
delegate.needHideProgress(); delegate.needHideProgress();
} }
if (error == null) { if (error == null) {
final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
TLRPC.TL_userSelf user = (TLRPC.TL_userSelf)res.user; TLRPC.TL_userSelf user = (TLRPC.TL_userSelf)res.user;
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp(); MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
ConnectionsManager.getInstance().cleanUp(); UserConfig.setCurrentUser(user);
UserConfig.currentUser = user;
UserConfig.clientActivated = true;
UserConfig.clientUserId = user.id;
UserConfig.saveConfig(true); UserConfig.saveConfig(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>(); ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(user); users.add(user);
@ -159,8 +164,6 @@ public class LoginActivityRegisterView extends SlideView {
delegate.needFinishActivity(); delegate.needFinishActivity();
} }
ConnectionsManager.getInstance().initPushConnection(); ConnectionsManager.getInstance().initPushConnection();
}
});
} else { } else {
if (delegate != null) { if (delegate != null) {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (error.text.contains("PHONE_NUMBER_INVALID")) {
@ -179,7 +182,9 @@ public class LoginActivityRegisterView extends SlideView {
} }
} }
} }
}, null, true, RPCRequest.RPCRequestClassGeneric); });
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassWithoutLogin);
} }
@Override @Override

View File

@ -48,10 +48,11 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
private Bundle currentParams; private Bundle currentParams;
private Timer timeTimer; private Timer timeTimer;
private final Integer timerSync = 1; private static final Integer timerSync = 1;
private volatile int time = 60000; private volatile int time = 60000;
private double lastCurrentTime; private double lastCurrentTime;
private boolean waitingForSms = false; private boolean waitingForSms = false;
private boolean nextPressed = false;
public LoginActivitySmsView(Context context) { public LoginActivitySmsView(Context context) {
super(context); super(context);
@ -129,18 +130,17 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
Utilities.showKeyboard(codeField); Utilities.showKeyboard(codeField);
codeField.requestFocus(); codeField.requestFocus();
try { destroyTimer();
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
timeText.setText(String.format("%s 1:00", LocaleController.getString("CallText", R.string.CallText))); timeText.setText(String.format("%s 1:00", LocaleController.getString("CallText", R.string.CallText)));
lastCurrentTime = System.currentTimeMillis(); lastCurrentTime = System.currentTimeMillis();
createTimer();
}
private void createTimer() {
if (timeTimer != null) {
return;
}
timeTimer = new Timer(); timeTimer = new Timer();
timeTimer.schedule(new TimerTask() { timeTimer.schedule(new TimerTask() {
@Override @Override
@ -158,12 +158,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds)); timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds));
} else { } else {
timeText.setText(LocaleController.getString("Calling", R.string.Calling)); timeText.setText(LocaleController.getString("Calling", R.string.Calling));
synchronized(timerSync) { destroyTimer();
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall(); TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall();
req.phone_number = requestPhone; req.phone_number = requestPhone;
req.phone_code_hash = phoneHash; req.phone_code_hash = phoneHash;
@ -171,7 +166,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
} }
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
} }
} }
}); });
@ -179,8 +174,25 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
}, 0, 1000); }, 0, 1000);
} }
private void destroyTimer() {
try {
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
@Override @Override
public void onNextPressed() { public void onNextPressed() {
if (nextPressed) {
return;
}
nextPressed = true;
waitingForSms = false; waitingForSms = false;
Utilities.setWaitingForSms(false); Utilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998); NotificationCenter.getInstance().removeObserver(this, 998);
@ -188,152 +200,68 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
req.phone_number = requestPhone; req.phone_number = requestPhone;
req.phone_code = codeField.getText().toString(); req.phone_code = codeField.getText().toString();
req.phone_code_hash = phoneHash; req.phone_code_hash = phoneHash;
try { destroyTimer();
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (delegate != null) { if (delegate != null) {
delegate.needShowProgress(); delegate.needShowProgress();
} }
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(final TLObject response, final TLRPC.TL_error error) {
if (delegate != null) {
delegate.needHideProgress();
}
if (error == null) {
final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response;
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
if (delegate == null) { if (delegate == null) {
return; return;
} }
try { delegate.needHideProgress();
synchronized(timerSync) { nextPressed = false;
if (timeTimer != null) { if (error == null) {
timeTimer.cancel(); TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response;
timeTimer = null; destroyTimer();
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp(); MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
ConnectionsManager.getInstance().cleanUp(); UserConfig.setCurrentUser(res.user);
UserConfig.currentUser = res.user;
UserConfig.clientActivated = true;
UserConfig.clientUserId = res.user.id;
UserConfig.saveConfig(true); UserConfig.saveConfig(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>(); ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(UserConfig.currentUser); users.add(res.user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().users.put(res.user.id, res.user); MessagesController.getInstance().users.put(res.user.id, res.user);
ContactsController.getInstance().checkAppAccount(); ContactsController.getInstance().checkAppAccount();
if (delegate != null) {
delegate.needFinishActivity(); delegate.needFinishActivity();
}
ConnectionsManager.getInstance().initPushConnection(); ConnectionsManager.getInstance().initPushConnection();
}
});
} else { } else {
if (error.text.contains("PHONE_NUMBER_UNOCCUPIED") && registered == null) { if (error.text.contains("PHONE_NUMBER_UNOCCUPIED") && registered == null) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
Bundle params = new Bundle(); Bundle params = new Bundle();
params.putString("phoneFormated", requestPhone); params.putString("phoneFormated", requestPhone);
params.putString("phoneHash", phoneHash); params.putString("phoneHash", phoneHash);
params.putString("code", req.phone_code); params.putString("code", req.phone_code);
delegate.setPage(2, true, params, false); delegate.setPage(2, true, params, false);
try { destroyTimer();
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
} else { } else {
if (timeTimer == null) { createTimer();
timeTimer = new Timer();
timeTimer.schedule(new TimerTask() {
@Override
public void run() {
double currentTime = System.currentTimeMillis();
double diff = currentTime - lastCurrentTime;
time -= diff;
lastCurrentTime = currentTime;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (time >= 1000) {
int minutes = time / 1000 / 60;
int seconds = time / 1000 - minutes * 60;
timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds));
} else {
timeText.setText(LocaleController.getString("Calling", R.string.Calling));
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall();
req.phone_number = requestPhone;
req.phone_code_hash = phoneHash;
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}
}
});
}
}, 0, 1000);
}
if (delegate != null) {
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (error.text.contains("PHONE_NUMBER_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); delegate.needShowAlert(LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
} else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) { } else if (error.text.contains("PHONE_CODE_EMPTY") || error.text.contains("PHONE_CODE_INVALID")) {
delegate.needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode)); delegate.needShowAlert(LocaleController.getString("InvalidCode", R.string.InvalidCode));
} else if (error.text.contains("PHONE_CODE_EXPIRED")) { } else if (error.text.contains("PHONE_CODE_EXPIRED")) {
delegate.needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired)); delegate.needShowAlert(LocaleController.getString("CodeExpired", R.string.CodeExpired));
} else if (error.text.startsWith("FLOOD_WAIT")) {
delegate.needShowAlert(LocaleController.getString("FloodWait", R.string.FloodWait));
} else { } else {
delegate.needShowAlert(error.text); delegate.needShowAlert(error.text);
} }
} }
} }
} }
});
} }
}, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors | RPCRequest.RPCRequestClassWithoutLogin);
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() {
try { destroyTimer();
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
currentParams = null; currentParams = null;
Utilities.setWaitingForSms(false); Utilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998); NotificationCenter.getInstance().removeObserver(this, 998);
@ -345,16 +273,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
super.onDestroyActivity(); super.onDestroyActivity();
Utilities.setWaitingForSms(false); Utilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998); NotificationCenter.getInstance().removeObserver(this, 998);
try { destroyTimer();
synchronized(timerSync) {
if (timeTimer != null) {
timeTimer.cancel();
timeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
waitingForSms = false; waitingForSms = false;
} }

View File

@ -20,7 +20,6 @@ import android.view.ViewTreeObserver;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.AbsListView; import android.widget.AbsListView;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView; import android.widget.GridView;
import android.widget.TextView; import android.widget.TextView;
@ -32,6 +31,7 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.objects.PhotoObject; import org.telegram.objects.PhotoObject;
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.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ActionBar.BaseFragment; import org.telegram.ui.Views.ActionBar.BaseFragment;
@ -347,7 +347,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {

View File

@ -17,7 +17,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;
@ -33,6 +32,7 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig; import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Cells.ChatOrUserCell;
import org.telegram.ui.Cells.DialogCell; import org.telegram.ui.Cells.DialogCell;
import org.telegram.ui.Views.ActionBar.ActionBarLayer; import org.telegram.ui.Views.ActionBar.ActionBarLayer;
@ -297,7 +297,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
messagesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { messagesListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override @Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (onlySelect || searching && searchWas) { if (onlySelect || searching && searchWas || getParentActivity() == null) {
return false; return false;
} }
TLRPC.TL_dialog dialog; TLRPC.TL_dialog dialog;
@ -324,7 +324,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (which == 0) { if (which == 0) {
MessagesController.getInstance().deleteDialog(selectedDialog, 0, true); MessagesController.getInstance().deleteDialog(selectedDialog, 0, true);
} else if (which == 1) { } else if (which == 1) {
MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().users.get(UserConfig.clientUserId), null); MessagesController.getInstance().deleteUserFromChat((int) -selectedDialog, MessagesController.getInstance().users.get(UserConfig.getClientUserId()), null);
MessagesController.getInstance().deleteDialog(selectedDialog, 0, false); MessagesController.getInstance().deleteDialog(selectedDialog, 0, false);
} }
} }
@ -455,6 +455,9 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private void didSelectResult(final long dialog_id, boolean useAlert) { private void didSelectResult(final long dialog_id, 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));
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
@ -555,7 +558,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} }
} }
private class MessagesAdapter extends BaseAdapter { private class MessagesAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public MessagesAdapter(Context context) { public MessagesAdapter(Context context) {

View File

@ -100,6 +100,9 @@ public class PhotoCropActivity extends BaseFragment {
} else { } else {
draggingState = 0; draggingState = 0;
} }
if (draggingState != 0) {
PhotoCropView.this.requestDisallowInterceptTouchEvent(true);
}
oldX = x; oldX = x;
oldY = y; oldY = y;
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) { } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

View File

@ -18,7 +18,6 @@ import android.view.ViewGroup;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button; import android.widget.Button;
import android.widget.GridView; import android.widget.GridView;
import android.widget.ImageView; import android.widget.ImageView;
@ -32,6 +31,7 @@ import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
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.BaseFragment; import org.telegram.ui.Views.ActionBar.BaseFragment;
@ -107,7 +107,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
} }
} else if (id == 1) { } else if (id == 1) {
if (delegate != null) { if (delegate != null) {
finishFragment(); finishFragment(false);
delegate.startPhotoSelectActivity(); delegate.startPhotoSelectActivity();
} }
} }
@ -441,7 +441,7 @@ public class PhotoPickerActivity extends BaseFragment implements NotificationCen
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {

View File

@ -42,6 +42,7 @@ import android.widget.Button;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.ConnectionsManager; import org.telegram.messenger.ConnectionsManager;
@ -101,6 +102,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean overlayViewVisible = true; private boolean overlayViewVisible = true;
private int animationInProgress = 0; private int animationInProgress = 0;
private PlaceProviderObject showAfterAnimation;
private PlaceProviderObject hideAfterAnimation;
private boolean disableShowCheck = false; private boolean disableShowCheck = false;
private Animation.AnimationListener animationListener; private Animation.AnimationListener animationListener;
@ -158,6 +161,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean zoomAnimation = false; private boolean zoomAnimation = false;
private int switchImageAfterAnimation = 0; private int switchImageAfterAnimation = 0;
private VelocityTracker velocityTracker = null; private VelocityTracker velocityTracker = null;
private Scroller scroller = null;
private ArrayList<MessageObject> imagesArrTemp = new ArrayList<MessageObject>(); private ArrayList<MessageObject> imagesArrTemp = new ArrayList<MessageObject>();
private HashMap<Integer, MessageObject> imagesByIdsTemp = new HashMap<Integer, MessageObject>(); private HashMap<Integer, MessageObject> imagesByIdsTemp = new HashMap<Integer, MessageObject>();
@ -310,13 +314,18 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
imagesArrLocations.clear(); imagesArrLocations.clear();
imagesArrLocationsSizes.clear(); imagesArrLocationsSizes.clear();
for (TLRPC.Photo photo : photos) { for (TLRPC.Photo photo : photos) {
if (photo instanceof TLRPC.TL_photoEmpty) { if (photo instanceof TLRPC.TL_photoEmpty || photo.sizes == null) {
continue; continue;
} }
TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 640, 640); TLRPC.PhotoSize sizeFull = PhotoObject.getClosestPhotoSizeWithSize(photo.sizes, 640, 640);
if (sizeFull != null) { if (sizeFull != null) {
if (currentFileLocation != null && sizeFull.location.local_id == currentFileLocation.local_id && sizeFull.location.volume_id == currentFileLocation.volume_id) { if (currentFileLocation != null) {
for (TLRPC.PhotoSize size : photo.sizes) {
if (size.location.local_id == currentFileLocation.local_id && size.location.volume_id == currentFileLocation.volume_id) {
setToImage = imagesArrLocations.size(); setToImage = imagesArrLocations.size();
break;
}
}
} }
imagesArrLocations.add(sizeFull.location); imagesArrLocations.add(sizeFull.location);
imagesArrLocationsSizes.add(sizeFull.size); imagesArrLocationsSizes.add(sizeFull.size);
@ -327,6 +336,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (setToImage != -1) { if (setToImage != -1) {
setImageIndex(setToImage, true); setImageIndex(setToImage, true);
} else { } else {
imagesArrLocations.add(0, currentFileLocation);
imagesArrLocationsSizes.add(0, 0);
setImageIndex(0, true); setImageIndex(0, true);
} }
if (fromCache) { if (fromCache) {
@ -423,6 +434,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
public void setParentActivity(Activity activity) { public void setParentActivity(Activity activity) {
parentActivity = activity; parentActivity = activity;
scroller = new Scroller(activity);
windowView = new FrameLayoutTouchListener(activity); windowView = new FrameLayoutTouchListener(activity);
windowView.setBackgroundDrawable(backgroundDrawable); windowView.setBackgroundDrawable(backgroundDrawable);
windowView.setFocusable(false); windowView.setFocusable(false);
@ -1038,7 +1051,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (messageObject.messageOwner.to_id.chat_id != 0) { if (messageObject.messageOwner.to_id.chat_id != 0) {
currentDialogId = -messageObject.messageOwner.to_id.chat_id; currentDialogId = -messageObject.messageOwner.to_id.chat_id;
} else { } else {
if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) { if (messageObject.messageOwner.to_id.user_id == UserConfig.getClientUserId()) {
currentDialogId = messageObject.messageOwner.from_id; currentDialogId = messageObject.messageOwner.from_id;
} else { } else {
currentDialogId = messageObject.messageOwner.to_id.user_id; currentDialogId = messageObject.messageOwner.to_id.user_id;
@ -1076,7 +1089,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (messageObject.messageOwner.to_id.chat_id != 0) { if (messageObject.messageOwner.to_id.chat_id != 0) {
currentDialogId = -messageObject.messageOwner.to_id.chat_id; currentDialogId = -messageObject.messageOwner.to_id.chat_id;
} else { } else {
if (messageObject.messageOwner.to_id.user_id == UserConfig.clientUserId) { if (messageObject.messageOwner.to_id.user_id == UserConfig.getClientUserId()) {
currentDialogId = messageObject.messageOwner.from_id; currentDialogId = messageObject.messageOwner.from_id;
} else { } else {
currentDialogId = messageObject.messageOwner.to_id.user_id; currentDialogId = messageObject.messageOwner.to_id.user_id;
@ -1147,15 +1160,20 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
} }
if (!init) {
if (android.os.Build.VERSION.SDK_INT >= 11 && currentPlaceObject != null) { if (android.os.Build.VERSION.SDK_INT >= 11 && currentPlaceObject != null) {
if (animationInProgress == 0) {
currentPlaceObject.imageReceiver.setVisible(true, true); currentPlaceObject.imageReceiver.setVisible(true, true);
} else {
showAfterAnimation = currentPlaceObject;
} }
} }
currentPlaceObject = placeProvider.getPlaceForPhoto(currentMessageObject, currentFileLocation, currentIndex); currentPlaceObject = placeProvider.getPlaceForPhoto(currentMessageObject, currentFileLocation, currentIndex);
if (!init) {
if (android.os.Build.VERSION.SDK_INT >= 11 && currentPlaceObject != null) { if (android.os.Build.VERSION.SDK_INT >= 11 && currentPlaceObject != null) {
if (animationInProgress == 0) {
currentPlaceObject.imageReceiver.setVisible(false, true); currentPlaceObject.imageReceiver.setVisible(false, true);
} else {
hideAfterAnimation = currentPlaceObject;
} }
} }
@ -1343,6 +1361,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
disableShowCheck = true; disableShowCheck = true;
animationInProgress = 1;
onPhotoShow(messageObject, fileLocation, messages, photos, index, object); onPhotoShow(messageObject, fileLocation, messages, photos, index, object);
isVisible = true; isVisible = true;
backgroundDrawable.setAlpha(255); backgroundDrawable.setAlpha(255);
@ -1352,8 +1371,6 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if(android.os.Build.VERSION.SDK_INT >= 11) { if(android.os.Build.VERSION.SDK_INT >= 11) {
Utilities.lockOrientation(parentActivity); Utilities.lockOrientation(parentActivity);
animationInProgress = 1;
animatingImageView.setVisibility(View.VISIBLE); animatingImageView.setVisibility(View.VISIBLE);
animatingImageView.setImageBitmap(object.thumb); animatingImageView.setImageBitmap(object.thumb);
@ -1419,6 +1436,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
containerView.invalidate(); containerView.invalidate();
animatingImageView.setVisibility(View.GONE); animatingImageView.setVisibility(View.GONE);
Utilities.unlockOrientation(parentActivity); Utilities.unlockOrientation(parentActivity);
if (showAfterAnimation != null) {
showAfterAnimation.imageReceiver.setVisible(true, true);
}
if (hideAfterAnimation != null) {
hideAfterAnimation.imageReceiver.setVisible(false, true);
}
} }
}); });
animatorSet.start(); animatorSet.start();
@ -1437,6 +1460,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
}); });
} else { } else {
animationInProgress = 0;
containerView.invalidate(); containerView.invalidate();
AnimationSet animationSet = new AnimationSet(true); AnimationSet animationSet = new AnimationSet(true);
AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f); AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
@ -1604,7 +1628,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
currentPathObject = null; currentPathObject = null;
currentThumb = null; currentThumb = null;
centerImage.setImageBitmap((Bitmap)null); centerImage.setImageBitmap((Bitmap)null);
leftImage.setImageBitmap((Bitmap) null); leftImage.setImageBitmap((Bitmap)null);
rightImage.setImageBitmap((Bitmap)null); rightImage.setImageBitmap((Bitmap)null);
if (android.os.Build.VERSION.SDK_INT >= 11 && object != null) { if (android.os.Build.VERSION.SDK_INT >= 11 && object != null) {
object.imageReceiver.setVisible(true, true); object.imageReceiver.setVisible(true, true);
@ -1668,6 +1692,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN || ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) { if (ev.getActionMasked() == MotionEvent.ACTION_DOWN || ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
if (!scroller.isFinished()) {
scroller.abortAnimation();
}
if (!draggingDown && !changingPage) { if (!draggingDown && !changingPage) {
if (canZoom && ev.getPointerCount() == 2) { if (canZoom && ev.getPointerCount() == 2) {
pinchStartDistance = (float) Math.hypot(ev.getX(1) - ev.getX(0), ev.getY(1) - ev.getY(0)); pinchStartDistance = (float) Math.hypot(ev.getX(1) - ev.getX(0), ev.getY(1) - ev.getY(0));
@ -1703,7 +1730,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (velocityTracker != null) { if (velocityTracker != null) {
velocityTracker.addMovement(ev); velocityTracker.addMovement(ev);
} }
if (canDragDown && !draggingDown && scale == 1 && Math.abs(ev.getY() - dragY) >= Utilities.dp(30)) { float dx = Math.abs(ev.getX() - moveStartX);
float dy = Math.abs(ev.getY() - dragY);
if (canDragDown && !draggingDown && scale == 1 && dy >= Utilities.dp(30) && dy / 2 > dx) {
draggingDown = true; draggingDown = true;
moving = false; moving = false;
dragY = ev.getY(); dragY = ev.getY();
@ -1734,9 +1763,19 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (translationX < minX && !rightImage.hasImage() || translationX > maxX && !leftImage.hasImage()) { if (translationX < minX && !rightImage.hasImage() || translationX > maxX && !leftImage.hasImage()) {
moveDx /= 3.0f; moveDx /= 3.0f;
} }
if (maxY == 0 && minY == 0) {
if (translationY - moveDy < minY) {
translationY = minY;
moveDy = 0;
} else if (translationY - moveDy > maxY) {
translationY = maxY;
moveDy = 0;
}
} else {
if (translationY < minY || translationY > maxY) { if (translationY < minY || translationY > maxY) {
moveDy /= 3.0f; moveDy /= 3.0f;
} }
}
translationX -= moveDx; translationX -= moveDx;
if (scale != 1) { if (scale != 1) {
@ -1900,6 +1939,10 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
if (ai != -1) { if (ai != -1) {
if (!scroller.isFinished()) {
scroller.abortAnimation();
}
float ts = scale + (animateToScale - scale) * ai; float ts = scale + (animateToScale - scale) * ai;
float tx = translationX + (animateToX - translationX) * ai; float tx = translationX + (animateToX - translationX) * ai;
float ty = translationY + (animateToY - translationY) * ai; float ty = translationY + (animateToY - translationY) * ai;
@ -1922,6 +1965,17 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
Utilities.unlockOrientation(parentActivity); Utilities.unlockOrientation(parentActivity);
zoomAnimation = false; zoomAnimation = false;
} }
if (!scroller.isFinished()) {
if (scroller.computeScrollOffset()) {
if (scroller.getStartX() < maxX && scroller.getStartX() > minX) {
translationX = scroller.getCurrX();
}
if (scroller.getStartY() < maxY && scroller.getStartY() > minY) {
translationY = scroller.getCurrY();
}
containerView.invalidate();
}
}
if (switchImageAfterAnimation != 0) { if (switchImageAfterAnimation != 0) {
if (switchImageAfterAnimation == 1) { if (switchImageAfterAnimation == 1) {
setImageIndex(currentIndex + 1, false); setImageIndex(currentIndex + 1, false);
@ -2097,6 +2151,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
@Override @Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (scale != 1) {
scroller.abortAnimation();
scroller.fling(Math.round(translationX), Math.round(translationY), Math.round(velocityX), Math.round(velocityY), (int) minX, (int) maxX, (int) minY, (int) maxY);
containerView.postInvalidate();
}
return false; return false;
} }

View File

@ -0,0 +1,392 @@
/*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package org.telegram.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.ColorPickerView;
public class ProfileNotificationsActivity extends BaseFragment {
private ListView listView;
private long dialog_id;
private int settingsNotificationsRow;
private int settingsVibrateRow;
private int settingsSoundRow;
private int settingsLedRow;
private int rowCount = 0;
public ProfileNotificationsActivity(Bundle args) {
super(args);
dialog_id = args.getLong("dialog_id");
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
}
@Override
public boolean onFragmentCreate() {
settingsNotificationsRow = rowCount++;
settingsVibrateRow = rowCount++;
settingsLedRow = rowCount++;
settingsSoundRow = rowCount++;
return super.onFragmentCreate();
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
if (fragmentView == null) {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
actionBarLayer.setTitle(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
}
}
});
fragmentView = inflater.inflate(R.layout.settings_layout, container, false);
listView = (ListView)fragmentView.findViewById(R.id.listView);
listView.setAdapter(new ListAdapter(getParentActivity()));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == settingsVibrateRow || i == settingsNotificationsRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setItems(new CharSequence[] {
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("Enabled", R.string.Enabled),
LocaleController.getString("Disabled", R.string.Disabled)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == settingsVibrateRow) {
editor.putInt("vibrate_" + dialog_id, which);
} else if (i == settingsNotificationsRow) {
editor.putInt("notify2_" + dialog_id, which);
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
} else if (i == settingsSoundRow) {
try {
Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
Uri currentSound = null;
String defaultPath = null;
Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
String path = preferences.getString("sound_path_" + dialog_id, defaultPath);
if (path != null && !path.equals("NoSound")) {
if (path.equals(defaultPath)) {
currentSound = defaultUri;
} else {
currentSound = Uri.parse(path);
}
}
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
getParentActivity().startActivityForResult(tmpIntent, 12);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else if (i == settingsLedRow) {
if (getParentActivity() == null) {
return;
}
LayoutInflater li = (LayoutInflater)getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_color_dialog_layout, null, false);
final ColorPickerView colorPickerView = (ColorPickerView)view.findViewById(R.id.color_picker);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (preferences.contains("color_" + dialog_id)) {
colorPickerView.setOldCenterColor(preferences.getInt("color_" + dialog_id, 0xff00ff00));
} else {
if ((int)dialog_id < 0) {
colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00));
} else {
colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00));
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor));
builder.setView(view);
builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("color_" + dialog_id, colorPickerView.getColor());
editor.commit();
listView.invalidateViews();
}
});
builder.setNeutralButton(LocaleController.getString("Disabled", R.string.Disabled), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("color_" + dialog_id, 0);
editor.commit();
listView.invalidateViews();
}
});
builder.setNegativeButton(LocaleController.getString("Default", R.string.Default), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.remove("color_" + dialog_id);
editor.commit();
listView.invalidateViews();
}
});
showAlertDialog(builder);
}
}
});
} else {
ViewGroup parent = (ViewGroup)fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
}
}
return fragmentView;
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
String name = null;
if (ringtone != null) {
Ringtone rng = RingtoneManager.getRingtone(ApplicationLoader.applicationContext, ringtone);
if (rng != null) {
if(ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
name = LocaleController.getString("Default", R.string.Default);
} else {
name = rng.getTitle(getParentActivity());
}
rng.stop();
}
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (requestCode == 12) {
if (name != null && ringtone != null) {
editor.putString("sound_" + dialog_id, name);
editor.putString("sound_path_" + dialog_id, ringtone.toString());
} else {
editor.putString("sound_" + dialog_id, "NoSound");
editor.putString("sound_path_" + dialog_id, "NoSound");
}
}
editor.commit();
listView.invalidateViews();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
public ListAdapter(Context context) {
mContext = context;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int i) {
return true;
}
@Override
public int getCount() {
return rowCount;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
int type = getItemViewType(i);
if (type == 0) {
if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.user_profile_leftright_row_layout, viewGroup, false);
}
TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsVibrateRow) {
textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("vibrate_" + dialog_id, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} else if (i == settingsNotificationsRow) {
textView.setText(LocaleController.getString("Notifications", R.string.Notifications));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("notify2_" + dialog_id, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
}
} if (type == 1) {
if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_detail_layout, viewGroup, false);
}
TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsSoundRow) {
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
String name = preferences.getString("sound_" + dialog_id, LocaleController.getString("Default", R.string.Default));
if (name.equals("NoSound")) {
detailTextView.setText(LocaleController.getString("NoSound", R.string.NoSound));
} else {
detailTextView.setText(name);
}
textView.setText(LocaleController.getString("Sound", R.string.Sound));
divider.setVisibility(View.INVISIBLE);
}
} else if (type == 2) {
if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_color_layout, viewGroup, false);
}
TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
View colorView = view.findViewById(R.id.settings_color);
View divider = view.findViewById(R.id.settings_row_divider);
textView.setText(LocaleController.getString("LedColor", R.string.LedColor));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (preferences.contains("color_" + dialog_id)) {
colorView.setBackgroundColor(preferences.getInt("color_" + dialog_id, 0xff00ff00));
} else {
if ((int)dialog_id < 0) {
colorView.setBackgroundColor(preferences.getInt("GroupLed", 0xff00ff00));
} else {
colorView.setBackgroundColor(preferences.getInt("MessagesLed", 0xff00ff00));
}
}
divider.setVisibility(View.VISIBLE);
}
return view;
}
@Override
public int getItemViewType(int i) {
if (i == settingsNotificationsRow || i == settingsVibrateRow) {
return 0;
} else if (i == settingsSoundRow) {
return 1;
} else if (i == settingsLedRow) {
return 2;
}
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public boolean isEmpty() {
return false;
}
}
}

View File

@ -28,7 +28,6 @@ import android.view.MotionEvent;
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.ImageButton; import android.widget.ImageButton;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
@ -53,6 +52,7 @@ import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
import org.telegram.objects.PhotoObject; import org.telegram.objects.PhotoObject;
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.AvatarUpdater; import org.telegram.ui.Views.AvatarUpdater;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
@ -127,15 +127,15 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (error == null) {
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
if (user == null) { if (user == null) {
return; return;
} }
MessagesController.getInstance().users.put(user.id, user); MessagesController.getInstance().users.put(user.id, user);
} else { } else {
UserConfig.currentUser = user; UserConfig.setCurrentUser(user);
} }
if (user == null) { if (user == null) {
return; return;
@ -240,6 +240,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == textSizeRow) { if (i == textSizeRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize)); builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
builder.setItems(new CharSequence[]{String.format("%d", 12), String.format("%d", 13), String.format("%d", 14), String.format("%d", 15), String.format("%d", 16), String.format("%d", 17), String.format("%d", 18), String.format("%d", 19), String.format("%d", 20), String.format("%d", 21), String.format("%d", 22), String.format("%d", 23), String.format("%d", 24)}, new DialogInterface.OnClickListener() { builder.setItems(new CharSequence[]{String.format("%d", 12), String.format("%d", 13), String.format("%d", 14), String.format("%d", 15), String.format("%d", 16), String.format("%d", 17), String.format("%d", 18), String.format("%d", 19), String.format("%d", 20), String.format("%d", 21), String.format("%d", 22), String.format("%d", 23), String.format("%d", 24)}, new DialogInterface.OnClickListener() {
@ -273,6 +276,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (i == backgroundRow) { } else if (i == backgroundRow) {
presentFragment(new SettingsWallpapersActivity()); presentFragment(new SettingsWallpapersActivity());
} else if (i == askQuestionRow) { } else if (i == askQuestionRow) {
if (getParentActivity() == null) {
return;
}
final TextView message = new TextView(getParentActivity()); final TextView message = new TextView(getParentActivity());
message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo))); message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo)));
message.setTextSize(18); message.setTextSize(18);
@ -303,6 +309,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
listView.invalidateViews(); listView.invalidateViews();
} }
} else if (i == terminateSessionsRow) { } else if (i == terminateSessionsRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -312,16 +321,27 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations(); TLRPC.TL_auth_resetAuthorizations req = new TLRPC.TL_auth_resetAuthorizations();
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(final TLObject response, final TLRPC.TL_error error) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (getParentActivity() == null) {
return;
}
if (error == null && response instanceof TLRPC.TL_boolTrue) { if (error == null && response instanceof TLRPC.TL_boolTrue) {
Toast toast = Toast.makeText(getParentActivity(), R.string.TerminateAllSessions, Toast.LENGTH_SHORT); Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("TerminateAllSessions", R.string.TerminateAllSessions), Toast.LENGTH_SHORT);
toast.show(); toast.show();
} else { } else {
Toast toast = Toast.makeText(getParentActivity(), R.string.UnknownError, Toast.LENGTH_SHORT); Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("UnknownError", R.string.UnknownError), Toast.LENGTH_SHORT);
toast.show(); toast.show();
} }
}
});
UserConfig.registeredForPush = false; UserConfig.registeredForPush = false;
UserConfig.registeredForInternalPush = false;
UserConfig.saveConfig(false);
MessagesController.getInstance().registerForPush(UserConfig.pushString); MessagesController.getInstance().registerForPush(UserConfig.pushString);
ConnectionsManager.getInstance().initPushConnection();
} }
}, null, true, RPCRequest.RPCRequestClassGeneric); }, null, true, RPCRequest.RPCRequestClassGeneric);
} }
@ -331,6 +351,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (i == languageRow) { } else if (i == languageRow) {
presentFragment(new LanguageSelectActivity()); presentFragment(new LanguageSelectActivity());
} else if (i == switchBackendButtonRow) { } else if (i == switchBackendButtonRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -352,6 +375,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} else if (i == contactsReimportRow) { } else if (i == contactsReimportRow) {
} else if (i == contactsSortRow) { } else if (i == contactsSortRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy));
builder.setItems(new CharSequence[] { builder.setItems(new CharSequence[] {
@ -373,6 +399,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder); showAlertDialog(builder);
} else if (i == photoDownloadChatRow || i == photoDownloadPrivateRow || i == audioDownloadChatRow || i == audioDownloadPrivateRow) { } else if (i == photoDownloadChatRow || i == photoDownloadPrivateRow || i == audioDownloadChatRow || i == audioDownloadPrivateRow) {
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.setItems(new CharSequence[] { builder.setItems(new CharSequence[] {
@ -418,7 +447,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
if (fileLocation == null) { if (fileLocation == null) {
return null; return null;
} }
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) { if (user != null && user.photo != null && user.photo.photo_big != null) {
TLRPC.FileLocation photoBig = user.photo.photo_big; TLRPC.FileLocation photoBig = user.photo.photo_big;
if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) {
@ -434,7 +463,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
object.viewY = coords[1] - Utilities.statusBarHeight; object.viewY = coords[1] - Utilities.statusBarHeight;
object.parentView = listView; object.parentView = listView;
object.imageReceiver = avatarImage.imageReceiver; object.imageReceiver = avatarImage.imageReceiver;
object.user_id = UserConfig.clientUserId; object.user_id = UserConfig.getClientUserId();
object.thumb = object.imageReceiver.getBitmap(); object.thumb = object.imageReceiver.getBitmap();
object.size = -1; object.size = -1;
return object; return object;
@ -607,7 +636,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {
@ -667,13 +696,16 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
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;
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
} }
if (user == null) { if (user == null) {
return; return;
@ -691,7 +723,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0 && full) { if (i == 0 && full) {
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) { if (user != null && user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this);
} }
@ -703,28 +735,28 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto(); TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto();
req.id = new TLRPC.TL_inputPhotoEmpty(); req.id = new TLRPC.TL_inputPhotoEmpty();
req.crop = new TLRPC.TL_inputPhotoCropAuto(); req.crop = new TLRPC.TL_inputPhotoCropAuto();
UserConfig.currentUser.photo = new TLRPC.TL_userProfilePhotoEmpty(); UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty();
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
} }
if (user == null) { if (user == null) {
return; return;
} }
if (user != null) { if (user != null) {
user.photo = UserConfig.currentUser.photo; user.photo = UserConfig.getCurrentUser().photo;
} }
NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL); NotificationCenter.getInstance().postNotificationName(MessagesController.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (error == null) {
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
MessagesController.getInstance().users.put(user.id, user); MessagesController.getInstance().users.put(user.id, user);
} else { } else {
UserConfig.currentUser = user; UserConfig.setCurrentUser(user);
} }
if (user == null) { if (user == null) {
return; return;
@ -757,9 +789,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
textView = (TextView)view.findViewById(R.id.settings_name); textView = (TextView)view.findViewById(R.id.settings_name);
Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf"); Typeface typeface = Utilities.getTypeface("fonts/rmedium.ttf");
textView.setTypeface(typeface); textView.setTypeface(typeface);
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
} }
if (user != null) { if (user != null) {
textView.setText(Utilities.formatName(user.first_name, user.last_name)); textView.setText(Utilities.formatName(user.first_name, user.last_name));
@ -804,7 +836,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
TextView textView = (TextView)view.findViewById(R.id.settings_row_text); TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
View divider = view.findViewById(R.id.settings_row_divider); View divider = view.findViewById(R.id.settings_row_divider);
if (i == numberRow) { if (i == numberRow) {
TLRPC.User user = UserConfig.currentUser; TLRPC.User user = UserConfig.getCurrentUser();
if (user != null && user.phone != null && user.phone.length() != 0) { if (user != null && user.phone != null && user.phone.length() != 0) {
textView.setText(PhoneFormat.getInstance().format("+" + user.phone)); textView.setText(PhoneFormat.getInstance().format("+" + user.phone));
} else { } else {
@ -890,6 +922,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
textView.setOnClickListener(new View.OnClickListener() { textView.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());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -898,10 +933,10 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
NotificationCenter.getInstance().postNotificationName(1234); NotificationCenter.getInstance().postNotificationName(1234);
MessagesController.getInstance().unregistedPush(); MessagesController.getInstance().unregistedPush();
MessagesController.getInstance().logOut();
UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp(); MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
ConnectionsManager.getInstance().cleanUp();
UserConfig.clearConfig();
} }
}); });
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);

View File

@ -16,7 +16,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;
@ -30,6 +29,7 @@ import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest; import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.ChatOrUserCell; import org.telegram.ui.Cells.ChatOrUserCell;
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;
@ -120,7 +120,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override @Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i >= blockedContacts.size()) { if (i >= blockedContacts.size() || getParentActivity() == null) {
return true; return true;
} }
selectedUserId = blockedContacts.get(i).user_id; selectedUserId = blockedContacts.get(i).user_id;
@ -276,7 +276,7 @@ public class SettingsBlockedUsers extends BaseFragment implements NotificationCe
}, null, true, RPCRequest.RPCRequestClassGeneric); }, null, true, RPCRequest.RPCRequestClassGeneric);
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {

View File

@ -65,9 +65,9 @@ public class SettingsChangeNameActivity extends BaseFragment {
fragmentView = inflater.inflate(R.layout.settings_change_name_layout, container, false); fragmentView = inflater.inflate(R.layout.settings_change_name_layout, container, false);
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user == null) { if (user == null) {
user = UserConfig.currentUser; user = UserConfig.getCurrentUser();
} }
firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field); firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field);
@ -126,12 +126,12 @@ public class SettingsChangeNameActivity extends BaseFragment {
private void saveName() { private void saveName() {
TLRPC.TL_account_updateProfile req = new TLRPC.TL_account_updateProfile(); TLRPC.TL_account_updateProfile req = new TLRPC.TL_account_updateProfile();
if (UserConfig.currentUser == null || lastNameField.getText() == null || firstNameField.getText() == null) { if (UserConfig.getCurrentUser() == null || lastNameField.getText() == null || firstNameField.getText() == null) {
return; return;
} }
UserConfig.currentUser.first_name = req.first_name = firstNameField.getText().toString(); UserConfig.getCurrentUser().first_name = req.first_name = firstNameField.getText().toString();
UserConfig.currentUser.last_name = req.last_name = lastNameField.getText().toString(); UserConfig.getCurrentUser().last_name = req.last_name = lastNameField.getText().toString();
TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.clientUserId); TLRPC.User user = MessagesController.getInstance().users.get(UserConfig.getClientUserId());
if (user != null) { if (user != null) {
user.first_name = req.first_name; user.first_name = req.first_name;
user.last_name = req.last_name; user.last_name = req.last_name;

View File

@ -22,7 +22,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.ImageView; import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
@ -37,8 +36,10 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest; import org.telegram.messenger.RPCRequest;
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.BaseFragment; import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.ColorPickerView;
public class SettingsNotificationsActivity extends BaseFragment { public class SettingsNotificationsActivity extends BaseFragment {
private ListView listView; private ListView listView;
@ -50,11 +51,13 @@ public class SettingsNotificationsActivity extends BaseFragment {
private int messagePreviewRow; private int messagePreviewRow;
private int messageVibrateRow; private int messageVibrateRow;
private int messageSoundRow; private int messageSoundRow;
private int messageLedRow;
private int groupSectionRow; private int groupSectionRow;
private int groupAlertRow; private int groupAlertRow;
private int groupPreviewRow; private int groupPreviewRow;
private int groupVibrateRow; private int groupVibrateRow;
private int groupSoundRow; private int groupSoundRow;
private int groupLedRow;
private int inappSectionRow; private int inappSectionRow;
private int inappSoundRow; private int inappSoundRow;
private int inappVibrateRow; private int inappVibrateRow;
@ -74,11 +77,13 @@ public class SettingsNotificationsActivity extends BaseFragment {
messageAlertRow = rowCount++; messageAlertRow = rowCount++;
messagePreviewRow = rowCount++; messagePreviewRow = rowCount++;
messageVibrateRow = rowCount++; messageVibrateRow = rowCount++;
messageLedRow = rowCount++;
messageSoundRow = rowCount++; messageSoundRow = rowCount++;
groupSectionRow = rowCount++; groupSectionRow = rowCount++;
groupAlertRow = rowCount++; groupAlertRow = rowCount++;
groupPreviewRow = rowCount++; groupPreviewRow = rowCount++;
groupVibrateRow = rowCount++; groupVibrateRow = rowCount++;
groupLedRow = rowCount++;
groupSoundRow = rowCount++; groupSoundRow = rowCount++;
inappSectionRow = rowCount++; inappSectionRow = rowCount++;
inappSoundRow = rowCount++; inappSoundRow = rowCount++;
@ -110,12 +115,12 @@ public class SettingsNotificationsActivity extends BaseFragment {
}); });
fragmentView = inflater.inflate(R.layout.settings_layout, container, false); fragmentView = inflater.inflate(R.layout.settings_layout, container, false);
ListAdapter listAdapter = new ListAdapter(getParentActivity()); final ListAdapter listAdapter = new ListAdapter(getParentActivity());
listView = (ListView)fragmentView.findViewById(R.id.listView); listView = (ListView)fragmentView.findViewById(R.id.listView);
listView.setAdapter(listAdapter); listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == messageAlertRow || i == groupAlertRow) { if (i == messageAlertRow || i == groupAlertRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); SharedPreferences.Editor editor = preferences.edit();
@ -217,7 +222,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
listView.invalidateViews(); listView.invalidateViews();
} }
if (getParentActivity() != null) { if (getParentActivity() != null) {
Toast toast = Toast.makeText(getParentActivity(), R.string.ResetNotificationsText, Toast.LENGTH_SHORT); Toast toast = Toast.makeText(getParentActivity(), LocaleController.getString("ResetNotificationsText", R.string.ResetNotificationsText), Toast.LENGTH_SHORT);
toast.show(); toast.show();
} }
} }
@ -270,6 +275,9 @@ public class SettingsNotificationsActivity extends BaseFragment {
listView.invalidateViews(); listView.invalidateViews();
ApplicationLoader.startPushService(); ApplicationLoader.startPushService();
} else { } else {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("NotificationsServiceDisableInfo", R.string.NotificationsServiceDisableInfo)); builder.setMessage(LocaleController.getString("NotificationsServiceDisableInfo", R.string.NotificationsServiceDisableInfo));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -286,6 +294,54 @@ public class SettingsNotificationsActivity extends BaseFragment {
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder); showAlertDialog(builder);
} }
} else if (i == messageLedRow || i == groupLedRow) {
if (getParentActivity() == null) {
return;
}
LayoutInflater li = (LayoutInflater)getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_color_dialog_layout, null, false);
final ColorPickerView colorPickerView = (ColorPickerView)view.findViewById(R.id.color_picker);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (i == messageLedRow) {
colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00));
} else if (i == groupLedRow) {
colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00));
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor));
builder.setView(view);
builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == messageLedRow) {
editor.putInt("MessagesLed", colorPickerView.getColor());
} else if (i == groupLedRow) {
editor.putInt("GroupLed", colorPickerView.getColor());
}
editor.commit();
listView.invalidateViews();
}
});
builder.setNeutralButton(LocaleController.getString("Disabled", R.string.Disabled), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == messageLedRow) {
editor.putInt("MessagesLed", 0);
} else if (i == groupLedRow) {
editor.putInt("GroupLed", 0);
}
editor.commit();
listView.invalidateViews();
}
});
showAlertDialog(builder);
} }
} }
}); });
@ -340,7 +396,7 @@ public class SettingsNotificationsActivity 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) {
@ -498,8 +554,23 @@ public class SettingsNotificationsActivity extends BaseFragment {
textViewDetail.setText(LocaleController.getString("UndoAllCustom", R.string.UndoAllCustom)); textViewDetail.setText(LocaleController.getString("UndoAllCustom", R.string.UndoAllCustom));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} }
} else if (type == 3) {
if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_color_layout, viewGroup, false);
}
TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
View colorView = view.findViewById(R.id.settings_color);
View divider = view.findViewById(R.id.settings_row_divider);
textView.setText(LocaleController.getString("LedColor", R.string.LedColor));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (i == messageLedRow) {
colorView.setBackgroundColor(preferences.getInt("MessagesLed", 0xff00ff00));
} else if (i == groupLedRow) {
colorView.setBackgroundColor(preferences.getInt("GroupLed", 0xff00ff00));
}
divider.setVisibility(View.VISIBLE);
} }
return view; return view;
} }
@ -513,6 +584,8 @@ public class SettingsNotificationsActivity extends BaseFragment {
i == contactJoinedRow || i == contactJoinedRow ||
i == pebbleAlertRow || i == notificationsServiceRow) { i == pebbleAlertRow || i == notificationsServiceRow) {
return 1; return 1;
} else if (i == messageLedRow || i == groupLedRow) {
return 3;
} else { } else {
return 2; return 2;
} }
@ -520,7 +593,7 @@ public class SettingsNotificationsActivity extends BaseFragment {
@Override @Override
public int getViewTypeCount() { public int getViewTypeCount() {
return 3; return 4;
} }
@Override @Override

View File

@ -24,7 +24,6 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button; import android.widget.Button;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ProgressBar; import android.widget.ProgressBar;
@ -42,6 +41,7 @@ import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest; import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.PhotoObject; import org.telegram.objects.PhotoObject;
import org.telegram.ui.Adapters.BaseFragmentAdapter;
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;
import org.telegram.ui.Views.HorizontalListView; import org.telegram.ui.Views.HorizontalListView;
@ -111,7 +111,14 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
boolean done; boolean done;
TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) { if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) {
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, Utilities.dp(320), Utilities.dp(480)); int width = Utilities.displaySize.x;
int height = Utilities.displaySize.y;
if (width > height) {
int temp = width;
width = height;
height = temp;
}
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, width, height);
String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
File f = new File(Utilities.getCacheDir(), fileName); File f = new File(Utilities.getCacheDir(), fileName);
File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg"); File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
@ -158,6 +165,9 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) { if (i == 0) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("Cancel", R.string.Cancel)}; CharSequence[] items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("Cancel", R.string.Cancel)};
@ -251,7 +261,14 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
private void processSelectedBackground() { private void processSelectedBackground() {
TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground); TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
if (selectedBackground != -1 && selectedBackground != 1000001 && wallPaper != null && wallPaper instanceof TLRPC.TL_wallPaper) { if (selectedBackground != -1 && selectedBackground != 1000001 && wallPaper != null && wallPaper instanceof TLRPC.TL_wallPaper) {
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, Utilities.dp(320), Utilities.dp(480)); int width = Utilities.displaySize.x;
int height = Utilities.displaySize.y;
if (width > height) {
int temp = width;
width = height;
height = temp;
}
TLRPC.PhotoSize size = PhotoObject.getClosestPhotoSizeWithSize(wallPaper.sizes, width, height);
String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg"; String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
File f = new File(Utilities.getCacheDir(), fileName); File f = new File(Utilities.getCacheDir(), fileName);
if (!f.exists()) { if (!f.exists()) {
@ -432,7 +449,7 @@ public class SettingsWallpapersActivity extends BaseFragment implements Notifica
fixLayout(); fixLayout();
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {

View File

@ -8,23 +8,17 @@
package org.telegram.ui; package org.telegram.ui;
import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater; 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.ImageButton; import android.widget.ImageButton;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
@ -43,6 +37,7 @@ import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest; import org.telegram.messenger.RPCRequest;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
import org.telegram.objects.MessageObject; import org.telegram.objects.MessageObject;
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;
@ -75,8 +70,6 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
private int settingsTimerRow; private int settingsTimerRow;
private int settingsKeyRow; private int settingsKeyRow;
private int settingsNotificationsRow; private int settingsNotificationsRow;
private int settingsVibrateRow;
private int settingsSoundRow;
private int sharedMediaSectionRow; private int sharedMediaSectionRow;
private int sharedMediaRow; private int sharedMediaRow;
private int rowCount = 0; private int rowCount = 0;
@ -125,8 +118,6 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
settingsKeyRow = -1; settingsKeyRow = -1;
} }
settingsNotificationsRow = rowCount++; settingsNotificationsRow = rowCount++;
settingsVibrateRow = rowCount++;
settingsSoundRow = rowCount++;
sharedMediaSectionRow = rowCount++; sharedMediaSectionRow = rowCount++;
sharedMediaRow = rowCount++; sharedMediaRow = rowCount++;
} }
@ -148,6 +139,12 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
if (id == -1) { if (id == -1) {
finishFragment(); finishFragment();
} else if (id == block_contact) { } else if (id == block_contact) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
TLRPC.User user = MessagesController.getInstance().users.get(user_id); TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user == null) { if (user == null) {
return; return;
@ -163,6 +160,10 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
} }
}, null, true, RPCRequest.RPCRequestClassGeneric); }, null, true, RPCRequest.RPCRequestClassGeneric);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
} else if (id == add_contact) { } else if (id == add_contact) {
TLRPC.User user = MessagesController.getInstance().users.get(user_id); TLRPC.User user = MessagesController.getInstance().users.get(user_id);
Bundle args = new Bundle(); Bundle args = new Bundle();
@ -181,7 +182,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
presentFragment(new ContactAddActivity(args)); presentFragment(new ContactAddActivity(args));
} else if (id == delete_contact) { } else if (id == delete_contact) {
final TLRPC.User user = MessagesController.getInstance().users.get(user_id); final TLRPC.User user = MessagesController.getInstance().users.get(user_id);
if (user == null) { if (user == null || getParentActivity() == null) {
return; return;
} }
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
@ -213,6 +214,9 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
startSecretButton.setOnClickListener(new View.OnClickListener() { startSecretButton.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());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -238,69 +242,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == settingsVibrateRow || i == settingsNotificationsRow) { if (i == sharedMediaRow) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setItems(new CharSequence[] {
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("Enabled", R.string.Enabled),
LocaleController.getString("Disabled", R.string.Disabled)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == settingsVibrateRow) {
if (dialog_id == 0) {
editor.putInt("vibrate_" + user_id, which);
} else {
editor.putInt("vibrate_" + dialog_id, which);
}
} else if (i == settingsNotificationsRow) {
if (dialog_id == 0) {
editor.putInt("notify2_" + user_id, which);
} else {
editor.putInt("notify2_" + dialog_id, which);
}
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
} else if (i == settingsSoundRow) {
try {
Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
Uri currentSound = null;
String defaultPath = null;
Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
String path = preferences.getString("sound_path_" + user_id, defaultPath);
if (path != null && !path.equals("NoSound")) {
if (path.equals(defaultPath)) {
currentSound = defaultUri;
} else {
currentSound = Uri.parse(path);
}
}
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
getParentActivity().startActivityForResult(tmpIntent, 12);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else if (i == sharedMediaRow) {
Bundle args = new Bundle(); Bundle args = new Bundle();
if (dialog_id != 0) { if (dialog_id != 0) {
args.putLong("dialog_id", dialog_id); args.putLong("dialog_id", dialog_id);
@ -313,6 +255,9 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
args.putInt("chat_id", (int)(dialog_id >> 32)); args.putInt("chat_id", (int)(dialog_id >> 32));
presentFragment(new IdenticonActivity(args)); presentFragment(new IdenticonActivity(args));
} else if (i == settingsTimerRow) { } else if (i == settingsTimerRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("MessageLifetime", R.string.MessageLifetime)); builder.setTitle(LocaleController.getString("MessageLifetime", R.string.MessageLifetime));
builder.setItems(new CharSequence[]{ builder.setItems(new CharSequence[]{
@ -354,6 +299,10 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
}); });
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder); showAlertDialog(builder);
} else if (i == settingsNotificationsRow) {
Bundle args = new Bundle();
args.putLong("dialog_id", dialog_id == 0 ? user_id : dialog_id);
presentFragment(new ProfileNotificationsActivity(args));
} }
} }
}); });
@ -371,43 +320,6 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
return fragmentView; return fragmentView;
} }
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
String name = null;
if (ringtone != null) {
Ringtone rng = RingtoneManager.getRingtone(ApplicationLoader.applicationContext, ringtone);
if (rng != null) {
if(ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
name = LocaleController.getString("Default", R.string.Default);
} else {
name = rng.getTitle(getParentActivity());
}
rng.stop();
}
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (requestCode == 12) {
if (name != null && ringtone != null) {
editor.putString("sound_" + user_id, name);
editor.putString("sound_path_" + user_id, ringtone.toString());
} else {
editor.putString("sound_" + user_id, "NoSound");
editor.putString("sound_path_" + user_id, "NoSound");
}
}
editor.commit();
listView.invalidateViews();
}
}
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.updateInterfaces) { if (id == MessagesController.updateInterfaces) {
int mask = (Integer)args[0]; int mask = (Integer)args[0];
@ -556,7 +468,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
} }
} }
private class ListAdapter extends BaseAdapter { private class ListAdapter extends BaseFragmentAdapter {
private Context mContext; private Context mContext;
public ListAdapter(Context context) { public ListAdapter(Context context) {
@ -570,7 +482,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public boolean isEnabled(int i) { public boolean isEnabled(int i) {
return i == phoneRow || i == settingsTimerRow || i == settingsKeyRow || i == settingsNotificationsRow || i == sharedMediaRow || i == settingsSoundRow || i == settingsVibrateRow; return i == phoneRow || i == settingsTimerRow || i == settingsKeyRow || i == settingsNotificationsRow || i == sharedMediaRow;
} }
@Override @Override
@ -657,7 +569,7 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
view.setOnClickListener(new View.OnClickListener() { view.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if (user.phone == null || user.phone.length() == 0) { if (user.phone == null || user.phone.length() == 0 || getParentActivity() == null) {
return; return;
} }
selectedPhone = user.phone; selectedPhone = user.phone;
@ -756,44 +668,6 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
} else { } else {
detailTextView.setText(String.format("%d", encryptedChat.ttl)); detailTextView.setText(String.format("%d", encryptedChat.ttl));
} }
} else if (i == settingsVibrateRow) {
textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
String key;
if (dialog_id == 0) {
key = "vibrate_" + user_id;
} else {
key = "vibrate_" + dialog_id;
}
int value = preferences.getInt(key, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} else if (i == settingsNotificationsRow) {
textView.setText(LocaleController.getString("Notifications", R.string.Notifications));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
String key;
if (dialog_id == 0) {
key = "notify2_" + user_id;
} else {
key = "notify2_" + dialog_id;
}
int value = preferences.getInt(key, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} }
} else if (type == 4) { } else if (type == 4) {
if (view == null) { if (view == null) {
@ -810,25 +684,15 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
} else if (type == 5) { } else if (type == 5) {
if (view == null) { if (view == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_detail_layout, viewGroup, false); view = li.inflate(R.layout.settings_row_button_layout, viewGroup, false);
} }
TextView textView = (TextView)view.findViewById(R.id.settings_row_text); TextView textView = (TextView)view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView)view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider); View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsSoundRow) { if (i == settingsNotificationsRow) {
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); textView.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds));
String name = preferences.getString("sound_" + user_id, LocaleController.getString("Default", R.string.Default));
if (name.equals("NoSound")) {
detailTextView.setText(LocaleController.getString("NoSound", R.string.NoSound));
} else {
detailTextView.setText(name);
}
textView.setText(LocaleController.getString("Sound", R.string.Sound));
divider.setVisibility(View.INVISIBLE); divider.setVisibility(View.INVISIBLE);
} }
} }
return view; return view;
} }
@ -840,11 +704,11 @@ public class UserProfileActivity extends BaseFragment implements NotificationCen
return 1; return 1;
} else if (i == phoneRow) { } else if (i == phoneRow) {
return 2; return 2;
} else if (i == sharedMediaRow || i == settingsTimerRow || i == settingsNotificationsRow || i == settingsVibrateRow) { } else if (i == sharedMediaRow || i == settingsTimerRow) {
return 3; return 3;
} else if (i == settingsKeyRow) { } else if (i == settingsKeyRow) {
return 4; return 4;
} else if (i == settingsSoundRow) { } else if (i == settingsNotificationsRow) {
return 5; return 5;
} }
return 0; return 0;

View File

@ -170,7 +170,7 @@ public class ActionBar extends FrameLayout {
@Override @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(40), MeasureSpec.EXACTLY)); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(40), MeasureSpec.EXACTLY));
} else { } else {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(48), MeasureSpec.EXACTLY)); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Utilities.dp(48), MeasureSpec.EXACTLY));

View File

@ -40,9 +40,21 @@ import java.util.ArrayList;
public class ActionBarActivity extends Activity { public class ActionBarActivity extends Activity {
private class FrameLayoutAnimationListener extends FrameLayout {
public FrameLayoutAnimationListener(Context context) {
super(context);
}
@Override
protected void onAnimationEnd() {
super.onAnimationEnd();
ActionBarActivity.this.onAnimationEnd();
}
}
protected ActionBar actionBar; protected ActionBar actionBar;
private FrameLayout containerView; private FrameLayoutAnimationListener containerView;
private FrameLayout containerViewBack; private FrameLayoutAnimationListener containerViewBack;
protected FrameLayout contentView; protected FrameLayout contentView;
private View shadowView; private View shadowView;
@ -52,6 +64,7 @@ public class ActionBarActivity extends Activity {
private boolean maybeStartTracking = false; private boolean maybeStartTracking = false;
protected boolean startedTracking = false; protected boolean startedTracking = false;
private int startedTrackingX; private int startedTrackingX;
private int startedTrackingY;
protected boolean animationInProgress = false; protected boolean animationInProgress = false;
private VelocityTracker velocityTracker = null; private VelocityTracker velocityTracker = null;
private boolean beginTrackingSent = false; private boolean beginTrackingSent = false;
@ -59,7 +72,8 @@ public class ActionBarActivity extends Activity {
private long transitionAnimationStartTime; private long transitionAnimationStartTime;
private boolean inActionMode = false; private boolean inActionMode = false;
private int startedTrackingPointerId; private int startedTrackingPointerId;
private Animation.AnimationListener listener; private Runnable onCloseAnimationEndRunnable = null;
private Runnable onOpenAnimationEndRunnable = null;
private class FrameLayoutTouch extends FrameLayout { private class FrameLayoutTouch extends FrameLayout {
public FrameLayoutTouch(Context context) { public FrameLayoutTouch(Context context) {
@ -115,10 +129,10 @@ public class ActionBarActivity extends Activity {
contentView = new FrameLayoutTouch(this); contentView = new FrameLayoutTouch(this);
setContentView(contentView, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); setContentView(contentView, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
containerViewBack = new FrameLayout(this); containerViewBack = new FrameLayoutAnimationListener(this);
contentView.addView(containerViewBack); contentView.addView(containerViewBack);
containerView = new FrameLayout(this); containerView = new FrameLayoutAnimationListener(this);
contentView.addView(containerView); contentView.addView(containerView);
shadowView = new FrameLayout(this); shadowView = new FrameLayout(this);
@ -157,17 +171,20 @@ public class ActionBarActivity extends Activity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
fixLayout(); fixLayout();
if (transitionAnimationInProgress && listener != null) { if (transitionAnimationInProgress) {
openAnimation.cancel(); if (onCloseAnimationEndRunnable != null) {
closeAnimation.cancel(); closeAnimation.cancel();
listener.onAnimationEnd(null); onCloseAnimationEnd(false);
} else if (onOpenAnimationEndRunnable != null) {
openAnimation.cancel();
onOpenAnimationEnd(false);
}
} }
if (!fragmentsStack.isEmpty()) { if (!fragmentsStack.isEmpty()) {
BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 1); BaseFragment lastFragment = fragmentsStack.get(fragmentsStack.size() - 1);
lastFragment.onResume(); lastFragment.onResume();
actionBar.setCurrentActionBarLayer(lastFragment.actionBarLayer); actionBar.setCurrentActionBarLayer(lastFragment.actionBarLayer);
onShowFragment();
} }
} }
@ -193,7 +210,7 @@ public class ActionBarActivity extends Activity {
lastFragment.setParentActivity(null); lastFragment.setParentActivity(null);
fragmentsStack.remove(fragmentsStack.size() - 1); fragmentsStack.remove(fragmentsStack.size() - 1);
FrameLayout temp = containerView; FrameLayoutAnimationListener temp = containerView;
containerView = containerViewBack; containerView = containerViewBack;
containerViewBack = temp; containerViewBack = temp;
ViewGroup parent = (ViewGroup)containerView.getParent(); ViewGroup parent = (ViewGroup)containerView.getParent();
@ -249,9 +266,14 @@ public class ActionBarActivity extends Activity {
public boolean onTouchEvent(MotionEvent ev) { public boolean onTouchEvent(MotionEvent ev) {
if(android.os.Build.VERSION.SDK_INT >= 11 && !checkTransitionAnimation() && !inActionMode && fragmentsStack.size() > 1 && !animationInProgress) { if(android.os.Build.VERSION.SDK_INT >= 11 && !checkTransitionAnimation() && !inActionMode && fragmentsStack.size() > 1 && !animationInProgress) {
if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN && !startedTracking && !maybeStartTracking) { if (ev != null && ev.getAction() == MotionEvent.ACTION_DOWN && !startedTracking && !maybeStartTracking) {
BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
if (!currentFragment.swipeBackEnabled) {
return false;
}
startedTrackingPointerId = ev.getPointerId(0); startedTrackingPointerId = ev.getPointerId(0);
maybeStartTracking = true; maybeStartTracking = true;
startedTrackingX = (int) ev.getX(); startedTrackingX = (int) ev.getX();
startedTrackingY = (int) ev.getY();
if (velocityTracker != null) { if (velocityTracker != null) {
velocityTracker.clear(); velocityTracker.clear();
} }
@ -260,8 +282,9 @@ public class ActionBarActivity extends Activity {
velocityTracker = VelocityTracker.obtain(); velocityTracker = VelocityTracker.obtain();
} }
int dx = Math.max(0, (int) (ev.getX() - startedTrackingX)); int dx = Math.max(0, (int) (ev.getX() - startedTrackingX));
int dy = Math.abs((int)ev.getY() - startedTrackingY);
velocityTracker.addMovement(ev); velocityTracker.addMovement(ev);
if (maybeStartTracking && !startedTracking && dx >= Utilities.dp(10)) { if (maybeStartTracking && !startedTracking && dx >= Utilities.dp(10) && Math.abs(dx) / 3 > dy) {
prepareForMoving(ev); prepareForMoving(ev);
} else if (startedTracking) { } else if (startedTracking) {
if (!beginTrackingSent) { if (!beginTrackingSent) {
@ -370,7 +393,7 @@ public class ActionBarActivity extends Activity {
onFinish(); onFinish();
finish(); finish();
} else if (!fragmentsStack.isEmpty()) { } else if (!fragmentsStack.isEmpty()) {
closeLastFragment(); closeLastFragment(true);
} }
} }
} }
@ -386,6 +409,7 @@ public class ActionBarActivity extends Activity {
public boolean checkTransitionAnimation() { public boolean checkTransitionAnimation() {
if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 400) { if (transitionAnimationInProgress && transitionAnimationStartTime < System.currentTimeMillis() - 400) {
transitionAnimationInProgress = false; transitionAnimationInProgress = false;
onAnimationEnd();
} }
return transitionAnimationInProgress; return transitionAnimationInProgress;
} }
@ -414,7 +438,7 @@ public class ActionBarActivity extends Activity {
int height = 0; int height = 0;
if (actionBar.getVisibility() == View.VISIBLE) { if (actionBar.getVisibility() == View.VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(this) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
height = Utilities.dp(40); height = Utilities.dp(40);
} else { } else {
height = Utilities.dp(48); height = Utilities.dp(48);
@ -460,6 +484,7 @@ public class ActionBarActivity extends Activity {
} }
} }
} }
containerViewBack.setVisibility(View.GONE);
} }
public boolean presentFragment(BaseFragment fragment) { public boolean presentFragment(BaseFragment fragment) {
@ -480,13 +505,10 @@ public class ActionBarActivity extends Activity {
boolean needAnimation = openAnimation != null && !forceWithoutAnimation && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true); boolean needAnimation = openAnimation != null && !forceWithoutAnimation && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
final BaseFragment currentFragment = !fragmentsStack.isEmpty() ? fragmentsStack.get(fragmentsStack.size() - 1) : null; final BaseFragment currentFragment = !fragmentsStack.isEmpty() ? fragmentsStack.get(fragmentsStack.size() - 1) : null;
if (!needAnimation) {
presentFragmentInternalRemoveOld(removeLast, currentFragment);
}
fragment.setParentActivity(this); fragment.setParentActivity(this);
View fragmentView = fragment.createView(getLayoutInflater(), null); View fragmentView = fragment.createView(getLayoutInflater(), null);
containerView.addView(fragmentView); containerViewBack.addView(fragmentView);
ViewGroup.LayoutParams layoutParams = fragmentView.getLayoutParams(); ViewGroup.LayoutParams layoutParams = fragmentView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
@ -497,39 +519,31 @@ public class ActionBarActivity extends Activity {
if (fragmentView.getBackground() == null) { if (fragmentView.getBackground() == null) {
fragmentView.setBackgroundColor(0xffffffff); fragmentView.setBackgroundColor(0xffffffff);
} }
onShowFragment();
FrameLayoutAnimationListener temp = containerView;
containerView = containerViewBack;
containerViewBack = temp;
containerView.setVisibility(View.VISIBLE);
ViewGroup parent = (ViewGroup)containerView.getParent();
parent.removeView(containerView);
parent.addView(containerView, 1);
if (!needAnimation) {
presentFragmentInternalRemoveOld(removeLast, currentFragment);
}
if (needAnimation) { if (needAnimation) {
transitionAnimationStartTime = System.currentTimeMillis(); transitionAnimationStartTime = System.currentTimeMillis();
transitionAnimationInProgress = true; transitionAnimationInProgress = true;
openAnimation.reset(); onOpenAnimationEndRunnable = new Runnable() {
openAnimation.setAnimationListener(listener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (transitionAnimationInProgress) {
transitionAnimationInProgress = false;
transitionAnimationStartTime = 0;
fragment.onOpenAnimationEnd();
new Handler().post(new Runnable() {
@Override @Override
public void run() { public void run() {
presentFragmentInternalRemoveOld(removeLast, currentFragment); presentFragmentInternalRemoveOld(removeLast, currentFragment);
fragment.onOpenAnimationEnd();
} }
}); };
listener = null; openAnimation.reset();
} containerView.startAnimation(openAnimation);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
fragmentView.startAnimation(openAnimation);
} else { } else {
fragment.onOpenAnimationEnd(); fragment.onOpenAnimationEnd();
} }
@ -550,25 +564,31 @@ public class ActionBarActivity extends Activity {
fragment.onFragmentDestroy(); fragment.onFragmentDestroy();
fragment.setParentActivity(null); fragment.setParentActivity(null);
fragmentsStack.remove(fragment); fragmentsStack.remove(fragment);
containerViewBack.setVisibility(View.GONE);
ViewGroup parent = (ViewGroup)containerView.getParent();
parent.removeView(containerViewBack);
parent.addView(containerViewBack, 0);
} }
public void closeLastFragment() { public void closeLastFragment(boolean animated) {
if (fragmentsStack.size() <= 1 || checkTransitionAnimation()) { if (fragmentsStack.size() <= 1 || checkTransitionAnimation()) {
return; return;
} }
if (getCurrentFocus() != null) { if (getCurrentFocus() != null) {
Utilities.hideKeyboard(getCurrentFocus()); Utilities.hideKeyboard(getCurrentFocus());
} }
boolean needAnimation = openAnimation != null && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true); boolean needAnimation = animated && closeAnimation != null && getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).getBoolean("view_animations", true);
final BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1); final BaseFragment currentFragment = fragmentsStack.get(fragmentsStack.size() - 1);
BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 2); BaseFragment previousFragment = fragmentsStack.get(fragmentsStack.size() - 2);
if (!needAnimation) {
closeLastFragmentInternalRemoveOld(currentFragment); FrameLayoutAnimationListener temp = containerView;
} containerView = containerViewBack;
containerViewBack = temp;
containerView.setVisibility(View.VISIBLE);
previousFragment.setParentActivity(this); previousFragment.setParentActivity(this);
View fragmentView = previousFragment.createView(getLayoutInflater(), null); View fragmentView = previousFragment.createView(getLayoutInflater(), null);
containerView.addView(fragmentView, 0); containerView.addView(fragmentView);
ViewGroup.LayoutParams layoutParams = fragmentView.getLayoutParams(); ViewGroup.LayoutParams layoutParams = fragmentView.getLayoutParams();
layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT; layoutParams.height = FrameLayout.LayoutParams.MATCH_PARENT;
@ -578,38 +598,22 @@ public class ActionBarActivity extends Activity {
if (fragmentView.getBackground() == null) { if (fragmentView.getBackground() == null) {
fragmentView.setBackgroundColor(0xffffffff); fragmentView.setBackgroundColor(0xffffffff);
} }
onShowFragment();
if (!needAnimation) {
closeLastFragmentInternalRemoveOld(currentFragment);
}
if (needAnimation) { if (needAnimation) {
transitionAnimationStartTime = System.currentTimeMillis(); transitionAnimationStartTime = System.currentTimeMillis();
transitionAnimationInProgress = true; transitionAnimationInProgress = true;
closeAnimation.reset(); closeAnimation.reset();
closeAnimation.setFillAfter(true); onCloseAnimationEndRunnable = new Runnable() {
closeAnimation.setAnimationListener(listener = new Animation.AnimationListener() {
@Override @Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (transitionAnimationInProgress) {
transitionAnimationInProgress = false;
transitionAnimationStartTime = 0;
new Handler().post(new Runnable() {
public void run() { public void run() {
closeLastFragmentInternalRemoveOld(currentFragment); closeLastFragmentInternalRemoveOld(currentFragment);
} }
}); };
listener = null; containerViewBack.startAnimation(closeAnimation);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
currentFragment.fragmentView.startAnimation(closeAnimation);
} }
} }
@ -627,7 +631,6 @@ public class ActionBarActivity extends Activity {
if (fragmentView.getBackground() == null) { if (fragmentView.getBackground() == null) {
fragmentView.setBackgroundColor(0xffffffff); fragmentView.setBackgroundColor(0xffffffff);
} }
onShowFragment();
} }
public void removeFragmentFromStack(BaseFragment fragment) { public void removeFragmentFromStack(BaseFragment fragment) {
@ -647,10 +650,6 @@ public class ActionBarActivity extends Activity {
} }
protected void onShowFragment() {
}
public void showActionBar() { public void showActionBar() {
actionBar.setVisibility(View.VISIBLE); actionBar.setVisibility(View.VISIBLE);
needLayout(); needLayout();
@ -664,7 +663,6 @@ public class ActionBarActivity extends Activity {
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && !checkTransitionAnimation() && !startedTracking) { if (keyCode == KeyEvent.KEYCODE_MENU && !checkTransitionAnimation() && !startedTracking) {
actionBar.onMenuButtonPressed(); actionBar.onMenuButtonPressed();
return true;
} }
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
} }
@ -691,13 +689,73 @@ public class ActionBarActivity extends Activity {
return false; return false;
} }
@Override private void onCloseAnimationEnd(boolean post) {
public void startActivityForResult(Intent intent, int requestCode) { if (transitionAnimationInProgress && onCloseAnimationEndRunnable != null) {
if (transitionAnimationInProgress && listener != null) { transitionAnimationInProgress = false;
openAnimation.cancel(); transitionAnimationStartTime = 0;
closeAnimation.cancel(); if (post) {
listener.onAnimationEnd(null); new Handler().post(new Runnable() {
public void run() {
onCloseAnimationEndRunnable.run();
onCloseAnimationEndRunnable = null;
} }
});
} else {
onCloseAnimationEndRunnable.run();
onCloseAnimationEndRunnable = null;
}
}
}
private void onOpenAnimationEnd(boolean post) {
if (transitionAnimationInProgress && onOpenAnimationEndRunnable != null) {
transitionAnimationInProgress = false;
transitionAnimationStartTime = 0;
if (post) {
new Handler().post(new Runnable() {
public void run() {
onOpenAnimationEndRunnable.run();
onOpenAnimationEndRunnable = null;
}
});
} else {
onOpenAnimationEndRunnable.run();
onOpenAnimationEndRunnable = null;
}
}
}
private void onAnimationEnd() {
onCloseAnimationEnd(false);
onOpenAnimationEnd(false);
}
@Override
public void startActivityForResult(final Intent intent, final int requestCode) {
if (transitionAnimationInProgress) {
if (onCloseAnimationEndRunnable != null) {
closeAnimation.cancel();
onCloseAnimationEnd(false);
} else if (onOpenAnimationEndRunnable != null) {
openAnimation.cancel();
onOpenAnimationEnd(false);
}
containerView.invalidate();
if (intent != null) {
try {
ActionBarActivity.super.startActivityForResult(intent, requestCode);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else {
if (intent != null) {
try {
super.startActivityForResult(intent, requestCode); super.startActivityForResult(intent, requestCode);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
} }
} }

View File

@ -107,7 +107,7 @@ public class ActionBarLayer extends FrameLayout {
private void positionLogoImage(int height) { private void positionLogoImage(int height) {
if (logoImageView != null) { if (logoImageView != null) {
LayoutParams layoutParams = (LayoutParams) logoImageView.getLayoutParams(); LayoutParams layoutParams = (LayoutParams) logoImageView.getLayoutParams();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
layoutParams.width = (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f); layoutParams.width = (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f);
layoutParams.height = (int)(logoImageView.getDrawable().getIntrinsicHeight() / 1.3f); layoutParams.height = (int)(logoImageView.getDrawable().getIntrinsicHeight() / 1.3f);
layoutParams.setMargins(Utilities.dp(12), (height - layoutParams.height) / 2, 0, 0); layoutParams.setMargins(Utilities.dp(12), (height - layoutParams.height) / 2, 0, 0);
@ -123,7 +123,7 @@ public class ActionBarLayer extends FrameLayout {
private void positionTitle(int width, int height) { private void positionTitle(int width, int height) {
int offset = Utilities.dp(2); int offset = Utilities.dp(2);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
offset = Utilities.dp(1); offset = Utilities.dp(1);
} }
int maxTextWidth = 0; int maxTextWidth = 0;
@ -131,7 +131,7 @@ public class ActionBarLayer extends FrameLayout {
LayoutParams layoutParams = null; LayoutParams layoutParams = null;
if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) { if (titleTextView != null && titleTextView.getVisibility() == VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
titleTextView.setTextSize(16); titleTextView.setTextSize(16);
} else { } else {
titleTextView.setTextSize(18); titleTextView.setTextSize(18);
@ -146,7 +146,7 @@ public class ActionBarLayer extends FrameLayout {
maxTextWidth = titleTextView.getMeasuredWidth(); maxTextWidth = titleTextView.getMeasuredWidth();
} }
if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) { if (subTitleTextView != null && subTitleTextView.getVisibility() == VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
subTitleTextView.setTextSize(12); subTitleTextView.setTextSize(12);
} else { } else {
subTitleTextView.setTextSize(14); subTitleTextView.setTextSize(14);
@ -165,7 +165,7 @@ public class ActionBarLayer extends FrameLayout {
if (logoImageView == null || logoImageView.getVisibility() == GONE) { if (logoImageView == null || logoImageView.getVisibility() == GONE) {
x = Utilities.dp(16); x = Utilities.dp(16);
} else { } else {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (!Utilities.isTablet(getContext()) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
x = Utilities.dp(22) + (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f); x = Utilities.dp(22) + (int)(logoImageView.getDrawable().getIntrinsicWidth() / 1.3f);
} else { } else {
x = Utilities.dp(22) + logoImageView.getDrawable().getIntrinsicWidth(); x = Utilities.dp(22) + logoImageView.getDrawable().getIntrinsicWidth();
@ -243,6 +243,7 @@ public class ActionBarLayer extends FrameLayout {
if (value != null && subTitleTextView == null) { if (value != null && subTitleTextView == null) {
subTitleTextView = new TextView(getContext()); subTitleTextView = new TextView(getContext());
backButtonFrameLayout.addView(subTitleTextView); backButtonFrameLayout.addView(subTitleTextView);
subTitleTextView.setGravity(Gravity.LEFT);
subTitleTextView.setTextColor(0xffd7e8f7); subTitleTextView.setTextColor(0xffd7e8f7);
subTitleTextView.setSingleLine(true); subTitleTextView.setSingleLine(true);
subTitleTextView.setLines(1); subTitleTextView.setLines(1);
@ -260,6 +261,7 @@ public class ActionBarLayer extends FrameLayout {
if (resourceId != 0 && subTitleTextView == null) { if (resourceId != 0 && subTitleTextView == null) {
subTitleTextView = new TextView(getContext()); subTitleTextView = new TextView(getContext());
backButtonFrameLayout.addView(subTitleTextView); backButtonFrameLayout.addView(subTitleTextView);
subTitleTextView.setGravity(Gravity.LEFT);
subTitleTextView.setTextColor(0xffd7e8f7); subTitleTextView.setTextColor(0xffd7e8f7);
subTitleTextView.setSingleLine(true); subTitleTextView.setSingleLine(true);
subTitleTextView.setLines(1); subTitleTextView.setLines(1);
@ -276,7 +278,10 @@ public class ActionBarLayer extends FrameLayout {
public void setTitle(CharSequence value) { public void setTitle(CharSequence value) {
if (value != null && titleTextView == null) { if (value != null && titleTextView == null) {
titleTextView = new TextView(getContext()); titleTextView = new TextView(getContext());
titleTextView.setGravity(Gravity.LEFT);
titleTextView.setSingleLine(true); titleTextView.setSingleLine(true);
titleTextView.setLines(1);
titleTextView.setMaxLines(1);
titleTextView.setEllipsize(TextUtils.TruncateAt.END); titleTextView.setEllipsize(TextUtils.TruncateAt.END);
backButtonFrameLayout.addView(titleTextView); backButtonFrameLayout.addView(titleTextView);
titleTextView.setTextColor(0xffffffff); titleTextView.setTextColor(0xffffffff);
@ -291,6 +296,7 @@ public class ActionBarLayer extends FrameLayout {
public void setTitleIcon(int resourceId, int padding) { public void setTitleIcon(int resourceId, int padding) {
if (resourceId != 0 && titleTextView == null) { if (resourceId != 0 && titleTextView == null) {
titleTextView = new TextView(getContext()); titleTextView = new TextView(getContext());
titleTextView.setGravity(Gravity.LEFT);
backButtonFrameLayout.addView(titleTextView); backButtonFrameLayout.addView(titleTextView);
titleTextView.setTextColor(0xffffffff); titleTextView.setTextColor(0xffffffff);
titleTextView.setSingleLine(true); titleTextView.setSingleLine(true);
@ -377,7 +383,7 @@ public class ActionBarLayer extends FrameLayout {
} }
actionMode.setVisibility(GONE); actionMode.setVisibility(GONE);
if (backButtonFrameLayout != null) { if (backButtonFrameLayout != null) {
backButtonFrameLayout.setVisibility(VISIBLE); backButtonFrameLayout.setVisibility(isSearchFieldVisible || actionOverlay == null || actionOverlay.getVisibility() == GONE ? VISIBLE : INVISIBLE);
} }
if (menu != null) { if (menu != null) {
menu.setVisibility(VISIBLE); menu.setVisibility(VISIBLE);
@ -455,6 +461,7 @@ public class ActionBarLayer extends FrameLayout {
LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
actionOverlay = li.inflate(resourceId, null); actionOverlay = li.inflate(resourceId, null);
addView(actionOverlay); addView(actionOverlay);
actionOverlay.setVisibility(GONE);
actionOverlay.setOnClickListener(new OnClickListener() { actionOverlay.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@ -470,10 +477,10 @@ public class ActionBarLayer extends FrameLayout {
return; return;
} }
isBackOverlayVisible = visible; isBackOverlayVisible = visible;
positionBackOverlay(getMeasuredWidth(), getMeasuredHeight());
if (visible) { if (visible) {
((ActionBarActivity)getContext()).onOverlayShow(actionOverlay, parentFragment); ((ActionBarActivity)getContext()).onOverlayShow(actionOverlay, parentFragment);
} }
positionBackOverlay(getMeasuredWidth(), getMeasuredHeight());
} }
private void positionBackOverlay(int widthMeasureSpec, int heightMeasureSpec) { private void positionBackOverlay(int widthMeasureSpec, int heightMeasureSpec) {
@ -484,9 +491,12 @@ public class ActionBarLayer extends FrameLayout {
actionOverlay.setVisibility(!isSearchFieldVisible && isBackOverlayVisible ? VISIBLE : GONE); actionOverlay.setVisibility(!isSearchFieldVisible && isBackOverlayVisible ? VISIBLE : GONE);
if (actionOverlay.getVisibility() == VISIBLE) { if (actionOverlay.getVisibility() == VISIBLE) {
ViewGroup.LayoutParams layoutParams = actionOverlay.getLayoutParams(); ViewGroup.LayoutParams layoutParams = actionOverlay.getLayoutParams();
layoutParams.width = widthMeasureSpec - (menu != null ? menu.getMeasuredWidth() : 0); layoutParams.width = LayoutParams.WRAP_CONTENT;
layoutParams.height = LayoutParams.MATCH_PARENT; layoutParams.height = LayoutParams.MATCH_PARENT;
actionOverlay.setLayoutParams(layoutParams); actionOverlay.setLayoutParams(layoutParams);
actionOverlay.measure(widthMeasureSpec, heightMeasureSpec);
layoutParams.width = Math.min(actionOverlay.getMeasuredWidth() + Utilities.dp(4), widthMeasureSpec - (menu != null ? menu.getMeasuredWidth() : 0));
actionOverlay.setLayoutParams(layoutParams);
} }
} }

View File

@ -9,13 +9,14 @@
package org.telegram.ui.Views.ActionBar; package org.telegram.ui.Views.ActionBar;
import android.content.Context; import android.content.Context;
import android.graphics.drawable.BitmapDrawable; import android.graphics.Rect;
import android.os.Build; import android.os.Build;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.Gravity; import android.view.Gravity;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.WindowManager; import android.view.WindowManager;
import android.view.inputmethod.EditorInfo; import android.view.inputmethod.EditorInfo;
@ -38,13 +39,16 @@ public class ActionBarMenuItem extends ImageView {
public abstract void onTextChanged(EditText editText); public abstract void onTextChanged(EditText editText);
} }
private LinearLayout popupLayout; private ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout;
private ActionBarMenu parentMenu; private ActionBarMenu parentMenu;
private ActionBarPopupWindow popupWindow; private ActionBarPopupWindow popupWindow;
private ActionBar parentActionBar; private ActionBar parentActionBar;
private EditText searchField; private EditText searchField;
private boolean isSearchField = false; private boolean isSearchField = false;
private ActionBarMenuItemSearchListener listener; private ActionBarMenuItemSearchListener listener;
private Rect rect = null;
private int[] location = null;
private View selectedMenuView = null;
public ActionBarMenuItem(Context context, ActionBarMenu menu, ActionBar actionBar, int background) { public ActionBarMenuItem(Context context, ActionBarMenu menu, ActionBar actionBar, int background) {
super(context); super(context);
@ -65,11 +69,82 @@ public class ActionBarMenuItem extends ImageView {
super(context, attrs, defStyleAttr); super(context, attrs, defStyleAttr);
} }
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
if (hasSubMenu() && (popupWindow == null || popupWindow != null && !popupWindow.isShowing())) {
if (event.getY() > getHeight()) {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
toggleSubMenu();
return true;
}
} else if (popupWindow != null && popupWindow.isShowing()) {
getLocationOnScreen(location);
float x = event.getX() + location[0];
float y = event.getY() + location[1];
popupLayout.getLocationOnScreen(location);
x -= location[0];
y -= location[1];
selectedMenuView = null;
for (int a = 0; a < popupLayout.getChildCount(); a++) {
View child = popupLayout.getChildAt(a);
child.getHitRect(rect);
if ((Integer)child.getTag() < 100) {
if (!rect.contains((int)x, (int)y)) {
child.setSelected(false);
} else {
child.setSelected(true);
selectedMenuView = child;
}
}
}
}
} else if (popupWindow != null && popupWindow.isShowing() && event.getActionMasked() == MotionEvent.ACTION_UP) {
if (selectedMenuView != null) {
selectedMenuView.setSelected(false);
parentMenu.onItemClick((Integer) selectedMenuView.getTag());
}
popupWindow.dismiss();
} else {
if (selectedMenuView != null) {
selectedMenuView.setSelected(false);
selectedMenuView = null;
}
}
return super.onTouchEvent(event);
}
public void addSubItem(int id, String text, int icon) { public void addSubItem(int id, String text, int icon) {
if (popupLayout == null) { if (popupLayout == null) {
popupLayout = new LinearLayout(getContext()); rect = new Rect();
location = new int[2];
popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getContext());
popupLayout.setOrientation(LinearLayout.VERTICAL); popupLayout.setOrientation(LinearLayout.VERTICAL);
popupLayout.setBackgroundResource(R.drawable.popup_fixed); popupLayout.setBackgroundResource(R.drawable.popup_fixed);
popupLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
if (popupWindow != null && popupWindow.isShowing()) {
v.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY())) {
popupWindow.dismiss();
}
}
}
return false;
}
});
popupLayout.setDispatchKeyEventListener(new ActionBarPopupWindow.OnDispatchKeyEventListener() {
@Override
public void onDispatchKeyEvent(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
});
} }
if (popupLayout.getChildCount() != 0) { if (popupLayout.getChildCount() != 0) {
View delimeter = new View(getContext()); View delimeter = new View(getContext());
@ -121,14 +196,14 @@ public class ActionBarMenuItem extends ImageView {
} }
if (popupWindow == null) { if (popupWindow == null) {
popupWindow = new ActionBarPopupWindow(popupLayout, FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); popupWindow = new ActionBarPopupWindow(popupLayout, FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true); //popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true); popupWindow.setOutsideTouchable(true);
popupWindow.setClippingEnabled(true); popupWindow.setClippingEnabled(true);
popupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED); popupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED); popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
popupLayout.measure(MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST)); popupLayout.measure(MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(Utilities.dp(1000), MeasureSpec.AT_MOST));
} }
popupWindow.setFocusable(true);
if (popupLayout.getMeasuredWidth() == 0) { if (popupLayout.getMeasuredWidth() == 0) {
popupWindow.showAsDropDown(this, parentActionBar.getMeasuredWidth() - popupLayout.getMeasuredWidth() - getLeft() - parentMenu.getLeft(), 0); popupWindow.showAsDropDown(this, parentActionBar.getMeasuredWidth() - popupLayout.getMeasuredWidth() - getLeft() - parentMenu.getLeft(), 0);
popupWindow.update(this, parentActionBar.getMeasuredWidth() - popupLayout.getMeasuredWidth() - getLeft() - parentMenu.getLeft(), 0, -1, -1); popupWindow.update(this, parentActionBar.getMeasuredWidth() - popupLayout.getMeasuredWidth() - getLeft() - parentMenu.getLeft(), 0, -1, -1);

View File

@ -12,8 +12,10 @@ package org.telegram.ui.Views.ActionBar;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View; import android.view.View;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.PopupWindow; import android.widget.PopupWindow;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -41,6 +43,39 @@ public class ActionBarPopupWindow extends PopupWindow {
private ViewTreeObserver.OnScrollChangedListener mSuperScrollListener; private ViewTreeObserver.OnScrollChangedListener mSuperScrollListener;
private ViewTreeObserver mViewTreeObserver; private ViewTreeObserver mViewTreeObserver;
public static interface OnDispatchKeyEventListener {
public void onDispatchKeyEvent(KeyEvent keyEvent);
}
public static class ActionBarPopupWindowLayout extends LinearLayout {
private OnDispatchKeyEventListener mOnDispatchKeyEventListener;
public ActionBarPopupWindowLayout(Context context) {
super(context);
}
public ActionBarPopupWindowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ActionBarPopupWindowLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setDispatchKeyEventListener(OnDispatchKeyEventListener listener) {
mOnDispatchKeyEventListener = listener;
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (mOnDispatchKeyEventListener != null) {
mOnDispatchKeyEventListener.onDispatchKeyEvent(event);
}
return super.dispatchKeyEvent(event);
}
}
public ActionBarPopupWindow() { public ActionBarPopupWindow() {
super(); super();
init(); init();
@ -98,7 +133,6 @@ public class ActionBarPopupWindow extends PopupWindow {
} }
private void unregisterListener() { private void unregisterListener() {
// Don't do anything if we haven't managed to patch the super listener
if (mSuperScrollListener != null && mViewTreeObserver != null) { if (mSuperScrollListener != null && mViewTreeObserver != null) {
if (mViewTreeObserver.isAlive()) { if (mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener); mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener);
@ -108,13 +142,8 @@ public class ActionBarPopupWindow extends PopupWindow {
} }
private void registerListener(View anchor) { private void registerListener(View anchor) {
// Don't do anything if we haven't managed to patch the super listener.
// And don't bother attaching the listener if the anchor view isn't
// attached. This means we'll only have to deal with the real VTO owned
// by the ViewRoot.
if (mSuperScrollListener != null) { if (mSuperScrollListener != null) {
ViewTreeObserver vto = (anchor.getWindowToken() != null) ? anchor.getViewTreeObserver() ViewTreeObserver vto = (anchor.getWindowToken() != null) ? anchor.getViewTreeObserver() : null;
: null;
if (vto != mViewTreeObserver) { if (vto != mViewTreeObserver) {
if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) { if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener); mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener);
@ -152,6 +181,7 @@ public class ActionBarPopupWindow extends PopupWindow {
@Override @Override
public void dismiss() { public void dismiss() {
setFocusable(false);
super.dismiss(); super.dismiss();
unregisterListener(); unregisterListener();
} }

View File

@ -28,6 +28,7 @@ public class BaseFragment {
protected int classGuid = 0; protected int classGuid = 0;
protected Bundle arguments; protected Bundle arguments;
private AlertDialog visibleDialog = null; private AlertDialog visibleDialog = null;
protected boolean swipeBackEnabled = true;
public BaseFragment() { public BaseFragment() {
classGuid = ConnectionsManager.getInstance().generateClassGuid(); classGuid = ConnectionsManager.getInstance().generateClassGuid();
@ -69,10 +70,14 @@ public class BaseFragment {
} }
public void finishFragment() { public void finishFragment() {
finishFragment(true);
}
public void finishFragment(boolean animated) {
if (isFinished || parentActivity == null) { if (isFinished || parentActivity == null) {
return; return;
} }
parentActivity.closeLastFragment(); parentActivity.closeLastFragment(animated);
} }
public void removeSelfFromStack() { public void removeSelfFromStack() {
@ -196,10 +201,14 @@ public class BaseFragment {
if (parentActivity == null || parentActivity.checkTransitionAnimation() || parentActivity.animationInProgress || parentActivity.startedTracking) { if (parentActivity == null || parentActivity.checkTransitionAnimation() || parentActivity.animationInProgress || parentActivity.startedTracking) {
return; return;
} }
if (visibleDialog != null && visibleDialog.isShowing()) { try {
if (visibleDialog != null) {
visibleDialog.dismiss(); visibleDialog.dismiss();
visibleDialog = null; visibleDialog = null;
} }
} catch (Exception e) {
FileLog.e("tmessages", e);
}
visibleDialog = builder.show(); visibleDialog = builder.show();
visibleDialog.setCanceledOnTouchOutside(true); visibleDialog.setCanceledOnTouchOutside(true);
visibleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { visibleDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

View File

@ -129,7 +129,7 @@ public class AvatarUpdater implements NotificationCenter.NotificationCenterDeleg
uploadingAvatar = Utilities.getCacheDir() + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg"; uploadingAvatar = Utilities.getCacheDir() + "/" + bigPhoto.location.volume_id + "_" + bigPhoto.location.local_id + ".jpg";
NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidUpload); NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidUpload);
NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload); NotificationCenter.getInstance().addObserver(AvatarUpdater.this, FileLoader.FileDidFailUpload);
FileLoader.getInstance().uploadFile(uploadingAvatar, null, null); FileLoader.getInstance().uploadFile(uploadingAvatar, false);
} }
} }
} }

View File

@ -0,0 +1,383 @@
/*
* Copyright 2012 Lars Werkman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.telegram.ui.Views;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import org.telegram.messenger.Utilities;
public class ColorPickerView extends View {
private static final String STATE_PARENT = "parent";
private static final String STATE_ANGLE = "angle";
private static final String STATE_OLD_COLOR = "color";
private static final String STATE_SHOW_OLD_COLOR = "showColor";
private static final int[] COLORS = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFFFF, 0xFFFFFF00, 0xFFFF0000 };
private Paint mColorWheelPaint;
private Paint mPointerHaloPaint;
private Paint mPointerColor;
private int mColorWheelThickness;
private int mColorWheelRadius;
private int mPreferredColorWheelRadius;
private int mColorCenterRadius;
private int mPreferredColorCenterRadius;
private int mColorCenterHaloRadius;
private int mPreferredColorCenterHaloRadius;
private int mColorPointerRadius;
private int mColorPointerHaloRadius;
private RectF mColorWheelRectangle = new RectF();
private RectF mCenterRectangle = new RectF();
private boolean mUserIsMovingPointer = false;
private int mCenterOldColor;
private boolean mShowCenterOldColor;
private int mCenterNewColor;
private float mTranslationOffset;
private float mSlopX;
private float mSlopY;
private float mAngle;
private Paint mCenterOldPaint;
private Paint mCenterNewPaint;
private Paint mCenterHaloPaint;
private float[] mHSV = new float[3];
private OnColorChangedListener onColorChangedListener;
private OnColorSelectedListener onColorSelectedListener;
private int oldChangedListenerColor;
private int oldSelectedListenerColor;
public ColorPickerView(Context context) {
super(context);
init(null, 0);
}
public ColorPickerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public ColorPickerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
public interface OnColorChangedListener {
public void onColorChanged(int color);
}
public interface OnColorSelectedListener {
public void onColorSelected(int color);
}
public void setOnColorChangedListener(OnColorChangedListener listener) {
this.onColorChangedListener = listener;
}
public void setOnColorSelectedListener(OnColorSelectedListener listener) {
this.onColorSelectedListener = listener;
}
private void init(AttributeSet attrs, int defStyle) {
mColorWheelThickness = Utilities.dp(8);
mColorWheelRadius = Utilities.dp(124);
mPreferredColorWheelRadius = mColorWheelRadius;
mColorCenterRadius = Utilities.dp(54);
mPreferredColorCenterRadius = mColorCenterRadius;
mColorCenterHaloRadius = Utilities.dp(60);
mPreferredColorCenterHaloRadius = mColorCenterHaloRadius;
mColorPointerRadius = Utilities.dp(14);
mColorPointerHaloRadius = Utilities.dp(18);
mAngle = (float) (-Math.PI / 2);
Shader s = new SweepGradient(0, 0, COLORS, null);
mColorWheelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mColorWheelPaint.setShader(s);
mColorWheelPaint.setStyle(Paint.Style.STROKE);
mColorWheelPaint.setStrokeWidth(mColorWheelThickness);
mPointerHaloPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPointerHaloPaint.setColor(Color.BLACK);
mPointerHaloPaint.setAlpha(0x50);
mPointerColor = new Paint(Paint.ANTI_ALIAS_FLAG);
mPointerColor.setColor(calculateColor(mAngle));
mCenterNewPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterNewPaint.setColor(calculateColor(mAngle));
mCenterNewPaint.setStyle(Paint.Style.FILL);
mCenterOldPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterOldPaint.setColor(calculateColor(mAngle));
mCenterOldPaint.setStyle(Paint.Style.FILL);
mCenterHaloPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterHaloPaint.setColor(Color.BLACK);
mCenterHaloPaint.setAlpha(0x00);
mCenterNewColor = calculateColor(mAngle);
mCenterOldColor = calculateColor(mAngle);
mShowCenterOldColor = true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.translate(mTranslationOffset, mTranslationOffset);
canvas.drawOval(mColorWheelRectangle, mColorWheelPaint);
float[] pointerPosition = calculatePointerPosition(mAngle);
canvas.drawCircle(pointerPosition[0], pointerPosition[1], mColorPointerHaloRadius, mPointerHaloPaint);
canvas.drawCircle(pointerPosition[0], pointerPosition[1], mColorPointerRadius, mPointerColor);
canvas.drawCircle(0, 0, mColorCenterHaloRadius, mCenterHaloPaint);
if (mShowCenterOldColor) {
canvas.drawArc(mCenterRectangle, 90, 180, true, mCenterOldPaint);
canvas.drawArc(mCenterRectangle, 270, 180, true, mCenterNewPaint);
} else {
canvas.drawArc(mCenterRectangle, 0, 360, true, mCenterNewPaint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int intrinsicSize = 2 * (mPreferredColorWheelRadius + mColorPointerHaloRadius);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(intrinsicSize, widthSize);
} else {
width = intrinsicSize;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(intrinsicSize, heightSize);
} else {
height = intrinsicSize;
}
int min = Math.min(width, height);
setMeasuredDimension(min, min);
mTranslationOffset = min * 0.5f;
mColorWheelRadius = min / 2 - mColorWheelThickness - mColorPointerHaloRadius;
mColorWheelRectangle.set(-mColorWheelRadius, -mColorWheelRadius, mColorWheelRadius, mColorWheelRadius);
mColorCenterRadius = (int) ((float) mPreferredColorCenterRadius * ((float) mColorWheelRadius / (float) mPreferredColorWheelRadius));
mColorCenterHaloRadius = (int) ((float) mPreferredColorCenterHaloRadius * ((float) mColorWheelRadius / (float) mPreferredColorWheelRadius));
mCenterRectangle.set(-mColorCenterRadius, -mColorCenterRadius, mColorCenterRadius, mColorCenterRadius);
}
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int calculateColor(float angle) {
float unit = (float) (angle / (2 * Math.PI));
if (unit < 0) {
unit += 1;
}
if (unit <= 0) {
return COLORS[0];
}
if (unit >= 1) {
return COLORS[COLORS.length - 1];
}
float p = unit * (COLORS.length - 1);
int i = (int) p;
p -= i;
int c0 = COLORS[i];
int c1 = COLORS[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
public int getColor() {
return mCenterNewColor;
}
public void setColor(int color) {
mAngle = colorToAngle(color);
mPointerColor.setColor(calculateColor(mAngle));
mCenterNewPaint.setColor(calculateColor(mAngle));
invalidate();
}
private float colorToAngle(int color) {
float[] colors = new float[3];
Color.colorToHSV(color, colors);
return (float) Math.toRadians(-colors[0]);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
getParent().requestDisallowInterceptTouchEvent(true);
float x = event.getX() - mTranslationOffset;
float y = event.getY() - mTranslationOffset;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float[] pointerPosition = calculatePointerPosition(mAngle);
if (x >= (pointerPosition[0] - mColorPointerHaloRadius) && x <= (pointerPosition[0] + mColorPointerHaloRadius) && y >= (pointerPosition[1] - mColorPointerHaloRadius) && y <= (pointerPosition[1] + mColorPointerHaloRadius)) {
mSlopX = x - pointerPosition[0];
mSlopY = y - pointerPosition[1];
mUserIsMovingPointer = true;
invalidate();
} else if (x >= -mColorCenterRadius && x <= mColorCenterRadius && y >= -mColorCenterRadius && y <= mColorCenterRadius && mShowCenterOldColor) {
mCenterHaloPaint.setAlpha(0x50);
setColor(getOldCenterColor());
invalidate();
} else {
getParent().requestDisallowInterceptTouchEvent(false);
return false;
}
break;
case MotionEvent.ACTION_MOVE:
if (mUserIsMovingPointer) {
mAngle = (float) java.lang.Math.atan2(y - mSlopY, x - mSlopX);
mPointerColor.setColor(calculateColor(mAngle));
setNewCenterColor(mCenterNewColor = calculateColor(mAngle));
invalidate();
} else {
getParent().requestDisallowInterceptTouchEvent(false);
return false;
}
break;
case MotionEvent.ACTION_UP:
mUserIsMovingPointer = false;
mCenterHaloPaint.setAlpha(0x00);
if (onColorSelectedListener != null && mCenterNewColor != oldSelectedListenerColor) {
onColorSelectedListener.onColorSelected(mCenterNewColor);
oldSelectedListenerColor = mCenterNewColor;
}
invalidate();
break;
case MotionEvent.ACTION_CANCEL:
if (onColorSelectedListener != null && mCenterNewColor != oldSelectedListenerColor) {
onColorSelectedListener.onColorSelected(mCenterNewColor);
oldSelectedListenerColor = mCenterNewColor;
}
break;
}
return true;
}
private float[] calculatePointerPosition(float angle) {
float x = (float) (mColorWheelRadius * Math.cos(angle));
float y = (float) (mColorWheelRadius * Math.sin(angle));
return new float[] { x, y };
}
public void setNewCenterColor(int color) {
mCenterNewColor = color;
mCenterNewPaint.setColor(color);
if (mCenterOldColor == 0) {
mCenterOldColor = color;
mCenterOldPaint.setColor(color);
}
if (onColorChangedListener != null && color != oldChangedListenerColor ) {
onColorChangedListener.onColorChanged(color);
oldChangedListenerColor = color;
}
invalidate();
}
public void setOldCenterColor(int color) {
mCenterOldColor = color;
mCenterOldPaint.setColor(color);
invalidate();
}
public int getOldCenterColor() {
return mCenterOldColor;
}
public void setShowOldCenterColor(boolean show) {
mShowCenterOldColor = show;
invalidate();
}
public boolean getShowOldCenterColor() {
return mShowCenterOldColor;
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle state = new Bundle();
state.putParcelable(STATE_PARENT, superState);
state.putFloat(STATE_ANGLE, mAngle);
state.putInt(STATE_OLD_COLOR, mCenterOldColor);
state.putBoolean(STATE_SHOW_OLD_COLOR, mShowCenterOldColor);
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
Bundle savedState = (Bundle) state;
Parcelable superState = savedState.getParcelable(STATE_PARENT);
super.onRestoreInstanceState(superState);
mAngle = savedState.getFloat(STATE_ANGLE);
setOldCenterColor(savedState.getInt(STATE_OLD_COLOR));
mShowCenterOldColor = savedState.getBoolean(STATE_SHOW_OLD_COLOR);
int currentColor = calculateColor(mAngle);
mPointerColor.setColor(currentColor);
setNewCenterColor(currentColor);
}
}

View File

@ -9,6 +9,7 @@
package org.telegram.ui.Views; package org.telegram.ui.Views;
import android.content.Context; import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable;
import android.support.v4.view.PagerAdapter; import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager;
@ -100,14 +101,23 @@ public class EmojiView extends LinearLayout {
} }
private void init() { private void init() {
setOrientation(1); setOrientation(LinearLayout.VERTICAL);
for (int i = 0; ; i++) { for (int i = 0; i < Emoji.data.length; i++) {
if (i >= Emoji.data.length) { GridView gridView = new GridView(getContext());
gridView.setColumnWidth(Utilities.dpf(45.0f));
gridView.setNumColumns(-1);
views.add(gridView);
EmojiGridAdapter localEmojiGridAdapter = new EmojiGridAdapter(Emoji.data[i]);
gridView.setAdapter(localEmojiGridAdapter);
adapters.add(localEmojiGridAdapter);
}
setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { -14145496, -16777216 })); setBackgroundDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { -14145496, -16777216 }));
pager = new ViewPager(getContext()); pager = new ViewPager(getContext());
pager.setAdapter(new EmojiPagesAdapter()); pager.setAdapter(new EmojiPagesAdapter());
PagerSlidingTabStrip tabs = new PagerSlidingTabStrip(getContext()); PagerSlidingTabStrip tabs = new PagerSlidingTabStrip(getContext());
tabs.setViewPager(this.pager); tabs.setViewPager(pager);
tabs.setShouldExpand(true); tabs.setShouldExpand(true);
tabs.setIndicatorColor(0xff33b5e5); tabs.setIndicatorColor(0xff33b5e5);
tabs.setIndicatorHeight(Utilities.dpf(2.0f)); tabs.setIndicatorHeight(Utilities.dpf(2.0f));
@ -115,47 +125,34 @@ public class EmojiView extends LinearLayout {
tabs.setUnderlineColor(1711276032); tabs.setUnderlineColor(1711276032);
tabs.setTabBackground(0); tabs.setTabBackground(0);
LinearLayout localLinearLayout = new LinearLayout(getContext()); LinearLayout localLinearLayout = new LinearLayout(getContext());
localLinearLayout.setOrientation(0); localLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
localLinearLayout.addView(tabs, new LinearLayout.LayoutParams(-1, -1, 1.0F)); localLinearLayout.addView(tabs, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
ImageView localImageView = new ImageView(getContext()); ImageView localImageView = new ImageView(getContext());
localImageView.setImageResource(R.drawable.ic_emoji_backspace); localImageView.setImageResource(R.drawable.ic_emoji_backspace);
localImageView.setScaleType(ImageView.ScaleType.CENTER); localImageView.setScaleType(ImageView.ScaleType.CENTER);
localImageView.setBackgroundResource(R.drawable.bg_emoji_bs); localImageView.setBackgroundResource(R.drawable.bg_emoji_bs);
localImageView.setOnClickListener(new View.OnClickListener() { localImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) { public void onClick(View view) {
if (EmojiView.this.listener != null) { if (EmojiView.this.listener != null) {
EmojiView.this.listener.onBackspace(); EmojiView.this.listener.onBackspace();
} }
} }
}); });
localImageView.setOnLongClickListener(new View.OnLongClickListener() { localLinearLayout.addView(localImageView, new LinearLayout.LayoutParams(Utilities.dpf(61.0f), LayoutParams.MATCH_PARENT));
public boolean onLongClick(View paramAnonymousView) { recentsWrap = new FrameLayout(getContext());
EmojiView.this.getContext().getSharedPreferences("emoji", 0).edit().clear().commit(); recentsWrap.addView(views.get(0));
return true;
}
});
localLinearLayout.addView(localImageView, new LinearLayout.LayoutParams(Utilities.dpf(61.0f), -1));
this.recentsWrap = new FrameLayout(getContext());
this.recentsWrap.addView(this.views.get(0));
TextView localTextView = new TextView(getContext()); TextView localTextView = new TextView(getContext());
localTextView.setText(LocaleController.getString("NoRecent", R.string.NoRecent)); localTextView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
localTextView.setTextSize(18.0f); localTextView.setTextSize(18.0f);
localTextView.setTextColor(-7829368); localTextView.setTextColor(-7829368);
localTextView.setGravity(17); localTextView.setGravity(17);
this.recentsWrap.addView(localTextView); recentsWrap.addView(localTextView);
this.views.get(0).setEmptyView(localTextView); views.get(0).setEmptyView(localTextView);
addView(localLinearLayout, new LinearLayout.LayoutParams(-1, Utilities.dpf(48.0f))); addView(localLinearLayout, new LinearLayout.LayoutParams(-1, Utilities.dpf(48.0f)));
addView(this.pager); addView(pager);
loadRecents(); loadRecents();
return; if (Emoji.data[0] == null || Emoji.data[0].length == 0) {
} pager.setCurrentItem(1);
GridView localGridView = new GridView(getContext());
localGridView.setColumnWidth(Utilities.dpf(45.0f));
localGridView.setNumColumns(-1);
EmojiGridAdapter localEmojiGridAdapter = new EmojiGridAdapter(Emoji.data[i]);
localGridView.setAdapter(localEmojiGridAdapter);
this.adapters.add(localEmojiGridAdapter);
this.views.add(localGridView);
} }
} }
@ -236,11 +233,11 @@ public class EmojiView extends LinearLayout {
} }
}; };
localObject.setOnClickListener(new View.OnClickListener() { localObject.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) { public void onClick(View view) {
if (EmojiView.this.listener != null) { if (EmojiView.this.listener != null) {
EmojiView.this.listener.onEmojiSelected(EmojiView.this.convert((Long)paramAnonymousView.getTag())); EmojiView.this.listener.onEmojiSelected(EmojiView.this.convert((Long)view.getTag()));
} }
EmojiView.this.addToRecent((Long)paramAnonymousView.getTag()); EmojiView.this.addToRecent((Long)view.getTag());
} }
}); });
localObject.setBackgroundResource(R.drawable.list_selector); localObject.setBackgroundResource(R.drawable.list_selector);
@ -251,6 +248,13 @@ public class EmojiView extends LinearLayout {
localObject.setTag(this.data[paramInt]); localObject.setTag(this.data[paramInt]);
return localObject; return localObject;
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }
private class EmojiPagesAdapter extends PagerAdapter implements PagerSlidingTabStrip.IconTabProvider { private class EmojiPagesAdapter extends PagerAdapter implements PagerSlidingTabStrip.IconTabProvider {
@ -290,6 +294,13 @@ public class EmojiView extends LinearLayout {
public boolean isViewFromObject(View paramView, Object paramObject) { public boolean isViewFromObject(View paramView, Object paramObject) {
return paramView == paramObject; return paramView == paramObject;
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }
public static abstract interface Listener { public static abstract interface Listener {

View File

@ -113,7 +113,7 @@ public class HorizontalListView extends AdapterView<ListAdapter> {
@Override @Override
public void setAdapter(ListAdapter adapter) { public void setAdapter(ListAdapter adapter) {
if(mAdapter != null) { if(mAdapter != null && mDataObserver != null) {
mAdapter.unregisterDataSetObserver(mDataObserver); mAdapter.unregisterDataSetObserver(mDataObserver);
} }
mAdapter = adapter; mAdapter = adapter;

View File

@ -17,6 +17,8 @@ import android.view.ViewGroup;
import android.widget.*; import android.widget.*;
import android.widget.AbsListView.OnScrollListener; import android.widget.AbsListView.OnScrollListener;
import org.telegram.messenger.FileLog;
public class PinnedHeaderListView extends ListView implements OnScrollListener, View.OnTouchListener { public class PinnedHeaderListView extends ListView implements OnScrollListener, View.OnTouchListener {
private OnScrollListener mOnScrollListener; private OnScrollListener mOnScrollListener;
@ -69,6 +71,9 @@ public class PinnedHeaderListView extends ListView implements OnScrollListener,
@Override @Override
public void setAdapter(ListAdapter adapter) { public void setAdapter(ListAdapter adapter) {
if (mAdapter == adapter) {
return;
}
mCurrentHeader = null; mCurrentHeader = null;
if (adapter instanceof PinnedSectionedHeaderAdapter) { if (adapter instanceof PinnedSectionedHeaderAdapter) {
mAdapter = (PinnedSectionedHeaderAdapter) adapter; mAdapter = (PinnedSectionedHeaderAdapter) adapter;
@ -80,14 +85,14 @@ public class PinnedHeaderListView extends ListView implements OnScrollListener,
@Override @Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mAdapter == null) {
return;
}
if (mOnScrollListener != null) { if (mOnScrollListener != null) {
mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
} }
if (mAdapter == null) {
return;
}
if (mAdapter == null || mAdapter.getCount() == 0 || !mShouldPin || (firstVisibleItem < getHeaderViewsCount())) { if (mAdapter.getCount() == 0 || !mShouldPin || (firstVisibleItem < getHeaderViewsCount())) {
mCurrentHeader = null; mCurrentHeader = null;
mHeaderOffset = 0.0f; mHeaderOffset = 0.0f;
for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) { for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) {
@ -131,9 +136,6 @@ public class PinnedHeaderListView extends ListView implements OnScrollListener,
@Override @Override
public void onScrollStateChanged(AbsListView view, int scrollState) { public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mAdapter == null) {
return;
}
if (mOnScrollListener != null) { if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(view, scrollState); mOnScrollListener.onScrollStateChanged(view, scrollState);
} }
@ -173,7 +175,11 @@ public class PinnedHeaderListView extends ListView implements OnScrollListener,
} else { } else {
heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
} }
try {
header.measure(widthSpec, heightSpec); header.measure(widthSpec, heightSpec);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight()); header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
} }
} }

View File

@ -8,6 +8,7 @@
package org.telegram.ui.Views; package org.telegram.ui.Views;
import android.database.DataSetObserver;
import android.util.SparseArray; import android.util.SparseArray;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -222,4 +223,11 @@ public abstract class SectionedBaseAdapter extends BaseFragmentAdapter implement
mSectionCount = getSectionCount(); mSectionCount = getSectionCount();
return mSectionCount; return mSectionCount;
} }
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
} }

View File

@ -9,8 +9,9 @@
package org.telegram.ui.Views; package org.telegram.ui.Views;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect; import android.graphics.Rect;
import android.util.Log; import android.graphics.drawable.Drawable;
import android.widget.RelativeLayout; import android.widget.RelativeLayout;
import org.telegram.messenger.Utilities; import org.telegram.messenger.Utilities;
@ -18,6 +19,7 @@ import org.telegram.messenger.Utilities;
public class SizeNotifierRelativeLayout extends RelativeLayout { public class SizeNotifierRelativeLayout extends RelativeLayout {
private Rect rect = new Rect(); private Rect rect = new Rect();
private Drawable backgroundDrawable;
public SizeNotifierRelativeLayoutDelegate delegate; public SizeNotifierRelativeLayoutDelegate delegate;
public abstract interface SizeNotifierRelativeLayoutDelegate { public abstract interface SizeNotifierRelativeLayoutDelegate {
@ -36,6 +38,14 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
public void setBackgroundImage(int resourceId) {
backgroundDrawable = getResources().getDrawable(resourceId);
}
public void setBackgroundImage(Drawable bitmap) {
backgroundDrawable = bitmap;
}
@Override @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) { protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b); super.onLayout(changed, l, t, r, b);
@ -46,4 +56,19 @@ public class SizeNotifierRelativeLayout extends RelativeLayout {
delegate.onSizeChanged(keyboardHeight); delegate.onSizeChanged(keyboardHeight);
} }
} }
@Override
protected void onDraw(Canvas canvas) {
if (backgroundDrawable != null) {
float scaleX = (float)Utilities.displaySize.x / (float)backgroundDrawable.getIntrinsicWidth();
float scaleY = (float)Utilities.displaySize.y / (float)backgroundDrawable.getIntrinsicHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int)Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
int height = (int)Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
int x = (Utilities.displaySize.x - width) / 2;
int y = (Utilities.displaySize.y - height) / 2;
backgroundDrawable.setBounds(x, y, x + width, y + height);
backgroundDrawable.draw(canvas);
}
}
} }

View File

@ -69,7 +69,6 @@
android:id="@+id/docs_item_thumb" android:id="@+id/docs_item_thumb"
android:layout_width="55dp" android:layout_width="55dp"
android:layout_height="42dp" android:layout_height="42dp"
android:scaleType="centerCrop"
android:layout_marginTop="11dp" android:layout_marginTop="11dp"
android:layout_gravity="top|right"/> android:layout_gravity="top|right"/>

View File

@ -21,8 +21,7 @@
<org.telegram.ui.Views.BackupImageView <org.telegram.ui.Views.BackupImageView
android:id="@+id/settings_avatar_image" android:id="@+id/settings_avatar_image"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"/>
android:src="@drawable/group_blue"/>
<ImageButton <ImageButton
android:id="@+id/settings_change_avatar_button" android:id="@+id/settings_change_avatar_button"

View File

@ -10,7 +10,6 @@
android:layout_width="50dp" android:layout_width="50dp"
android:layout_height="50dp" android:layout_height="50dp"
android:id="@+id/messages_list_row_avatar" android:id="@+id/messages_list_row_avatar"
android:contentDescription=""
android:layout_marginTop="8dp" android:layout_marginTop="8dp"
android:layout_gravity="top|right"/> android:layout_gravity="top|right"/>

View File

@ -22,7 +22,6 @@
<org.telegram.ui.Views.BackupImageView <org.telegram.ui.Views.BackupImageView
android:layout_width="64dp" android:layout_width="64dp"
android:layout_height="64dp" android:layout_height="64dp"
android:contentDescription=""
android:id="@+id/location_avatar_view" android:id="@+id/location_avatar_view"
android:layout_marginRight="12dp" android:layout_marginRight="12dp"
android:layout_marginTop="16dp" android:layout_marginTop="16dp"

View File

@ -5,17 +5,20 @@
android:id="@+id/container_view" android:id="@+id/container_view"
android:orientation="vertical"> android:orientation="vertical">
<FrameLayout android:layout_width="fill_parent" <FrameLayout
android:layout_width="fill_parent"
android:layout_height="0dp" android:layout_height="0dp"
android:layout_weight="1" android:layout_weight="1"
android:background="#ffffff"> android:background="#ffffff">
<org.telegram.ui.Views.BackupImageView android:layout_height="48dp" <org.telegram.ui.Views.BackupImageView
android:layout_height="48dp"
android:layout_width="48dp" android:layout_width="48dp"
android:id="@+id/avatar_image" android:id="@+id/avatar_image"
android:layout_gravity="right|top"/> android:layout_gravity="right|top"/>
<FrameLayout android:layout_width="fill_parent" <FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_marginLeft="40dp" android:layout_marginLeft="40dp"
android:orientation="vertical" android:orientation="vertical"
@ -23,7 +26,8 @@
android:layout_gravity="top|right" android:layout_gravity="top|right"
android:id="@+id/text_layout"> android:id="@+id/text_layout">
<TextView android:layout_height="wrap_content" <TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:gravity="right|center" android:gravity="right|center"
android:textSize="15dp" android:textSize="15dp"
@ -34,7 +38,8 @@
android:layout_gravity="top|right" android:layout_gravity="top|right"
android:singleLine="true"/> android:singleLine="true"/>
<TextView android:layout_height="wrap_content" <TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:gravity="right|center" android:gravity="right|center"
android:textColor="#000000" android:textColor="#000000"
@ -47,7 +52,8 @@
</FrameLayout> </FrameLayout>
<ImageView android:layout_height="40dp" <ImageView
android:layout_height="40dp"
android:layout_width="40dp" android:layout_width="40dp"
android:layout_gravity="left|center" android:layout_gravity="left|center"
android:src="@drawable/ic_profile_cross" android:src="@drawable/ic_profile_cross"

View File

@ -0,0 +1,41 @@
<!--
~ This is the source code of Telegram for Android v. 1.4.x.
~ It is licensed under GNU GPL v. 2 or later.
~ You should have received a copy of the license in this archive (see LICENSE).
~
~ Copyright Nikolai Kudashov, 2013-2014.
-->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_gravity="top">
<FrameLayout
android:id="@+id/settings_color"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginLeft="14dp"
android:layout_marginRight="8dp"
android:layout_gravity="center_vertical"/>
<TextView
android:textSize="18dp"
android:textColor="#333333"
android:id="@+id/settings_row_text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:gravity="center_vertical|right"
android:layout_gravity="top|right"/>
<View
android:background="@color/divider"
android:layout_width="fill_parent"
android:layout_height="1px"
android:layout_gravity="bottom"
android:id="@+id/settings_row_divider"/>
</FrameLayout>

View File

@ -37,7 +37,6 @@
android:layout_width="64dp" android:layout_width="64dp"
android:layout_height="64dp" android:layout_height="64dp"
android:layout_marginTop="5dp" android:layout_marginTop="5dp"
android:scaleType="fitCenter"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>
</LinearLayout> </LinearLayout>

View File

@ -14,7 +14,6 @@
android:layout_height="42dp" android:layout_height="42dp"
android:layout_marginLeft="6dp" android:layout_marginLeft="6dp"
android:id="@+id/chat_group_avatar_image" android:id="@+id/chat_group_avatar_image"
android:scaleType="fitCenter"
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginRight="4dp" android:layout_marginRight="4dp"
android:layout_gravity="bottom"/> android:layout_gravity="bottom"/>
@ -34,7 +33,8 @@
android:id="@+id/shared_layout" android:id="@+id/shared_layout"
android:layout_weight="1"> android:layout_weight="1">
<org.telegram.ui.Views.BackupImageView android:layout_height="42dp" <org.telegram.ui.Views.BackupImageView
android:layout_height="42dp"
android:layout_width="42dp" android:layout_width="42dp"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>

View File

@ -13,7 +13,6 @@
android:layout_height="42dp" android:layout_height="42dp"
android:layout_marginLeft="6dp" android:layout_marginLeft="6dp"
android:id="@+id/chat_group_avatar_image" android:id="@+id/chat_group_avatar_image"
android:scaleType="fitCenter"
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_marginRight="4dp" android:layout_marginRight="4dp"
android:layout_gravity="bottom"/> android:layout_gravity="bottom"/>
@ -38,8 +37,6 @@
android:layout_width="42dp" android:layout_width="42dp"
android:layout_height="42dp" android:layout_height="42dp"
android:background="#40b7c9d7" android:background="#40b7c9d7"
android:src="@drawable/doc_blue"
android:scaleType="center"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>
<org.telegram.ui.Views.TightTextView <org.telegram.ui.Views.TightTextView

View File

@ -14,7 +14,6 @@
android:layout_height="42dp" android:layout_height="42dp"
android:layout_marginLeft="6dp" android:layout_marginLeft="6dp"
android:id="@+id/chat_group_avatar_image" android:id="@+id/chat_group_avatar_image"
android:scaleType="fitCenter"
android:layout_marginBottom="2dp" android:layout_marginBottom="2dp"
android:layout_gravity="bottom"/> android:layout_gravity="bottom"/>
@ -31,7 +30,6 @@
android:layout_width="100dp" android:layout_width="100dp"
android:layout_margin="6dp" android:layout_margin="6dp"
android:layout_gravity="top" android:layout_gravity="top"
android:scaleType="centerCrop"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>
<LinearLayout <LinearLayout

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentRight="true"> android:layout_alignParentRight="true">

View File

@ -21,7 +21,8 @@
android:id="@+id/shared_layout" android:id="@+id/shared_layout"
android:layout_weight="1"> android:layout_weight="1">
<org.telegram.ui.Views.BackupImageView android:layout_height="42dp" <org.telegram.ui.Views.BackupImageView
android:layout_height="42dp"
android:layout_width="42dp" android:layout_width="42dp"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>
@ -57,18 +58,21 @@
</FrameLayout> </FrameLayout>
<FrameLayout android:layout_width="wrap_content" <FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="8dp" android:layout_marginLeft="8dp"
android:layout_gravity="top" android:layout_gravity="top"
android:id="@+id/add_contact_view"> android:id="@+id/add_contact_view">
<FrameLayout android:layout_height="54dp" <FrameLayout
android:layout_height="54dp"
android:layout_width="1dp" android:layout_width="1dp"
android:background="#e8e8e8" android:background="#e8e8e8"
android:paddingRight="8dp"/> android:paddingRight="8dp"/>
<ImageView android:layout_width="38dp" <ImageView
android:layout_width="38dp"
android:layout_height="54dp" android:layout_height="54dp"
android:src="@drawable/ic_ab_add_member" android:src="@drawable/ic_ab_add_member"
android:scaleType="center" android:scaleType="center"
@ -79,4 +83,5 @@
</FrameLayout> </FrameLayout>
</LinearLayout> </LinearLayout>
</FrameLayout> </FrameLayout>

View File

@ -29,7 +29,6 @@
android:layout_height="42dp" android:layout_height="42dp"
android:background="#40b7c9d7" android:background="#40b7c9d7"
android:src="@drawable/doc_blue" android:src="@drawable/doc_blue"
android:scaleType="center"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>
<TextView <TextView

View File

@ -22,7 +22,6 @@
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_margin="6dp" android:layout_margin="6dp"
android:layout_gravity="top" android:layout_gravity="top"
android:scaleType="centerCrop"
android:minHeight="100dp" android:minHeight="100dp"
android:minWidth="100dp" android:minWidth="100dp"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>

View File

@ -4,12 +4,6 @@
android:layout_height="match_parent" android:layout_height="match_parent"
android:id="@+id/chat_layout"> android:id="@+id/chat_layout">
<ImageView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:id="@+id/background_image"
android:scaleType="centerCrop"/>
<org.telegram.ui.Views.FrameLayoutFixed <org.telegram.ui.Views.FrameLayoutFixed
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_width="fill_parent"

View File

@ -16,19 +16,22 @@
android:layout_gravity="top|right" android:layout_gravity="top|right"
android:id="@+id/chat_bubble_layout"> android:id="@+id/chat_bubble_layout">
<FrameLayout android:layout_width="wrap_content" <FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="8dp" android:layout_marginRight="8dp"
android:layout_gravity="top" android:layout_gravity="top"
android:id="@+id/add_contact_view"> android:id="@+id/add_contact_view">
<FrameLayout android:layout_height="54dp" <FrameLayout
android:layout_height="54dp"
android:layout_width="1dp" android:layout_width="1dp"
android:background="#aa70b15c" android:background="#aa70b15c"
android:paddingLeft="8dp" android:paddingLeft="8dp"
android:layout_gravity="right"/> android:layout_gravity="right"/>
<ImageView android:layout_width="40dp" <ImageView
android:layout_width="40dp"
android:layout_height="54dp" android:layout_height="54dp"
android:src="@drawable/ic_ab_add_member" android:src="@drawable/ic_ab_add_member"
android:scaleType="center" android:scaleType="center"
@ -38,16 +41,19 @@
</FrameLayout> </FrameLayout>
<FrameLayout android:layout_height="58dp" <FrameLayout
android:layout_height="58dp"
android:layout_width="0dp" android:layout_width="0dp"
android:id="@+id/shared_layout" android:id="@+id/shared_layout"
android:layout_weight="1"> android:layout_weight="1">
<org.telegram.ui.Views.BackupImageView android:layout_height="42dp" <org.telegram.ui.Views.BackupImageView
android:layout_height="42dp"
android:layout_width="42dp" android:layout_width="42dp"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>
<TextView android:layout_height="wrap_content" <TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:scrollHorizontally="true" android:scrollHorizontally="true"
android:paddingLeft="51dp" android:paddingLeft="51dp"
@ -59,7 +65,8 @@
android:ellipsize="end" android:ellipsize="end"
android:id="@+id/chat_user_group_name"/> android:id="@+id/chat_user_group_name"/>
<TextView android:layout_height="wrap_content" <TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:paddingLeft="51dp" android:paddingLeft="51dp"
android:layout_marginTop="20dp" android:layout_marginTop="20dp"
@ -68,7 +75,8 @@
android:maxLines="1" android:maxLines="1"
android:id="@+id/phone_text_view"/> android:id="@+id/phone_text_view"/>
<LinearLayout android:layout_width="wrap_content" <LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/chat_time_layout" android:id="@+id/chat_time_layout"
android:layout_gravity="bottom|right"> android:layout_gravity="bottom|right">

View File

@ -80,8 +80,6 @@
android:layout_width="42dp" android:layout_width="42dp"
android:layout_height="42dp" android:layout_height="42dp"
android:background="#408ed057" android:background="#408ed057"
android:src="@drawable/doc_green"
android:scaleType="center"
android:id="@+id/contact_avatar"/> android:id="@+id/contact_avatar"/>
<org.telegram.ui.Views.TightTextView <org.telegram.ui.Views.TightTextView

View File

@ -39,7 +39,6 @@
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_margin="6dp" android:layout_margin="6dp"
android:layout_gravity="top" android:layout_gravity="top"
android:scaleType="centerCrop"
android:minHeight="100dp" android:minHeight="100dp"
android:minWidth="100dp" android:minWidth="100dp"
android:id="@+id/chat_photo_image"/> android:id="@+id/chat_photo_image"/>

View File

@ -59,7 +59,6 @@
android:id="@+id/docs_item_thumb" android:id="@+id/docs_item_thumb"
android:layout_width="55dp" android:layout_width="55dp"
android:layout_height="42dp" android:layout_height="42dp"
android:scaleType="centerCrop"
android:layout_marginTop="11dp" android:layout_marginTop="11dp"
android:layout_gravity="top|left"/> android:layout_gravity="top|left"/>

View File

@ -21,8 +21,7 @@
<org.telegram.ui.Views.BackupImageView <org.telegram.ui.Views.BackupImageView
android:id="@+id/settings_avatar_image" android:id="@+id/settings_avatar_image"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"/>
android:src="@drawable/group_blue"/>
<ImageButton <ImageButton
android:id="@+id/settings_change_avatar_button" android:id="@+id/settings_change_avatar_button"

Some files were not shown because too many files have changed in this diff Show More